Bug 974335 - Refactor Qt Widget Backend implementation. Qt Only changes NPDB. r=romaxa
authorOleg Romashin <romaxa@gmail.com>
Thu, 20 Feb 2014 18:09:02 -0800
changeset 169797 c5953f75569b803a730ec277b1afca9ff9a6868f
parent 169796 acab9b9fc4da4b25bc47ea4a9c1f6418812c921d
child 169798 8db4d719f5f853db811be590f262acfc356cfb0f
push id26266
push usercbook@mozilla.com
push dateFri, 21 Feb 2014 12:03:53 +0000
treeherdermozilla-central@2d935f3e9587 [default view] [failures only]
perfherder[talos] [build metrics] [platform microbench] (compared to previous push)
reviewersromaxa
bugs974335
milestone30.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 974335 - Refactor Qt Widget Backend implementation. Qt Only changes NPDB. r=romaxa
dom/plugins/test/testplugin/nptest_qt.cpp
dom/src/geolocation/nsGeolocation.cpp
dom/system/moz.build
dom/system/qt/Makefile.in
dom/system/qt/QTMLocationProvider.cpp
dom/system/qt/QTMLocationProvider.h
dom/system/qt/QtHapticFeedback.cpp
dom/system/qt/QtHapticFeedback.h
dom/system/qt/moz.build
dom/system/unix/Makefile.in
dom/system/unix/QTMLocationProvider.cpp
dom/system/unix/QTMLocationProvider.h
dom/system/unix/moz.build
dom/system/unix/nsHapticFeedback.cpp
dom/system/unix/nsHapticFeedback.h
gfx/cairo/cairo/src/cairo-qt-surface.cpp
gfx/thebes/gfxQtNativeRenderer.cpp
gfx/thebes/gfxQtNativeRenderer.h
gfx/thebes/gfxQtPlatform.cpp
gfx/thebes/gfxQtPlatform.h
image/decoders/icon/qt/nsIconChannel.cpp
ipc/chromium/src/base/message_pump_qt.cc
netwerk/base/src/nsAutodialQt.cpp
toolkit/components/remote/nsQtRemoteService.cpp
toolkit/components/remote/nsQtRemoteService.h
toolkit/xre/nsAppRunner.cpp
toolkit/xre/nsQAppInstance.cpp
toolkit/xre/nsQAppInstance.h
widget/qt/Makefile.in
widget/qt/faststartupqt/Makefile.in
widget/qt/faststartupqt/moz.build
widget/qt/faststartupqt/mozqwidgetfast.cpp
widget/qt/faststartupqt/mozqwidgetfast.h
widget/qt/faststartupqt/nsFastStartupQt.cpp
widget/qt/faststartupqt/nsFastStartupQt.h
widget/qt/moz.build
widget/qt/mozSwipeGesture.cpp
widget/qt/mozSwipeGesture.h
widget/qt/moziqwidget.h
widget/qt/mozqglwidgetwrapper.cpp
widget/qt/mozqglwidgetwrapper.h
widget/qt/mozqorientationsensorfilter.cpp
widget/qt/mozqorientationsensorfilter.h
widget/qt/mozqwidget.cpp
widget/qt/mozqwidget.h
widget/qt/nsAppShell.cpp
widget/qt/nsBidiKeyboard.cpp
widget/qt/nsClipboard.cpp
widget/qt/nsCommonWidget.cpp
widget/qt/nsCommonWidget.h
widget/qt/nsDragService.cpp
widget/qt/nsDragService.h
widget/qt/nsFilePicker.cpp
widget/qt/nsFilePicker.h
widget/qt/nsLookAndFeel.cpp
widget/qt/nsLookAndFeel.h
widget/qt/nsMFilePicker.cpp
widget/qt/nsMFilePicker.h
widget/qt/nsNativeThemeQt.cpp
widget/qt/nsNativeThemeQt.h
widget/qt/nsQtKeyUtils.cpp
widget/qt/nsScreenManagerQt.cpp
widget/qt/nsScreenManagerQt.h
widget/qt/nsScreenQt.cpp
widget/qt/nsScreenQt.h
widget/qt/nsSound.cpp
widget/qt/nsSound.h
widget/qt/nsWidgetFactory.cpp
widget/qt/nsWindow.cpp
widget/qt/nsWindow.h
--- a/dom/plugins/test/testplugin/nptest_qt.cpp
+++ b/dom/plugins/test/testplugin/nptest_qt.cpp
@@ -25,30 +25,20 @@
  * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  * 
  * Contributor(s):
  *   Josh Aas <josh@mozilla.com>
  * 
  * ***** END LICENSE BLOCK ***** */
-#include <QWidget>
-#include <QPainter>
-
 #include "nptest_platform.h"
 #include "npapi.h"
 
-struct _PlatformData {
-#ifdef MOZ_X11
-  Display* display;
-  Visual* visual;
-  Colormap colormap;
-#endif
-};
- using namespace std;
+using namespace std;
 
 bool
 pluginSupportsWindowMode()
 {
   return false;
 }
 
 bool
@@ -61,34 +51,18 @@ bool
 pluginSupportsAsyncBitmapDrawing()
 {
   return false;
 }
 
 NPError
 pluginInstanceInit(InstanceData* instanceData)
 {
-#ifdef MOZ_X11
-  instanceData->platformData = static_cast<PlatformData*>
-    (NPN_MemAlloc(sizeof(PlatformData)));
-  if (!instanceData->platformData){
-    //printf("NPERR_OUT_OF_MEMORY_ERROR\n");
-    return NPERR_OUT_OF_MEMORY_ERROR;
-  }
-
-  instanceData->platformData->display = nullptr;
-  instanceData->platformData->visual = nullptr;
-  instanceData->platformData->colormap = None;
-
-  return NPERR_NO_ERROR;
-#else
   printf("NPERR_INCOMPATIBLE_VERSION_ERROR\n");
   return NPERR_INCOMPATIBLE_VERSION_ERROR;
-#endif
-  return NPERR_NO_ERROR;
 }
 
 void
 pluginInstanceShutdown(InstanceData* instanceData)
 {
   NPN_MemFree(instanceData->platformData);
   instanceData->platformData = 0;
 }
@@ -100,112 +74,19 @@ pluginDoSetWindow(InstanceData* instance
 }
 
 void
 pluginWidgetInit(InstanceData* instanceData, void* oldWindow)
 {
   // XXX nothing here yet since we don't support windowed plugins
 }
 
-static void
-pluginDrawWindow(InstanceData* instanceData, void* event)
-{
-  NPWindow& window = instanceData->window;
-  // When we have a widget, window.x/y are meaningless since our
-  // widget is always positioned correctly and we just draw into it at 0,0
-  int x = instanceData->hasWidget ? 0 : window.x;
-  int y = instanceData->hasWidget ? 0 : window.y;
-  int width = window.width;
-  int height = window.height;
-
-#ifdef MOZ_X11
-  XEvent* nsEvent = (XEvent*)event;
-  const XGraphicsExposeEvent& expose = nsEvent->xgraphicsexpose;
-
-  QColor drawColor((QColor)instanceData->scriptableObject->drawColor);//QRgb qRgba ( int r, int g, int b, int a )
-#ifdef Q_WS_X11
-  QPixmap pixmap = QPixmap::fromX11Pixmap(expose.drawable, QPixmap::ExplicitlyShared);
-
-  QRect exposeRect(expose.x, expose.y, expose.width, expose.height);
-  if (instanceData->scriptableObject->drawMode == DM_SOLID_COLOR) {
-    //printf("Drawing Solid\n");
-    // drawing a solid color for reftests
-    QPainter painter(&pixmap);
-    painter.fillRect(exposeRect, drawColor);
-    notifyDidPaint(instanceData);
-    return;
-
-  }
-#endif
-#endif
-
-  NPP npp = instanceData->npp;
-  if (!npp)
-    return;
-
-  QString text (NPN_UserAgent(npp));
-  if (text.isEmpty())
-    return;
-
-#ifdef MOZ_X11
-#ifdef Q_WS_X11
-  //printf("Drawing Default\n");
-  // drawing a solid color for reftests
-  QColor color;
-  QPainter painter(&pixmap);
-  QRect theRect(x, y, width, height);
-  QRect clipRect(QPoint(window.clipRect.left, window.clipRect.top),
-                 QPoint(window.clipRect.right, window.clipRect.bottom));
-  painter.setClipRect(clipRect);
-  painter.fillRect(theRect, QColor(128,128,128,255));
-  painter.drawRect(theRect);
-  painter.drawText(QRect(theRect), Qt::AlignCenter, text);
-  notifyDidPaint(instanceData);
-#endif
-#endif
-  return;
-}
-
 int16_t
 pluginHandleEvent(InstanceData* instanceData, void* event)
 {
-#ifdef MOZ_X11
-  XEvent* nsEvent = (XEvent*)event;
-  //printf("\nEvent Type %d\n", nsEvent->type);
-  switch (nsEvent->type) {
-  case GraphicsExpose: {
-    //printf("GraphicsExpose\n");
-
-    pluginDrawWindow(instanceData, event);
-    break;
-  }
-  case MotionNotify: {
-    //printf("MotionNotify\n");
-    XMotionEvent* motion = &nsEvent->xmotion;
-    instanceData->lastMouseX = motion->x;
-    instanceData->lastMouseY = motion->y;
-    break;
-  }
-  case ButtonPress:{
-    ////printf("ButtonPress\n");
-    break;
-  }
-  case ButtonRelease: {
-    //printf("ButtonRelease\n");
-    XButtonEvent* button = &nsEvent->xbutton;
-    instanceData->lastMouseX = button->x;
-    instanceData->lastMouseY = button->y;
-    instanceData->mouseUpEventCount++;
-    break;
-  }
-  default:
-    break;
-  }
-#endif
-
   return 0;
 }
 
 int32_t pluginGetEdge(InstanceData* instanceData, RectEdge edge)
 {
   // XXX nothing here yet since we don't support windowed plugins
   return NPTEST_INT32_ERROR;
 }
--- a/dom/src/geolocation/nsGeolocation.cpp
+++ b/dom/src/geolocation/nsGeolocation.cpp
@@ -23,17 +23,17 @@
 #include "mozilla/unused.h"
 #include "mozilla/Preferences.h"
 #include "mozilla/ClearOnShutdown.h"
 #include "PCOMContentPermissionRequestChild.h"
 #include "mozilla/dom/PermissionMessageUtils.h"
 
 class nsIPrincipal;
 
-#ifdef MOZ_ENABLE_QTMOBILITY
+#ifdef MOZ_ENABLE_QT5GEOPOSITION
 #include "QTMLocationProvider.h"
 #endif
 
 #ifdef MOZ_WIDGET_ANDROID
 #include "AndroidLocationProvider.h"
 #endif
 
 #ifdef MOZ_WIDGET_GONK
@@ -662,17 +662,17 @@ nsresult nsGeolocationService::Init()
   nsCOMPtr<nsIObserverService> obs = services::GetObserverService();
   if (!obs) {
     return NS_ERROR_FAILURE;
   }
 
   obs->AddObserver(this, "quit-application", false);
   obs->AddObserver(this, "mozsettings-changed", false);
 
-#ifdef MOZ_ENABLE_QTMOBILITY
+#ifdef MOZ_ENABLE_QT5GEOPOSITION
   mProvider = new QTMLocationProvider();
 #endif
 
 #ifdef MOZ_WIDGET_ANDROID
   mProvider = new AndroidLocationProvider();
 #endif
 
 #ifdef MOZ_WIDGET_GONK
--- a/dom/system/moz.build
+++ b/dom/system/moz.build
@@ -1,18 +1,18 @@
 # -*- Mode: python; c-basic-offset: 4; indent-tabs-mode: nil; tab-width: 40 -*-
 # vim: set filetype=python:
 # 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/.
 
 toolkit = CONFIG['MOZ_WIDGET_TOOLKIT']
 
-if toolkit in ('qt', 'gtk2', 'gtk3'):
-    DIRS += ['unix']
+if toolkit in ('qt'):
+    DIRS += ['qt']
 elif toolkit == 'windows':
     DIRS += ['windows']
 elif toolkit == 'cocoa':
     DIRS += ['mac']
 elif toolkit == 'android':
     DIRS += ['android']
 elif toolkit == 'gonk':
     DIRS += ['gonk']
rename from dom/system/unix/Makefile.in
rename to dom/system/qt/Makefile.in
rename from dom/system/unix/QTMLocationProvider.cpp
rename to dom/system/qt/QTMLocationProvider.cpp
--- a/dom/system/unix/QTMLocationProvider.cpp
+++ b/dom/system/qt/QTMLocationProvider.cpp
@@ -7,16 +7,19 @@
 #include "nsGeoPosition.h"
 
 using namespace mozilla;
 
 NS_IMPL_ISUPPORTS1(QTMLocationProvider, nsIGeolocationProvider)
 
 QTMLocationProvider::QTMLocationProvider()
 {
+    if (QMetaType::type("QGeoPositionInfo") == QMetaType::UnknownType) {
+        qRegisterMetaType<QGeoPositionInfo>("QGeoPositionInfo");
+    }
     mLocation = QGeoPositionInfoSource::createDefaultSource(this);
     if (mLocation)
         connect(mLocation, SIGNAL(positionUpdated(QGeoPositionInfo)), this, SLOT(positionUpdated(QGeoPositionInfo)));
 }
 
 QTMLocationProvider::~QTMLocationProvider()
 {
     delete mLocation;
@@ -52,16 +55,19 @@ QTMLocationProvider::positionUpdated(con
 }
 
 NS_IMETHODIMP
 QTMLocationProvider::Startup()
 {
     if (!mLocation)
         return NS_ERROR_NOT_IMPLEMENTED;
 
+    // Not all versions of qt5positioning set default prefered method
+    // thus this workaround initializing QGeoPositionSource explicitly
+    SetHighAccuracy(false);
     mLocation->startUpdates();
 
     return NS_OK;
 }
 
 NS_IMETHODIMP
 QTMLocationProvider::Watch(nsIGeolocationUpdate* aCallback)
 {
@@ -78,12 +84,18 @@ QTMLocationProvider::Shutdown()
 
     mLocation->stopUpdates();
     mCallback = nullptr;
 
     return NS_OK;
 }
 
 NS_IMETHODIMP
-QTMLocationProvider::SetHighAccuracy(bool)
+QTMLocationProvider::SetHighAccuracy(bool aHigh)
 {
-  return NS_OK;
+    if (!mLocation)
+        return NS_ERROR_NOT_IMPLEMENTED;
+
+    mLocation->setPreferredPositioningMethods(aHigh ?
+                                              QGeoPositionInfoSource::SatellitePositioningMethods :
+                                              QGeoPositionInfoSource::AllPositioningMethods);
+    return NS_OK;
 }
rename from dom/system/unix/QTMLocationProvider.h
rename to dom/system/qt/QTMLocationProvider.h
--- a/dom/system/unix/QTMLocationProvider.h
+++ b/dom/system/qt/QTMLocationProvider.h
@@ -5,19 +5,16 @@
 #ifndef QTMLocationProvider_h
 #define QTMLocationProvider_h
 
 #include <QGeoPositionInfoSource>
 #include "nsGeolocation.h"
 #include "nsIGeolocationProvider.h"
 #include "nsCOMPtr.h"
 
-
-using namespace QtMobility;
-
 class QTMLocationProvider : public QObject,
                             public nsIGeolocationProvider
 {
     Q_OBJECT
 
 public:
     NS_DECL_ISUPPORTS
     NS_DECL_NSIGEOLOCATIONPROVIDER
rename from dom/system/unix/nsHapticFeedback.cpp
rename to dom/system/qt/QtHapticFeedback.cpp
--- a/dom/system/unix/nsHapticFeedback.cpp
+++ b/dom/system/qt/QtHapticFeedback.cpp
@@ -1,68 +1,20 @@
 /* -*- Mode: c++; c-basic-offset: 4; tab-width: 20; indent-tabs-mode: nil; -*-
  * 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/. */
 
-#if (MOZ_PLATFORM_MAEMO == 5)
-#include <dbus/dbus.h>
-#include <mce/dbus-names.h>
-#endif
-#if defined(MOZ_ENABLE_QTMOBILITY)
 #include <QFeedbackEffect>
-using namespace QtMobility;
-#endif
+#include "QtHapticFeedback.h"
 
-#include "nsHapticFeedback.h"
-
-NS_IMPL_ISUPPORTS1(nsHapticFeedback, nsIHapticFeedback)
+NS_IMPL_ISUPPORTS1(QtHapticFeedback, nsIHapticFeedback)
 
 NS_IMETHODIMP
-nsHapticFeedback::PerformSimpleAction(int32_t aType)
+QtHapticFeedback::PerformSimpleAction(int32_t aType)
 {
-#if (MOZ_PLATFORM_MAEMO == 5)
-    DBusError err;
-    dbus_error_init(&err);
-
-    DBusConnection  *connection;
-    connection = dbus_bus_get(DBUS_BUS_SYSTEM, &err);
-    if (dbus_error_is_set(&err)) {
-        dbus_error_free(&err);
-        return NS_ERROR_FAILURE;
-    }
-    if (nullptr == connection) {
-        return NS_ERROR_FAILURE;
-    }
-
-    dbus_connection_set_exit_on_disconnect(connection,false);
-
-    DBusMessage* msg =
-        dbus_message_new_method_call(MCE_SERVICE, MCE_REQUEST_PATH,
-                                     MCE_REQUEST_IF, MCE_ACTIVATE_VIBRATOR_PATTERN);
-
-    if (!msg) {
-        return NS_ERROR_FAILURE;
-    }
-
-    dbus_message_set_no_reply(msg, true);
-
-    DBusMessageIter iter;
-    dbus_message_iter_init_append(msg, &iter);
-    const char* pattern = "PatternTouchscreen";
-    dbus_message_iter_append_basic(&iter, DBUS_TYPE_STRING, &pattern);
-
-    if (dbus_connection_send(connection, msg, nullptr)) {
-        dbus_connection_flush(connection);
-        dbus_message_unref(msg);
-    } else {
-        dbus_message_unref(msg);
-        return NS_ERROR_FAILURE;
-    }
-#elif defined(MOZ_ENABLE_QTMOBILITY)
     if (aType == ShortPress)
-        QFeedbackEffect::playThemeEffect(QFeedbackEffect::ThemeBasicButton);
+        QFeedbackEffect::playThemeEffect(QFeedbackEffect::PressWeak);
     if (aType == LongPress)
-        QFeedbackEffect::playThemeEffect(QFeedbackEffect::ThemeLongPress);
-#endif
+        QFeedbackEffect::playThemeEffect(QFeedbackEffect::PressStrong);
 
     return NS_OK;
 }
rename from dom/system/unix/nsHapticFeedback.h
rename to dom/system/qt/QtHapticFeedback.h
--- a/dom/system/unix/nsHapticFeedback.h
+++ b/dom/system/qt/QtHapticFeedback.h
@@ -1,13 +1,13 @@
 /* -*- Mode: c++; c-basic-offset: 4; tab-width: 20; indent-tabs-mode: nil; -*-
  * 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 "nsIHapticFeedback.h"
 
-class nsHapticFeedback : public nsIHapticFeedback
+class QtHapticFeedback : public nsIHapticFeedback
 {
 public:
   NS_DECL_ISUPPORTS
   NS_DECL_NSIHAPTICFEEDBACK
 };
rename from dom/system/unix/moz.build
rename to dom/system/qt/moz.build
--- a/dom/system/unix/moz.build
+++ b/dom/system/qt/moz.build
@@ -13,16 +13,16 @@ if CONFIG['MOZ_ENABLE_QT5GEOPOSITION']:
     ]
 
     LOCAL_INCLUDES += [
         '/dom/src/geolocation',
     ]
 
 if CONFIG['MOZ_ENABLE_QT5FEEDBACK']:
     SOURCES += [
-        'nsHapticFeedback.cpp',
+        'QtHapticFeedback.cpp',
     ]
 
 FAIL_ON_WARNINGS = True
 
 include('/ipc/chromium/chromium-config.mozbuild')
 
 FINAL_LIBRARY = 'gklayout'
--- a/gfx/cairo/cairo/src/cairo-qt-surface.cpp
+++ b/gfx/cairo/cairo/src/cairo-qt-surface.cpp
@@ -51,17 +51,16 @@
 
 #include <QtGui/QPainter>
 #include <QtGui/QPaintEngine>
 #include <QtGui/QPaintDevice>
 #include <QtGui/QImage>
 #include <QtGui/QPixmap>
 #include <QtGui/QBrush>
 #include <QtGui/QPen>
-#include <QWidget>
 #include <QtCore/QVarLengthArray>
 
 #include <sys/time.h>
 
 /* Enable workaround slow regional Qt paths */
 #define ENABLE_FAST_FILL 0
 #define ENABLE_FAST_CLIP 0
 
@@ -584,18 +583,16 @@ static cairo_status_t
 	QPaintDevice *rpd = QPainter::redirected(pd, &offset);
 	if (rpd)
 	    pd = rpd;
 
         if (pd->devType() == QInternal::Image) {
             qimg = new QImage(((QImage*) pd)->copy());
         } else if (pd->devType() == QInternal::Pixmap) {
             qimg = new QImage(((QPixmap*) pd)->toImage());
-        } else if (pd->devType() == QInternal::Widget) {
-            qimg = new QImage(QPixmap::grabWindow(((QWidget*)pd)->winId()).toImage());
         }
     }
 
     if (qimg == NULL)
         return _cairo_error (CAIRO_STATUS_NO_MEMORY);
 
     *image_out = (cairo_image_surface_t*)
                  cairo_image_surface_create_for_data (qimg->bits(),
--- a/gfx/thebes/gfxQtNativeRenderer.cpp
+++ b/gfx/thebes/gfxQtNativeRenderer.cpp
@@ -32,17 +32,17 @@ gfxQtNativeRenderer::Draw(gfxContext* ct
                                gfxIntSize(size.width, size.height));
 
     if (!isOpaque) {
         nsRefPtr<gfxContext> tempCtx = new gfxContext(xsurf);
         tempCtx->SetOperator(gfxContext::OPERATOR_CLEAR);
         tempCtx->Paint();
     }
 
-    nsresult rv = DrawWithXlib(xsurf.get(), nsIntPoint(0, 0), nullptr, 0);
+    nsresult rv = DrawWithXlib(xsurf->CairoSurface(), nsIntPoint(0, 0), nullptr, 0);
 
     if (NS_FAILED(rv))
         return rv;
 
     ctx->SetSource(xsurf);
     ctx->Paint();
 
     return rv;
--- a/gfx/thebes/gfxQtNativeRenderer.h
+++ b/gfx/thebes/gfxQtNativeRenderer.h
@@ -25,19 +25,19 @@ public:
     /**
      * Perform the native drawing.
      * @param offsetX draw at this offset into the given drawable
      * @param offsetY draw at this offset into the given drawable
      * @param clipRects an array of rects; clip to the union
      * @param numClipRects the number of rects in the array, or zero if
      * no clipping is required
      */
-    virtual nsresult DrawWithXlib(gfxXlibSurface *xsurf,
-            nsIntPoint offset,
-            nsIntRect* clipRects, uint32_t numClipRects) = 0;
+    virtual nsresult DrawWithXlib(cairo_surface_t* surface,
+                                  nsIntPoint offset,
+                                  nsIntRect* clipRects, uint32_t numClipRects) = 0;
   
     enum {
         // If set, then Draw() is opaque, i.e., every pixel in the intersection
         // of the clipRect and (offset.x,offset.y,bounds.width,bounds.height)
         // will be set and there is no dependence on what the existing pixels
         // in the drawable are set to.
         DRAW_IS_OPAQUE = 0x01,
         // If set, then numClipRects can be zero or one
--- a/gfx/thebes/gfxQtPlatform.cpp
+++ b/gfx/thebes/gfxQtPlatform.cpp
@@ -1,24 +1,21 @@
 /* -*- Mode: C++; tab-width: 20; indent-tabs-mode: nil; c-basic-offset: 4 -*-
  * 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 <QPixmap>
-#include <qglobal.h>
-#if (QT_VERSION < QT_VERSION_CHECK(5,0,0))
-#  include <QX11Info>
-#else
-#  include <qpa/qplatformnativeinterface.h>
-#  include <qpa/qplatformintegration.h>
+#include <QWindow>
+#ifdef MOZ_X11
+#include <qpa/qplatformnativeinterface.h>
+#include <qpa/qplatformintegration.h>
 #endif
-#include <QApplication>
-#include <QDesktopWidget>
-#include <QPaintEngine>
+#include <QGuiApplication>
+#include <QScreen>
 
 #include "gfxQtPlatform.h"
 
 #include "gfxFontconfigUtils.h"
 
 #include "mozilla/gfx/2D.h"
 
 #include "cairo.h"
@@ -28,187 +25,107 @@
 #include "nsUnicodeProperties.h"
 
 #include "gfxPangoFonts.h"
 #include "gfxContext.h"
 #include "gfxUserFontSet.h"
 
 #include "nsUnicharUtils.h"
 
-#include <fontconfig/fontconfig.h>
-
 #include "nsMathUtils.h"
 #include "nsTArray.h"
 #ifdef MOZ_X11
 #include "gfxXlibSurface.h"
+#include "prenv.h"
 #endif
 
 #include "qcms.h"
 
 #include "mozilla/Preferences.h"
 
 using namespace mozilla;
 using namespace mozilla::unicode;
 using namespace mozilla::gfx;
 
-#if (QT_VERSION < QT_VERSION_CHECK(5,0,0))
-#define DEFAULT_RENDER_MODE RENDER_DIRECT
-#else
-#define DEFAULT_RENDER_MODE RENDER_BUFFERED
+gfxFontconfigUtils *gfxQtPlatform::sFontconfigUtils = nullptr;
+#ifdef MOZ_X11
+bool gfxQtPlatform::sUseXRender = true;
 #endif
 
-static QPaintEngine::Type sDefaultQtPaintEngineType = QPaintEngine::Raster;
-gfxFontconfigUtils *gfxQtPlatform::sFontconfigUtils = nullptr;
-static cairo_user_data_key_t cairo_qt_pixmap_key;
-static void do_qt_pixmap_unref (void *data)
-{
-    QPixmap *pmap = (QPixmap*)data;
-    delete pmap;
-}
-
 static gfxImageFormat sOffscreenFormat = gfxImageFormat::RGB24;
 
 gfxQtPlatform::gfxQtPlatform()
 {
-    mPrefFonts.Init(50);
-
+#ifdef MOZ_X11
+    sUseXRender = mozilla::Preferences::GetBool("gfx.xrender.enabled");
+#endif
     if (!sFontconfigUtils)
         sFontconfigUtils = gfxFontconfigUtils::GetFontconfigUtils();
 
-    g_type_init();
-
-    nsresult rv;
-    // 0 - default gfxQPainterSurface
-    // 1 - gfxImageSurface
-    int32_t ival = Preferences::GetInt("mozilla.widget-qt.render-mode", DEFAULT_RENDER_MODE);
-
-    const char *envTypeOverride = getenv("MOZ_QT_RENDER_TYPE");
-    if (envTypeOverride)
-        ival = atoi(envTypeOverride);
-
-    switch (ival) {
-        case 0:
-            mRenderMode = RENDER_QPAINTER;
-            break;
-        case 1:
-            mRenderMode = RENDER_BUFFERED;
-            break;
-        case 2:
-            mRenderMode = RENDER_DIRECT;
-            break;
-        default:
-            mRenderMode = RENDER_QPAINTER;
-    }
-
-    // Qt doesn't provide a public API to detect the graphicssystem type. We hack
-    // around this by checking what type of graphicssystem a test QPixmap uses.
-    QPixmap pixmap(1, 1);
-    if (pixmap.depth() == 16) {
+    mScreenDepth = qApp->primaryScreen()->depth();
+    if (mScreenDepth == 16) {
         sOffscreenFormat = gfxImageFormat::RGB16_565;
     }
-    mScreenDepth = pixmap.depth();
-#if (QT_VERSION < QT_VERSION_CHECK(4,8,0))
-    if (pixmap.paintEngine())
-        sDefaultQtPaintEngineType = pixmap.paintEngine()->type();
-#endif
     uint32_t canvasMask = BackendTypeBit(BackendType::CAIRO) | BackendTypeBit(BackendType::SKIA);
     uint32_t contentMask = BackendTypeBit(BackendType::CAIRO) | BackendTypeBit(BackendType::SKIA);
     InitBackendPrefs(canvasMask, BackendType::CAIRO,
                      contentMask, BackendType::CAIRO);
 }
 
 gfxQtPlatform::~gfxQtPlatform()
 {
     gfxFontconfigUtils::Shutdown();
     sFontconfigUtils = nullptr;
 
     gfxPangoFontGroup::Shutdown();
-
-#if 0
-    // It would be nice to do this (although it might need to be after
-    // the cairo shutdown that happens in ~gfxPlatform).  It even looks
-    // idempotent.  But it has fatal assertions that fire if stuff is
-    // leaked, and we hit them.
-    FcFini();
-#endif
 }
 
 #ifdef MOZ_X11
 Display*
-gfxQtPlatform::GetXDisplay(QWidget* aWindow)
+gfxQtPlatform::GetXDisplay(QWindow* aWindow)
 {
-#if (QT_VERSION < QT_VERSION_CHECK(5,0,0))
-#ifdef Q_WS_X11
-  return aWindow ? aWindow->x11Info().display() : QX11Info::display();
-#else
-  return nullptr;
-#endif
-#else
-  return (Display*)(qApp->platformNativeInterface()->
-    nativeResourceForWindow("display", aWindow ? aWindow->windowHandle() : nullptr));
-#endif
+    return (Display*)(qApp->platformNativeInterface()->
+        nativeResourceForScreen("display", aWindow ? aWindow->screen() : qApp->primaryScreen()));
 }
 
 Screen*
-gfxQtPlatform::GetXScreen(QWidget* aWindow)
+gfxQtPlatform::GetXScreen(QWindow* aWindow)
 {
-#if (QT_VERSION < QT_VERSION_CHECK(5,0,0))
-#ifdef Q_WS_X11
-  return ScreenOfDisplay(GetXDisplay(aWindow), aWindow ? aWindow->x11Info().screen() : QX11Info().screen());
-#else
-  return nullptr;
-#endif
-#else
-  return ScreenOfDisplay(GetXDisplay(aWindow),
-                         (int)(intptr_t)qApp->platformNativeInterface()->
-                           nativeResourceForWindow("screen",
-                             aWindow ? aWindow->windowHandle() : nullptr));
-#endif
+    return ScreenOfDisplay(GetXDisplay(aWindow),
+        (int)(intptr_t)qApp->platformNativeInterface()->
+            nativeResourceForScreen("screen", aWindow ? aWindow->screen() : qApp->primaryScreen()));
 }
 #endif
 
 already_AddRefed<gfxASurface>
 gfxQtPlatform::CreateOffscreenSurface(const IntSize& size,
                                       gfxContentType contentType)
 {
-    nsRefPtr<gfxASurface> newSurface = nullptr;
-
     gfxImageFormat imageFormat = OptimalFormatForContent(contentType);
 
-#ifdef CAIRO_HAS_QT_SURFACE
-    if (mRenderMode == RENDER_QPAINTER) {
-      newSurface = new gfxQPainterSurface(ThebesIntSize(size), imageFormat);
-      return newSurface.forget();
-    }
-#endif
-
-    if ((mRenderMode == RENDER_BUFFERED || mRenderMode == RENDER_DIRECT) &&
-        sDefaultQtPaintEngineType != QPaintEngine::X11) {
-      newSurface = new gfxImageSurface(ThebesIntSize(size), imageFormat);
-      return newSurface.forget();
-    }
-
-#ifdef MOZ_X11
-    XRenderPictFormat* xrenderFormat =
-        gfxXlibSurface::FindRenderFormat(GetXDisplay(), imageFormat);
-
-    Screen* screen = GetXScreen();
-    newSurface = gfxXlibSurface::Create(screen, xrenderFormat,
-                                        ThebesIntSize(size));
-#endif
-
-    if (newSurface) {
-        gfxContext ctx(newSurface);
-        ctx.SetOperator(gfxContext::OPERATOR_CLEAR);
-        ctx.Paint();
-    }
+    nsRefPtr<gfxASurface> newSurface =
+        new gfxImageSurface(gfxIntSize(size.width, size.height), imageFormat);
 
     return newSurface.forget();
 }
 
+already_AddRefed<gfxASurface>
+gfxQtPlatform::OptimizeImage(gfxImageSurface *aSurface,
+                             gfxImageFormat format)
+{
+    /* Qt have no special offscreen surfaces so we can avoid a copy */
+    if (OptimalFormatForContent(gfxASurface::ContentFromFormat(format)) ==
+        format) {
+        return nullptr;
+    }
+
+    return gfxPlatform::OptimizeImage(aSurface, format);
+}
+
+
 nsresult
 gfxQtPlatform::GetFontList(nsIAtom *aLangGroup,
                            const nsACString& aGenericFamily,
                            nsTArray<nsString>& aListOfFonts)
 {
     return sFontconfigUtils->GetFontList(aLangGroup, aGenericFamily,
                                          aListOfFonts);
 }
@@ -255,16 +172,27 @@ gfxQtPlatform::MakePlatformFont(const gf
                                  const uint8_t *aFontData, uint32_t aLength)
 {
     // passing ownership of the font data to the new font entry
     return gfxPangoFontGroup::NewFontEntry(*aProxyEntry,
                                            aFontData, aLength);
 }
 
 bool
+gfxQtPlatform::SupportsOffMainThreadCompositing()
+{
+#if defined(MOZ_X11) && !defined(NIGHTLY_BUILD)
+  return (PR_GetEnv("MOZ_USE_OMTC") != nullptr) ||
+         (PR_GetEnv("MOZ_OMTC_ENABLED") != nullptr);
+#else
+  return true;
+#endif
+}
+
+bool
 gfxQtPlatform::IsFontFormatSupported(nsIURI *aFontURI, uint32_t aFormatFlags)
 {
     // check for strange format flags
     NS_ASSERTION(!(aFormatFlags & gfxUserFontSet::FLAG_FORMAT_NOT_USED),
                  "strange font format hint set");
 
     // accept supported formats
     // Pango doesn't apply features from AAT TrueType extensions.
@@ -280,28 +208,27 @@ gfxQtPlatform::IsFontFormatSupported(nsI
     if (aFormatFlags != 0) {
         return false;
     }
 
     // no format hint set, need to look at data
     return true;
 }
 
-qcms_profile*
-gfxQtPlatform::GetPlatformCMSOutputProfile()
+void
+gfxQtPlatform::GetPlatformCMSOutputProfile(void *&mem, size_t &size)
 {
-    return nullptr;
+    mem = nullptr;
+    size = 0;
 }
 
 int32_t
 gfxQtPlatform::GetDPI()
 {
-    QDesktopWidget* rootWindow = qApp->desktop();
-    int32_t dpi = rootWindow->logicalDpiY(); // y-axis DPI for fonts
-    return dpi <= 0 ? 96 : dpi;
+    return qApp->primaryScreen()->logicalDotsPerInch();
 }
 
 gfxImageFormat
 gfxQtPlatform::GetOffscreenFormat()
 {
     return sOffscreenFormat;
 }
 
--- a/gfx/thebes/gfxQtPlatform.h
+++ b/gfx/thebes/gfxQtPlatform.h
@@ -10,106 +10,111 @@
 #include "nsAutoRef.h"
 #include "nsDataHashtable.h"
 #include "nsTArray.h"
 #ifdef MOZ_X11
 #include "X11/Xlib.h"
 #endif
 
 class gfxFontconfigUtils;
-class QWidget;
+class QWindow;
 
 class gfxQtPlatform : public gfxPlatform {
 public:
-
-    enum RenderMode {
-        /* Use QPainter surfaces */
-        RENDER_QPAINTER = 0,
-        /* Use offscreen buffer for rendering with image or xlib gfx backend */
-        RENDER_BUFFERED,
-        /* Direct rendering to Widget surface */
-        RENDER_DIRECT,
-        /* max */
-        RENDER_MODE_MAX
-    };
-
     gfxQtPlatform();
     virtual ~gfxQtPlatform();
 
     static gfxQtPlatform *GetPlatform() {
-        return (gfxQtPlatform*) gfxPlatform::GetPlatform();
+        return static_cast<gfxQtPlatform*>(gfxPlatform::GetPlatform());
     }
 
     virtual already_AddRefed<gfxASurface>
+    OptimizeImage(gfxImageSurface *aSurface,
+                  gfxImageFormat format) MOZ_OVERRIDE;
+    virtual already_AddRefed<gfxASurface>
       CreateOffscreenSurface(const IntSize& size,
                              gfxContentType contentType) MOZ_OVERRIDE;
 
-    mozilla::TemporaryRef<mozilla::gfx::ScaledFont>
-      GetScaledFontForFont(mozilla::gfx::DrawTarget* aTarget, gfxFont *aFont);
+    virtual mozilla::TemporaryRef<mozilla::gfx::ScaledFont>
+      GetScaledFontForFont(mozilla::gfx::DrawTarget* aTarget, gfxFont *aFont) MOZ_OVERRIDE;
 
-    nsresult GetFontList(nsIAtom *aLangGroup,
-                         const nsACString& aGenericFamily,
-                         nsTArray<nsString>& aListOfFonts);
+    virtual nsresult GetFontList(nsIAtom *aLangGroup,
+                                 const nsACString& aGenericFamily,
+                                 nsTArray<nsString>& aListOfFonts) MOZ_OVERRIDE;
 
-    nsresult UpdateFontList();
+    virtual nsresult UpdateFontList() MOZ_OVERRIDE;
 
-    nsresult ResolveFontName(const nsAString& aFontName,
-                             FontResolverCallback aCallback,
-                             void *aClosure, bool& aAborted);
+    virtual nsresult ResolveFontName(const nsAString& aFontName,
+                                     FontResolverCallback aCallback,
+                                     void *aClosure, bool& aAborted) MOZ_OVERRIDE;
 
-    nsresult GetStandardFamilyName(const nsAString& aFontName, nsAString& aFamilyName);
+    virtual nsresult GetStandardFamilyName(const nsAString& aFontName, nsAString& aFamilyName) MOZ_OVERRIDE;
 
-    gfxFontGroup *CreateFontGroup(const nsAString &aFamilies,
-                                  const gfxFontStyle *aStyle,
-                                  gfxUserFontSet* aUserFontSet);
+    virtual gfxFontGroup *CreateFontGroup(const nsAString &aFamilies,
+                                          const gfxFontStyle *aStyle,
+                                          gfxUserFontSet* aUserFontSet) MOZ_OVERRIDE;
 
     /**
      * Look up a local platform font using the full font face name (needed to
      * support @font-face src local() )
      */
     virtual gfxFontEntry* LookupLocalFont(const gfxProxyFontEntry *aProxyEntry,
-                                          const nsAString& aFontName);
+                                          const nsAString& aFontName) MOZ_OVERRIDE;
 
     /**
      * Activate a platform font (needed to support @font-face src url() )
      *
      */
     virtual gfxFontEntry* MakePlatformFont(const gfxProxyFontEntry *aProxyEntry,
                                            const uint8_t *aFontData,
-                                           uint32_t aLength);
+                                           uint32_t aLength) MOZ_OVERRIDE;
 
     /**
      * Check whether format is supported on a platform or not (if unclear,
      * returns true).
      */
     virtual bool IsFontFormatSupported(nsIURI *aFontURI,
-                                         uint32_t aFormatFlags);
+                                       uint32_t aFormatFlags) MOZ_OVERRIDE;
 
-    void ClearPrefFonts() { mPrefFonts.Clear(); }
-
-    RenderMode GetRenderMode() { return mRenderMode; }
-    void SetRenderMode(RenderMode rmode) { mRenderMode = rmode; }
+    virtual void ClearPrefFonts() { mPrefFonts.Clear(); }
 
     static int32_t GetDPI();
 
-    virtual gfxImageFormat GetOffscreenFormat();
+    virtual gfxImageFormat GetOffscreenFormat() MOZ_OVERRIDE;
 #ifdef MOZ_X11
-    static Display* GetXDisplay(QWidget* aWindow = 0);
-    static Screen* GetXScreen(QWidget* aWindow = 0);
+    static Display* GetXDisplay(QWindow* aWindow = 0);
+    static Screen* GetXScreen(QWindow* aWindow = 0);
 #endif
 
-    virtual int GetScreenDepth() const;
+    virtual int GetScreenDepth() const MOZ_OVERRIDE;
+
+    virtual bool SupportsOffMainThreadCompositing() MOZ_OVERRIDE;
 
 protected:
     static gfxFontconfigUtils *sFontconfigUtils;
 
 private:
-    virtual qcms_profile *GetPlatformCMSOutputProfile();
+
+    bool UseXRender() {
+#if defined(MOZ_X11)
+        if (GetContentBackend() != mozilla::gfx::BackendType::NONE &&
+            GetContentBackend() != mozilla::gfx::BackendType::CAIRO)
+            return false;
+
+        return sUseXRender;
+#else
+        return false;
+#endif
+    }
+
+    virtual void GetPlatformCMSOutputProfile(void *&mem, size_t &size) MOZ_OVERRIDE;
 
     // TODO: unify this with mPrefFonts (NB: holds families, not fonts) in gfxPlatformFontList
     nsDataHashtable<nsCStringHashKey, nsTArray<nsRefPtr<gfxFontEntry> > > mPrefFonts;
 
-    RenderMode mRenderMode;
     int mScreenDepth;
+#ifdef MOZ_X11
+    static bool sUseXRender;
+#endif
 };
 
 #endif /* GFX_PLATFORM_QT_H */
 
--- a/image/decoders/icon/qt/nsIconChannel.cpp
+++ b/image/decoders/icon/qt/nsIconChannel.cpp
@@ -1,16 +1,14 @@
 /* vim:set ts=2 sw=2 sts=2 cin et: */
 /* 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 <QIcon>
-#include <QStyle>
-#include <QApplication>
 
 #include <stdlib.h>
 #include <unistd.h>
 
 #include "nsMimeTypes.h"
 #include "nsIMIMEService.h"
 
 #include "nsIStringBundle.h"
@@ -103,28 +101,18 @@ nsIconChannel::Init(nsIURI* aURI)
 
   uint32_t desiredImageSize;
   iconURI->GetImageSize(&desiredImageSize);
 
   nsAutoCString iconStateString;
   iconURI->GetIconState(iconStateString);
   bool disabled = iconStateString.EqualsLiteral("disabled");
 
-  QStyle::StandardPixmap sp_icon = (QStyle::StandardPixmap)0;
-  nsCOMPtr <nsIGtkQtIconsConverter> converter = do_GetService("@mozilla.org/gtkqticonsconverter;1");
-  if (converter) {
-    int32_t res = 0;
-    stockIcon.Cut(0,4);
-    converter->Convert(stockIcon.get(), &res);
-    sp_icon = (QStyle::StandardPixmap)res;
-    // printf("ConvertIcon: icon:'%s' -> res:%i\n", stockIcon.get(), res);
-  }
-  if (!sp_icon)
-    return NS_ERROR_FAILURE;
+  // This is a workaround for https://bugzilla.mozilla.org/show_bug.cgi?id=662299
+  // Try to find corresponding freedesktop icon and fallback to empty QIcon if failed.
+  QIcon icon = QIcon::fromTheme(QString(stockIcon.get()).replace("gtk-", "edit-"));
+  QPixmap pixmap = icon.pixmap(desiredImageSize, desiredImageSize, disabled ? QIcon::Disabled : QIcon::Normal);
 
-  QStyle *style = qApp->style();
-  NS_ENSURE_TRUE(style, NS_ERROR_NULL_POINTER);
-  QPixmap pixmap = style->standardIcon(sp_icon).pixmap(desiredImageSize, desiredImageSize, disabled?QIcon::Disabled:QIcon::Normal);
   QImage image = pixmap.toImage();
 
   return moz_qicon_to_channel(&image, iconURI,
                               getter_AddRefs(mRealChannel));
 }
--- a/ipc/chromium/src/base/message_pump_qt.cc
+++ b/ipc/chromium/src/base/message_pump_qt.cc
@@ -34,21 +34,17 @@ MessagePumpForUI::MessagePumpForUI()
 
 MessagePumpForUI::~MessagePumpForUI() {
 }
 
 MessagePumpQt::MessagePumpQt(MessagePumpForUI &aPump)
   : pump(aPump), mTimer(new QTimer(this))
 {
   // Register our custom event type, to use in qApp event loop
-#if (QT_VERSION >= QT_VERSION_CHECK(4, 4, 0))
   sPokeEvent = QEvent::registerEventType();
-#else
-  sPokeEvent = QEvent::User+5000;
-#endif
   connect(mTimer, SIGNAL(timeout()), this, SLOT(dispatchDelayed()));
   mTimer->setSingleShot(true);
 }
 
 MessagePumpQt::~MessagePumpQt()
 {
   mTimer->stop();
   delete mTimer;
--- a/netwerk/base/src/nsAutodialQt.cpp
+++ b/netwerk/base/src/nsAutodialQt.cpp
@@ -23,17 +23,17 @@ nsresult
 nsAutodial::Init()
 {
   return NS_OK;
 }
 
 nsresult
 nsAutodial::DialDefault(const char16_t* hostName)
 {
-  if (nsQtNetworkManager::get()->openConnection(QString::fromUtf16(hostName))) {
+  if (nsQtNetworkManager::get()->openConnection(QString::fromUtf16((const ushort*)hostName))) {
     return NS_OK;
   }
 
   return NS_ERROR_FAILURE;
 }
 
 bool
 nsAutodial::ShouldDialOnNetworkError()
--- a/toolkit/components/remote/nsQtRemoteService.cpp
+++ b/toolkit/components/remote/nsQtRemoteService.cpp
@@ -1,34 +1,35 @@
 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /* vim:expandtab:shiftwidth=2:tabstop=8:
  */
 /* 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 <QWidget>
+#include <QWindow>
 #include "nsQtRemoteService.h"
 
 #include "mozilla/ModuleUtils.h"
 #include "mozilla/X11Util.h"
 #include "nsIServiceManager.h"
 #include "nsIAppShellService.h"
 
 #include "nsCOMPtr.h"
 
 /**
   Helper class which is used to receive notification about property changes
 */
-class MozQRemoteEventHandlerWidget: public QWidget {
+class MozQRemoteEventHandlerWidget: public QWindow {
 public:
   /**
     Constructor
     @param aRemoteService remote service, which is notified about atom change
   */
   MozQRemoteEventHandlerWidget(nsQtRemoteService &aRemoteService);
+  virtual ~MozQRemoteEventHandlerWidget() {}
 
 protected:
   /**
     Event filter, which receives all XEvents
     @return false which continues event handling
   */
   bool x11Event(XEvent *);
 
--- a/toolkit/components/remote/nsQtRemoteService.h
+++ b/toolkit/components/remote/nsQtRemoteService.h
@@ -16,22 +16,21 @@ class RemoteEventHandlerWidget;
 class nsQtRemoteService : public nsXRemoteService
 {
 public:
   // We will be a static singleton, so don't use the ordinary methods.
   NS_DECL_ISUPPORTS
   NS_DECL_NSIREMOTESERVICE  
 
   nsQtRemoteService();
+  virtual ~nsQtRemoteService() { };
 
 private:
-  ~nsQtRemoteService() { };
-
   virtual void SetDesktopStartupIDOrTimestamp(const nsACString& aDesktopStartupID,
                                               uint32_t aTimestamp);
 
   void PropertyNotifyEvent(XEvent *evt);
   friend class MozQRemoteEventHandlerWidget;
 
-  QWidget *mServerWindow;
+  QWindow *mServerWindow;
 };
 
 #endif // __nsQtRemoteService_h__
--- a/toolkit/xre/nsAppRunner.cpp
+++ b/toolkit/xre/nsAppRunner.cpp
@@ -1,21 +1,17 @@
 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /* 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/. */
 
 #if defined(MOZ_WIDGET_QT)
-#include <QApplication>
+#include <QGuiApplication>
 #include <QStringList>
 #include "nsQAppInstance.h"
-#if (QT_VERSION < QT_VERSION_CHECK(5, 0, 0))
-#include <QInputContextFactory>
-#include <QInputContext>
-#endif
 #endif // MOZ_WIDGET_QT
 
 #include "mozilla/dom/ContentParent.h"
 #include "mozilla/dom/ContentChild.h"
 
 #include "mozilla/ArrayUtils.h"
 #include "mozilla/Attributes.h"
 #include "mozilla/Likely.h"
--- a/toolkit/xre/nsQAppInstance.cpp
+++ b/toolkit/xre/nsQAppInstance.cpp
@@ -1,48 +1,31 @@
 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /* vim: set ts=8 et sw=2 tw=80: */
 /* 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 "nsQAppInstance.h"
-#include <QApplication>
-#ifdef MOZ_ENABLE_MEEGOTOUCH
-#include <MComponentData>
-#include <MApplicationService>
-#endif
+#include <QGuiApplication>
 #include "prenv.h"
 #include "nsXPCOMPrivate.h"
 #include <stdlib.h>
 
-QApplication *nsQAppInstance::sQAppInstance = nullptr;
-#ifdef MOZ_ENABLE_MEEGOTOUCH
-MComponentData* nsQAppInstance::sMComponentData = nullptr;
-#endif
+QGuiApplication *nsQAppInstance::sQAppInstance = nullptr;
 int nsQAppInstance::sQAppRefCount = 0;
 
 void nsQAppInstance::AddRef(int& aArgc, char** aArgv, bool aDefaultProcess) {
   if (qApp)
     return;
   if (!sQAppInstance) {
-#if (QT_VERSION < QT_VERSION_CHECK(5,0,0))
-    const char *graphicsSystem = getenv("MOZ_QT_GRAPHICSSYSTEM");
-    if (graphicsSystem) {
-      QApplication::setGraphicsSystem(QString(graphicsSystem));
-    }
-#endif
     mozilla::SetICUMemoryFunctions();
-    sQAppInstance = new QApplication(aArgc, aArgv);
+    sQAppInstance = new QGuiApplication(aArgc, aArgv);
   }
   sQAppRefCount++;
 }
 
 void nsQAppInstance::Release(void) {
   if (sQAppInstance && !--sQAppRefCount) {
-#ifdef MOZ_ENABLE_MEEGOTOUCH
-    delete sMComponentData;
-    sMComponentData = nullptr;
-#endif
     delete sQAppInstance;
     sQAppInstance = nullptr;
   }
 }
--- a/toolkit/xre/nsQAppInstance.h
+++ b/toolkit/xre/nsQAppInstance.h
@@ -6,25 +6,23 @@
 
 #ifndef nsQAppInstance_h
 #define nsQAppInstance_h
 
 // declared in nsAppRunner.cpp
 extern int    gArgc;
 extern char **gArgv;
 
-class QApplication;
-class MComponentData;
+class QGuiApplication;
 class nsQAppInstance
 {
 public:
   static void AddRef(int& aArgc = gArgc,
                      char** aArgv = gArgv,
                      bool aDefaultProcess = false);
   static void Release(void);
 
 private:
-  static QApplication *sQAppInstance;
-  static MComponentData* sMComponentData;
+  static QGuiApplication *sQAppInstance;
   static int sQAppRefCount;
 };
 
 #endif /* nsQAppInstance_h */
--- a/widget/qt/Makefile.in
+++ b/widget/qt/Makefile.in
@@ -1,9 +1,9 @@
 #
 # 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 $(topsrcdir)/config/rules.mk
 
-CXXFLAGS	+= $(MOZ_QT_CFLAGS) $(GLIB_CFLAGS) $(MOZ_CAIRO_CFLAGS)
-CFLAGS		+= $(MOZ_QT_CFLAGS) $(GLIB_CFLAGS) $(MOZ_CAIRO_CFLAGS)
+CXXFLAGS	+= $(MOZ_QT_CFLAGS) $(MOZ_CAIRO_CFLAGS)
+CFLAGS		+= $(MOZ_QT_CFLAGS) $(MOZ_CAIRO_CFLAGS)
deleted file mode 100644
--- a/widget/qt/faststartupqt/Makefile.in
+++ /dev/null
@@ -1,23 +0,0 @@
-# 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/.
-
-DIST_INSTALL = 1
-STL_FLAGS=
-
-EXPORT_SOURCES = \
-	$(topsrcdir)/widget/qt/moziqwidget.h \
-	$(topsrcdir)/toolkit/xre/nsQAppInstance.h \
-	$(topsrcdir)/toolkit/xre/nsQAppInstance.cpp \
-	$(topsrcdir)/widget/qt/mozqglwidgetwrapper.h \
-	$(topsrcdir)/widget/qt/mozqglwidgetwrapper.cpp
-
-GARBAGE += $(EXPORT_SOURCES)
-export:: $(EXPORT_SOURCES)
-	$(INSTALL) $^ .
-
-include $(topsrcdir)/config/rules.mk
-
-CXXFLAGS += \
-	$(MOZ_QT_CFLAGS) \
-	$(NULL)
deleted file mode 100644
--- a/widget/qt/faststartupqt/moz.build
+++ /dev/null
@@ -1,37 +0,0 @@
-# -*- Mode: python; c-basic-offset: 4; indent-tabs-mode: nil; tab-width: 40 -*-
-# vim: set filetype=python:
-# 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/.
-
-GENERATED_SOURCES += [
-    'moc_moziqwidget.cpp',
-    'moc_nsFastStartupQt.cpp',
-    'mozqwidgetfast.cpp',
-]
-
-SOURCES += [
-    TOPSRCDIR + '/toolkit/xre/nsQAppInstance.cpp',
-    TOPSRCDIR + '/widget/qt/mozqglwidgetwrapper.cpp',
-]
-
-SOURCES += [
-    'nsFastStartupQt.cpp',
-]
-
-FINAL_LIBRARY = 'xul'
-
-LOCAL_INCLUDES += [
-    '/widget/qt',
-    '/xpcom/build',
-]
-
-
-DEFINES['LIBRARY_FILENAME'] = '%s%s%s' % (
-    CONFIG['DLL_PREFIX'],
-    LIBRARY_NAME,
-    CONFIG['DLL_SUFFIX']
-)
-
-DEFINES['MOZ_NO_MOZALLOC'] = True
-DEFINES['XPCOM_GLUE'] = True
deleted file mode 100644
--- a/widget/qt/faststartupqt/mozqwidgetfast.cpp
+++ /dev/null
@@ -1,105 +0,0 @@
-/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
-/* vim: set ts=4 et sw=4 tw=80: */
-/* 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 <QtCore/QUrl>
-#include "mozqwidgetfast.h"
-#include "nsFastStartupQt.h"
-#include "nsIFile.h"
-#include "nsString.h"
-#include "BinaryPath.h"
-
-#define TOOLBAR_SPLASH "toolbar_splash.png"
-#define FAVICON_SPLASH "favicon32.png"
-#define DRAWABLE_PATH "res/drawable/"
-
-MozQWidgetFast::MozQWidgetFast(nsWindow* aReceiver, QGraphicsItem* aParent)
-{
-  setParentItem(aParent);
-  char exePath[MAXPATHLEN];
-  QStringList arguments = qApp->arguments();
-  nsresult rv =
-    mozilla::BinaryPath::Get(arguments.at(0).toLocal8Bit().constData(),
-                             exePath);
-  if (NS_FAILED(rv)) {
-    printf("Cannot read default path\n");
-    return;
-  }
-  char *lastSlash = strrchr(exePath, XPCOM_FILE_PATH_SEPARATOR[0]);
-  if (!lastSlash ||
-      (lastSlash - exePath > int(MAXPATHLEN - sizeof(XPCOM_DLL) - 1))) {
-     return;
-  }
-  strcpy(++lastSlash, "/");
-  QString resourcePath(QString((const char*)&exePath) + DRAWABLE_PATH);
-  mToolbar.load(resourcePath + TOOLBAR_SPLASH);
-  mIcon.load(resourcePath + FAVICON_SPLASH);
-  for (int i = 1; i < arguments.size(); i++) {
-    QUrl url = QUrl::fromUserInput(arguments.at(i));
-    if (url.isValid()) {
-      mUrl = url.toString();
-    }
-  }
-}
-
-void MozQWidgetFast::paint(QPainter* aPainter,
-                           const QStyleOptionGraphicsItem*,
-                           QWidget*)
-{
-  // toolbar height
-  int toolbarHeight = 80;
-  // Offset of favicon starting from left toolbar edge
-  int faviconOffset = 25;
-  // favicon size
-  int faviconSize = 32;
-  // width of left and right TOOLBAR_SPLASH part
-  // |------------------------------|
-  // |LeftPart|tile...part|RightPart|
-  float toolbarPartWidth = 77;
-  // width of TOOLBAR_SPLASH part after toolbarPartWidth,
-  // that can be used for tiled toolbar area
-  int tileWidth = 2;
-  // Paint left toolbar part
-  aPainter->drawPixmap(QRect(0, 0, toolbarPartWidth, toolbarHeight),
-                       mToolbar, QRect(0, 0, toolbarPartWidth, toolbarHeight));
-
-  // Paint Tile pixmap of middle toolbar part
-  QPixmap tile(tileWidth, toolbarHeight);
-  QPainter p(&tile);
-  p.drawPixmap(QRect(0, 0, tileWidth, toolbarHeight), mToolbar,
-               QRect(toolbarPartWidth, 0, tileWidth, toolbarHeight));
-  aPainter->drawTiledPixmap(QRect(toolbarPartWidth, 0, rect().width() - toolbarPartWidth * 2,
-                                  toolbarHeight),
-                            tile);
-  // Paint Favicon
-  aPainter->drawPixmap(QRect(faviconOffset, faviconOffset,
-                             faviconSize, faviconSize),
-                       mIcon);
-  if (!mUrl.isEmpty()) {
-    // Height or URL string (font height)
-    float urlHeight = 24.0f;
-    // Start point of URL string, relative to window 0,0
-    int urlOffsetX = 80;
-    int urlOffsetY = 48;
-    QFont font = aPainter->font();
-    font.setPixelSize(urlHeight);
-    font.setFamily(QString("Nokia Sans"));
-    font.setKerning(true);
-    aPainter->setFont(font);
-    aPainter->setRenderHint(QPainter::TextAntialiasing, true);
-    aPainter->drawText(urlOffsetX, urlOffsetY,
-                       aPainter->fontMetrics().elidedText(mUrl, Qt::ElideRight, rect().width() - urlOffsetX * 2));
-  }
-
-  // Paint Right toolbar part
-  aPainter->drawPixmap(QRect(rect().width() - toolbarPartWidth,
-                             0, toolbarPartWidth,
-                             toolbarHeight),
-                       mToolbar,
-                       QRect(mToolbar.width() - toolbarPartWidth, 0,
-                             toolbarPartWidth, toolbarHeight));
-
-  nsFastStartup::GetSingleton()->painted();
-}
deleted file mode 100644
--- a/widget/qt/faststartupqt/mozqwidgetfast.h
+++ /dev/null
@@ -1,28 +0,0 @@
-/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
-/* vim: set ts=4 et sw=4 tw=80: */
-/* 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 MOZQWIDGETFAST_H
-#define MOZQWIDGETFAST_H
-
-#include <QtCore/QObject>
-#include "moziqwidget.h"
-
-class MozQWidgetFast : public IMozQWidget
-{
-public:
-    MozQWidgetFast(nsWindow* aReceiver, QGraphicsItem *aParent);
-    ~MozQWidgetFast() {}
-
-protected:
-    virtual void paint(QPainter*, const QStyleOptionGraphicsItem*, QWidget*);
-
-private:
-    QPixmap mToolbar;
-    QPixmap mIcon;
-    QString mUrl;
-};
-
-#endif
deleted file mode 100644
--- a/widget/qt/faststartupqt/nsFastStartupQt.cpp
+++ /dev/null
@@ -1,126 +0,0 @@
-/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
-/* vim: set ts=4 et sw=4 tw=80: */
-/* 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 <QApplication>
-#include "nsQAppInstance.h"
-#include <QtOpenGL/QGLWidget>
-#include <QThread>
-#if defined MOZ_ENABLE_MEEGOTOUCH
-#include <MScene>
-#endif
-#include "moziqwidget.h"
-#include "mozqwidgetfast.h"
-#include "nsFastStartupQt.h"
-#include "nsXPCOMGlue.h"
-#include "nsXULAppAPI.h"
-
-
-static nsFastStartup* sFastStartup = nullptr;
-
-void
-GeckoThread::run()
-{
-  Q_EMIT symbolsLoadingFinished(mFunc(mExecPath));
-}
-
-void
-nsFastStartup::symbolsLoadingFinished(bool preloaded)
-{
-  mSymbolsLoaded = preloaded;
-  if (mWidgetPainted && mSymbolsLoaded) {
-    mLoop.quit();
-  }
-}
-
-void nsFastStartup::painted()
-{
-  mWidgetPainted = true;
-  if (mWidgetPainted && mSymbolsLoaded) {
-    mLoop.quit();
-  }
-}
-
-MozGraphicsView*
-nsFastStartup::GetStartupGraphicsView(QWidget* parentWidget, IMozQWidget* aTopChild)
-{
-  MozGraphicsView* view = nullptr;
-  if (sFastStartup && sFastStartup->mGraphicsView) {
-    view = sFastStartup->mGraphicsView;
-  } else {
-    view = new MozGraphicsView(parentWidget);
-    Qt::WindowFlags flags = Qt::Widget;
-    view->setWindowFlags(flags);
-  }
-  view->SetTopLevel(aTopChild, parentWidget);
-
-  return view;
-}
-
-nsFastStartup*
-nsFastStartup::GetSingleton()
-{
-  return sFastStartup;
-}
-
-nsFastStartup::nsFastStartup()
- : mGraphicsView(0)
- , mFakeWidget(0)
- , mSymbolsLoaded(false)
- , mWidgetPainted(false)
- , mThread(0)
-
-{
-  sFastStartup = this;
-}
-
-nsFastStartup::~nsFastStartup()
-{
-  nsQAppInstance::Release();
-  sFastStartup = 0;
-}
-
-void
-nsFastStartup::RemoveFakeLayout()
-{
-  if (mFakeWidget && mGraphicsView) {
-    mGraphicsView->scene()->removeItem(mFakeWidget);
-    mFakeWidget->deleteLater();
-    mFakeWidget = 0;
-    // Forget GraphicsView, ownership moved to nsIWidget
-    mGraphicsView = 0;
-  }
-}
-
-bool
-nsFastStartup::CreateFastStartup(int& argc, char ** argv,
-                                 const char* execPath,
-                                 GeckoLoaderFunc aFunc)
-{
-  gArgc = argc;
-  gArgv = argv;
-  // Create main QApplication instance
-  nsQAppInstance::AddRef(argc, argv, true);
-  // Create symbols loading thread
-  mThread = new GeckoThread();
-  // Setup thread loading finished callbacks
-  connect(mThread, SIGNAL(symbolsLoadingFinished(bool)),
-          this, SLOT(symbolsLoadingFinished(bool)));
-  mThread->SetLoader(aFunc, execPath);
-  // Create Static UI widget and view
-  IMozQWidget* fakeWidget = new MozQWidgetFast(nullptr, nullptr);
-  mGraphicsView = GetStartupGraphicsView(nullptr, fakeWidget);
-  mFakeWidget = fakeWidget;
-
-  mThread->start();
-  mGraphicsView->showNormal();
-
-  // Start native loop in order to get view opened and painted once
-  // Will block CreateFastStartup function and
-  // exit when symbols are loaded and Static UI shown
-  mLoop.exec();
-
-  return true;
-}
deleted file mode 100644
--- a/widget/qt/faststartupqt/nsFastStartupQt.h
+++ /dev/null
@@ -1,81 +0,0 @@
-/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
-/* vim: set ts=4 et sw=4 tw=80: */
-/* 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 FAST_STARTUP_H
-#define FAST_STARTUP_H
-
-#include <QObject>
-#include "nscore.h"
-#include <QThread>
-#include <QEventLoop>
-#include <sys/time.h>
-
-class QGraphicsView;
-class MozMGraphicsView;
-class MozQGraphicsView;
-class QGraphicsWidget;
-class IMozQWidget;
-class QWidget;
-
-#if defined MOZ_ENABLE_MEEGOTOUCH
-typedef MozMGraphicsView MozGraphicsView;
-#else
-typedef MozQGraphicsView MozGraphicsView;
-#endif
-
-class nsFastStartup;
-typedef bool (*GeckoLoaderFunc)(const char* execPath);
-class GeckoThread : public QThread
-{
-  Q_OBJECT
-
-public:
-  void run();
-  void SetLoader(GeckoLoaderFunc aFunc, const char* execPath)
-  {
-    mExecPath = execPath;
-    mFunc = aFunc;
-  }
-
-Q_SIGNALS:
-  void symbolsLoadingFinished(bool);
-
-private:
-  const char* mExecPath;
-  GeckoLoaderFunc mFunc;
-};
-
-class NS_EXPORT nsFastStartup : public QObject
-{
-  Q_OBJECT
-
-public:
-  static nsFastStartup* GetSingleton();
-  // Create new or get QGraphicsView which could have been created for Static UI
-  static MozGraphicsView* GetStartupGraphicsView(QWidget* parentWidget, IMozQWidget* aTopChild);
-  nsFastStartup();
-  virtual ~nsFastStartup();
-  virtual bool CreateFastStartup(int& argc, char ** argv,
-                                 const char* execPath,
-                                 GeckoLoaderFunc aFunc);
-  // Called when first real mozilla paint happend
-  void RemoveFakeLayout();
-  // Final notification that Static UI show and painted
-  void painted();
-
-protected Q_SLOTS:
-    void symbolsLoadingFinished(bool);
-
-private:
-  MozGraphicsView* mGraphicsView;
-  QGraphicsWidget* mFakeWidget;
-  bool mSymbolsLoaded;
-  bool mWidgetPainted;
-  GeckoThread* mThread;
-  QEventLoop mLoop;
-};
-
-#endif
--- a/widget/qt/moz.build
+++ b/widget/qt/moz.build
@@ -1,76 +1,50 @@
 # -*- Mode: python; c-basic-offset: 4; indent-tabs-mode: nil; tab-width: 40 -*-
 # vim: set filetype=python:
 # 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/.
 
-DIRS += ['faststartupqt']
-
-EXPORTS += [
-    'nsQtKeyUtils.h',
-]
-
 GENERATED_SOURCES += [
-    'moc_moziqwidget.cpp',
     'moc_mozqwidget.cpp',
     'moc_nsAppShell.cpp',
 ]
 
 SOURCES += [
-    'mozqglwidgetwrapper.cpp',
     'mozqwidget.cpp',
-    'mozSwipeGesture.cpp',
     'nsAppShell.cpp',
     'nsBidiKeyboard.cpp',
     'nsClipboard.cpp',
-    'nsDeviceContextSpecQt.cpp',
-    'nsDragService.cpp',
-    'nsFilePicker.cpp',
     'nsIdleServiceQt.cpp',
     'nsLookAndFeel.cpp',
-    'nsNativeThemeQt.cpp',
-    'nsPrintDialogQt.cpp',
-    'nsPrintOptionsQt.cpp',
-    'nsPrintSettingsQt.cpp',
     'nsQtKeyUtils.cpp',
     'nsScreenManagerQt.cpp',
     'nsScreenQt.cpp',
-    'nsSound.cpp',
     'nsWidgetFactory.cpp',
     'nsWindow.cpp',
 ]
 
-if CONFIG['MOZ_ENABLE_CONTENTMANAGER']:
+
+if CONFIG['NS_PRINTING']:
     SOURCES += [
-        'nsMFilePicker.cpp',
-    ]
-    GENERATED_SOURCES += [
-        'moc_nsMFilePicker.cpp',
-    ]
-
-if CONFIG[' MOZ_ENABLE_QTMOBILITY']:
-    SOURCES += [
-        'mozqorientationsensorfilter.cpp',
-    ]
-    GENERATED_SOURCES += [
-        'moc_mozqorientationsensorfilter.cpp',
+        'nsDeviceContextSpecQt.cpp',
+        'nsPrintDialogQt.cpp',
+        'nsPrintOptionsQt.cpp',
+        'nsPrintSettingsQt.cpp',
     ]
 
 LIBRARY_NAME = 'widget_qt'
 
 include('/ipc/chromium/chromium-config.mozbuild')
 
 FINAL_LIBRARY = 'xul'
 
 LOCAL_INCLUDES += [
     '../shared',
-    '/widget/qt/faststartupqt',
-    '/widget/shared',
     '/widget/xpwidgets',
 ]
 
 if CONFIG['MOZ_X11']:
     LOCAL_INCLUDES += [
         '../shared/x11',
     ]
 
deleted file mode 100644
--- a/widget/qt/mozSwipeGesture.cpp
+++ /dev/null
@@ -1,180 +0,0 @@
-/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
-/* vim:expandtab:shiftwidth=4:tabstop=4:
- */
-/* 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 "mozSwipeGesture.h"
-#include <QTouchEvent>
-#include <QGraphicsWidget>
-#include <nsIDOMSimpleGestureEvent.h>
-#include <math.h>
-
-// Percent of screen size
-static const float TRIGGER_DISTANCE = 0.3;
-
-// It would be nice to get platform defines for these values
-// Maximum finger distance in pixels
-const int MAX_FINGER_DISTANCE = 250;
-// We could define it as 2*QT_GUI_DOUBLE_CLICK_RADIUS, but it's not available
-// due to QTBUG-9630
-const int FINGER_DISTANCE_MISTAKE = 50;
-
-QGesture*
-MozSwipeGestureRecognizer::create(QObject* target)
-{
-    return new MozSwipeGesture();
-}
-
-QGestureRecognizer::Result
-MozSwipeGestureRecognizer::recognize(QGesture* aState,
-                                     QObject* aWatched,
-                                     QEvent* aEvent)
-{
-    const QTouchEvent* ev = static_cast<const QTouchEvent *>(aEvent);
-    MozSwipeGesture* swipe = static_cast<MozSwipeGesture *>(aState);
-
-    QGestureRecognizer::Result result = QGestureRecognizer::Ignore;
-
-    QGraphicsWidget* widget = qobject_cast<QGraphicsWidget*>(aWatched);
-    if (!widget) {
-        return result;
-    }
-
-    switch (aEvent->type()) {
-        case QEvent::TouchBegin:
-            swipe->mSwipeState = MozSwipeGesture::NOT_STARTED;
-            result = QGestureRecognizer::MayBeGesture;
-            break;
-
-        case QEvent::TouchEnd:
-            if (swipe->state() != Qt::NoGesture &&
-                swipe->mSwipeState == MozSwipeGesture::TRIGGERED) {
-                result = QGestureRecognizer::FinishGesture;
-            }
-            else {
-                result = QGestureRecognizer::CancelGesture;
-            }
-            break;
-
-        case QEvent::TouchUpdate:
-            // We have already handled this swipe
-            if (swipe->mSwipeState > MozSwipeGesture::STARTED) {
-                break;
-            }
-
-            if (ev->touchPoints().count() > 2) {
-                swipe->mSwipeState = MozSwipeGesture::CANCELLED;
-                result = QGestureRecognizer::CancelGesture;
-                break;
-            }
-
-
-            if (ev->touchPoints().count() == 2) {
-               swipe->mSwipeState = MozSwipeGesture::STARTED;
-               QList <QTouchEvent::TouchPoint> touchPoints = ev->touchPoints();
-               if (!swipe->Update(touchPoints[0], touchPoints[1], widget->size())) {
-                   result = QGestureRecognizer::CancelGesture;
-                   swipe->mSwipeState = MozSwipeGesture::CANCELLED;
-               }
-               if (swipe->mSwipeState == MozSwipeGesture::TRIGGERED) {
-                   result = QGestureRecognizer::TriggerGesture;
-               }
-               else {
-                   result = QGestureRecognizer::MayBeGesture;
-               }
-           }
-           break;
-
-        default:
-            result = QGestureRecognizer::Ignore;
-    }
-
-    return result;
-}
-
-void
-MozSwipeGestureRecognizer::reset(QGesture* aState)
-{
-    MozSwipeGesture* swipe = static_cast<MozSwipeGesture *>(aState);
-    swipe->mHorizontalDirection = 0;
-    swipe->mVerticalDirection = 0;
-    QGestureRecognizer::reset(aState);
-}
-
-MozSwipeGesture::MozSwipeGesture()
-  : mHorizontalDirection(0)
-  , mVerticalDirection(0)
-  , mSwipeState(MozSwipeGesture::NOT_STARTED)
-{
-}
-
-int MozSwipeGesture::Direction()
-{
-    return mHorizontalDirection | mVerticalDirection;
-}
-
-bool
-MozSwipeGesture::Update(const QTouchEvent::TouchPoint& aFirstPoint,
-                        const QTouchEvent::TouchPoint& aSecondPoint,
-                        const QSizeF& aSize)
-{
-    // Check that fingers are not too far away
-    QPointF fingerDistance = aFirstPoint.pos() - aSecondPoint.pos();
-    if (fingerDistance.manhattanLength() > MAX_FINGER_DISTANCE) {
-        return false;
-    }
-
-    // Check that fingers doesn't move too much from the original distance
-    QPointF startFingerDistance = aFirstPoint.startPos() - aSecondPoint.startPos();
-    if ((startFingerDistance - fingerDistance).manhattanLength()
-         > FINGER_DISTANCE_MISTAKE) {
-        return false;
-    }
-
-    QPointF startPosition = aFirstPoint.startNormalizedPos();
-    QPointF currentPosition = aFirstPoint.normalizedPos();
-
-    float xDistance = fabs(currentPosition.x() - startPosition.x());
-    float yDistance = fabs(currentPosition.y() - startPosition.y());
-
-    startPosition = aFirstPoint.startPos();
-    currentPosition = aFirstPoint.pos();
-
-    if (!aSize.isEmpty()) {
-        xDistance = fabs(currentPosition.x() - startPosition.x())
-                    / aSize.width();
-        yDistance = fabs(currentPosition.y() - startPosition.y())
-                    / aSize.height();
-    }
-
-    mVerticalDirection = nsIDOMSimpleGestureEvent::DIRECTION_UP;
-    if (currentPosition.y() > startPosition.y()) {
-        mVerticalDirection = nsIDOMSimpleGestureEvent::DIRECTION_DOWN;
-    }
-
-    mHorizontalDirection = nsIDOMSimpleGestureEvent::DIRECTION_LEFT;
-    if (currentPosition.x() > startPosition.x()) {
-        mHorizontalDirection = nsIDOMSimpleGestureEvent::DIRECTION_RIGHT;
-    }
-
-    if (xDistance > TRIGGER_DISTANCE) {
-        if (yDistance < TRIGGER_DISTANCE/2) {
-            mVerticalDirection = 0;
-        }
-        mSwipeState = TRIGGERED;
-    }
-
-    if (yDistance > TRIGGER_DISTANCE) {
-        if (xDistance < TRIGGER_DISTANCE/2) {
-            mHorizontalDirection = 0;
-        }
-        mSwipeState = TRIGGERED;
-    }
-
-    // Use center of touchpoints as hotspot
-    QPointF hotspot = aFirstPoint.pos() + aSecondPoint.pos();
-    hotspot /= 2;
-    setHotSpot(hotspot);
-    return true;
-}
deleted file mode 100644
--- a/widget/qt/mozSwipeGesture.h
+++ /dev/null
@@ -1,50 +0,0 @@
-/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
-/* vim:expandtab:shiftwidth=4:tabstop=4:
- */
-/* 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 MOZSWIPEGESTURE_H
-#define MOZSWIPEGESTURE_H
-
-#include <QGestureRecognizer>
-#include <QGesture>
-#include <QTouchEvent>
-
-class MozSwipeGestureRecognizer: public QGestureRecognizer
-{
-public:
-    virtual QGesture* create(QObject* aTarget);
-    virtual QGestureRecognizer::Result recognize(QGesture* aState,
-                                                 QObject* aWatched,
-                                                 QEvent* aEvent);
-    virtual void reset(QGesture* aState);
-};
-
-class MozSwipeGesture: public QGesture
-{
-public:
-    int Direction();
-
-private:
-    enum SwipeState {
-        NOT_STARTED = 0,
-        STARTED,
-        CANCELLED,
-        TRIGGERED
-    };
-
-    MozSwipeGesture();
-
-    bool Update(const QTouchEvent::TouchPoint& aFirstPoint,
-                const QTouchEvent::TouchPoint& aSecondPoint,
-                const QSizeF& aSize);
-
-    int mHorizontalDirection;
-    int mVerticalDirection;
-    SwipeState mSwipeState;
-    friend class MozSwipeGestureRecognizer;
-};
-
-#endif
deleted file mode 100644
--- a/widget/qt/moziqwidget.h
+++ /dev/null
@@ -1,319 +0,0 @@
-/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
-/* vim: set ts=4 et sw=4 tw=80: */
-/* 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 MOZIQWIDGET_H
-#define MOZIQWIDGET_H
-
-#include <QApplication>
-#include <QGraphicsWidget>
-#include <QGraphicsView>
-#include "mozqglwidgetwrapper.h"
-
-#include "nsCOMPtr.h"
-
-#ifdef MOZ_ENABLE_MEEGOTOUCH
-#include <MSceneWindow>
-#include <MInputMethodState>
-#include <QtGui/QGraphicsSceneResizeEvent>
-#include <QTimer>
-#endif
-
-class nsWindow;
-
-class IMozQWidget : public QGraphicsWidget
-{
-    Q_OBJECT
-public:
-    /**
-     * Mozilla helper.
-     */
-    virtual void setModal(bool) {}
-    virtual void dropReceiver() { };
-    virtual nsWindow* getReceiver() { return nullptr; };
-
-    virtual void activate() {}
-    virtual void deactivate() {}
-
-    /**
-     * VirtualKeyboardIntegration
-     */
-    virtual bool isVKBOpen() { return false; }
-
-    virtual void NotifyVKB(const QRect& rect) {}
-    virtual void SwitchToForeground() {}
-    virtual void SwitchToBackground() {}
-};
-
-class MozQGraphicsViewEvents
-{
-public:
-
-    MozQGraphicsViewEvents(QGraphicsView* aView)
-     : mView(aView)
-    { }
-
-    void handleEvent(QEvent* aEvent, IMozQWidget* aTopLevel)
-    {
-        if (!aEvent)
-            return;
-        if (aEvent->type() == QEvent::WindowActivate) {
-            if (aTopLevel)
-                aTopLevel->activate();
-        }
-
-        if (aEvent->type() == QEvent::WindowDeactivate) {
-            if (aTopLevel)
-                aTopLevel->deactivate();
-        }
-    }
-
-    void handleResizeEvent(QResizeEvent* aEvent, IMozQWidget* aTopLevel)
-    {
-        if (!aEvent)
-            return;
-        if (aTopLevel) {
-            // transfer new size to graphics widget
-            aTopLevel->setGeometry(0.0, 0.0,
-                static_cast<qreal>(aEvent->size().width()),
-                static_cast<qreal>(aEvent->size().height()));
-            // resize scene rect to vieport size,
-            // to avoid extra scrolling from QAbstractScrollable
-            if (mView)
-                mView->setSceneRect(mView->viewport()->rect());
-        }
-    }
-
-    bool handleCloseEvent(QCloseEvent* aEvent, IMozQWidget* aTopLevel)
-    {
-        if (!aEvent)
-            return false;
-        if (aTopLevel) {
-            // close graphics widget instead, this view will be discarded
-            // automatically
-            QApplication::postEvent(aTopLevel, new QCloseEvent(*aEvent));
-            aEvent->ignore();
-            return true;
-        }
-
-        return false;
-    }
-
-private:
-    QGraphicsView* mView;
-};
-
-/**
-    This is a helper class to synchronize the QGraphicsView window with
-    its contained QGraphicsWidget for things like resizing and closing
-    by the user.
-*/
-class MozQGraphicsView : public QGraphicsView
-{
-    Q_OBJECT
-
-public:
-    MozQGraphicsView(QWidget * aParent = nullptr)
-     : QGraphicsView (new QGraphicsScene(), aParent)
-     , mEventHandler(this)
-     , mTopLevelWidget(nullptr)
-     , mGLWidget(0)
-    {
-        setMouseTracking(true);
-        setFrameShape(QFrame::NoFrame);
-    }
-
-    void SetTopLevel(IMozQWidget* aTopLevel, QWidget* aParent)
-    {
-        scene()->addItem(aTopLevel);
-        mTopLevelWidget = aTopLevel;
-    }
-
-    void setGLWidgetEnabled(bool aEnabled)
-    {
-        if (aEnabled) {
-            mGLWidget = new MozQGLWidgetWrapper();
-            mGLWidget->setViewport(this);
-        } else {
-            delete mGLWidget;
-            mGLWidget = 0;
-            setViewport(new QWidget());
-        }
-    }
-
-protected:
-
-    virtual bool event(QEvent* aEvent)
-    {
-        mEventHandler.handleEvent(aEvent, mTopLevelWidget);
-        return QGraphicsView::event(aEvent);
-    }
-
-    virtual void resizeEvent(QResizeEvent* aEvent)
-    {
-        mEventHandler.handleResizeEvent(aEvent, mTopLevelWidget);
-        QGraphicsView::resizeEvent(aEvent);
-    }
-
-    virtual void closeEvent (QCloseEvent* aEvent)
-    {
-        if (!mEventHandler.handleCloseEvent(aEvent, mTopLevelWidget))
-            QGraphicsView::closeEvent(aEvent);
-    }
-
-    virtual void paintEvent(QPaintEvent* aEvent)
-    {
-        if (mGLWidget) {
-            mGLWidget->makeCurrent();
-        }
-        QGraphicsView::paintEvent(aEvent);
-    }
-
-private:
-    MozQGraphicsViewEvents mEventHandler;
-    IMozQWidget* mTopLevelWidget;
-    MozQGLWidgetWrapper* mGLWidget;
-};
-
-#ifdef MOZ_ENABLE_MEEGOTOUCH
-class MozMSceneWindow : public MSceneWindow
-{
-    Q_OBJECT
-public:
-    MozMSceneWindow(IMozQWidget* aTopLevel)
-     : MSceneWindow(aTopLevel->parentItem())
-     , mTopLevelWidget(aTopLevel)
-    {
-        MInputMethodState* inputMethodState = MInputMethodState::instance();
-        if (inputMethodState) {
-            connect(inputMethodState, SIGNAL(inputMethodAreaChanged(const QRect&)),
-                    this, SLOT(VisibleScreenAreaChanged(const QRect&)));
-        }
-    }
-
-    void SetTopLevel(IMozQWidget* aTopLevel)
-    {
-        mTopLevelWidget = aTopLevel;
-        mTopLevelWidget->setParentItem(this);
-        mTopLevelWidget->installEventFilter(this);
-    }
-
-protected:
-    virtual void resizeEvent(QGraphicsSceneResizeEvent* aEvent)
-    {
-        mCurrentSize = aEvent->newSize();
-        MSceneWindow::resizeEvent(aEvent);
-        CheckTopLevelSize();
-    }
-
-    virtual bool eventFilter(QObject* watched, QEvent* e)
-    {
-        if (e->type() == QEvent::GraphicsSceneResize ||
-            e->type() == QEvent::GraphicsSceneMove) {
-
-            //Do this in next event loop, or we are in recursion!
-            QTimer::singleShot(0, this, SLOT(CheckTopLevelSize()));
-        }
-
-        return false;
-    }
-
-private Q_SLOTS:
-    void CheckTopLevelSize()
-    {
-        if (mTopLevelWidget) {
-            qreal xpos = 0;
-            qreal ypos = 0;
-            qreal width = mCurrentSize.width();
-            qreal height = mCurrentSize.height();
-
-            // transfer new size to graphics widget if changed
-            QRectF r = mTopLevelWidget->geometry();
-            if (r != QRectF(xpos, ypos, width, height)) {
-                mTopLevelWidget->setGeometry(xpos, ypos, width, height);
-            }
-        }
-    }
-
-    void VisibleScreenAreaChanged(const QRect& rect) {
-        if (mTopLevelWidget) {
-            mTopLevelWidget->NotifyVKB(rect);
-        }
-    }
-
-private:
-    IMozQWidget* mTopLevelWidget;
-    QSizeF mCurrentSize;
-};
-
-/**
-  This is a helper class to synchronize the MWindow window with
-  its contained QGraphicsWidget for things like resizing and closing
-  by the user.
-*/
-class MozMGraphicsView : public MWindow
-{
-    Q_OBJECT
-public:
-    MozMGraphicsView(QWidget* aParent = nullptr)
-     : MWindow(aParent)
-     , mEventHandler(this)
-     , mTopLevelWidget(nullptr)
-     , mSceneWin(nullptr)
-    {
-        QObject::connect(this, SIGNAL(switcherEntered()), this, SLOT(onSwitcherEntered()));
-        QObject::connect(this, SIGNAL(switcherExited()), this, SLOT(onSwitcherExited()));
-        setFrameShape(QFrame::NoFrame);
-    }
-
-    void SetTopLevel(IMozQWidget* aTopLevel, QWidget* aParent)
-    {
-        if (!mSceneWin) {
-            mSceneWin = new MozMSceneWindow(aTopLevel);
-            mSceneWin->appear(this);
-        }
-        mSceneWin->SetTopLevel(aTopLevel);
-        mTopLevelWidget = aTopLevel;
-    }
-
-public Q_SLOTS:
-    void onSwitcherEntered() {
-        if (mTopLevelWidget) {
-            mTopLevelWidget->SwitchToBackground();
-        }
-    }
-    void onSwitcherExited() {
-        if (mTopLevelWidget) {
-            mTopLevelWidget->SwitchToForeground();
-        }
-    }
-
-protected:
-    virtual bool event(QEvent* aEvent) {
-        mEventHandler.handleEvent(aEvent, mTopLevelWidget);
-        return MWindow::event(aEvent);
-    }
-
-    virtual void resizeEvent(QResizeEvent* aEvent)
-    {
-        setSceneRect(viewport()->rect());
-        MWindow::resizeEvent(aEvent);
-    }
-
-    virtual void closeEvent (QCloseEvent* aEvent)
-    {
-        if (!mEventHandler.handleCloseEvent(aEvent, mTopLevelWidget)) {
-            MWindow::closeEvent(aEvent);
-        }
-    }
-
-private:
-    MozQGraphicsViewEvents mEventHandler;
-    IMozQWidget* mTopLevelWidget;
-    MozMSceneWindow* mSceneWin;
-};
-
-#endif /* MOZ_ENABLE_MEEGOTOUCH */
-#endif
deleted file mode 100644
--- a/widget/qt/mozqglwidgetwrapper.cpp
+++ /dev/null
@@ -1,41 +0,0 @@
-/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
-/* vim: set ts=4 et sw=4 tw=80: */
-/* 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 "mozqglwidgetwrapper.h"
-#include <QGraphicsView>
-#include <QtOpenGL/QGLWidget>
-#include <QtOpenGL/QGLContext>
-
-MozQGLWidgetWrapper::MozQGLWidgetWrapper()
-  : mWidget(new QGLWidget())
-{
-}
-
-MozQGLWidgetWrapper::~MozQGLWidgetWrapper()
-{
-    delete mWidget;
-}
-
-void MozQGLWidgetWrapper::makeCurrent()
-{
-    mWidget->makeCurrent();
-}
-
-void MozQGLWidgetWrapper::setViewport(QGraphicsView* aView)
-{
-    aView->setViewport(mWidget);
-}
-
-bool MozQGLWidgetWrapper::hasGLContext(QGraphicsView* aView)
-{
-    return aView && qobject_cast<QGLWidget*>(aView->viewport());
-}
-
-bool MozQGLWidgetWrapper::isRGBAContext()
-{
-    QGLContext* context = const_cast<QGLContext*>(QGLContext::currentContext());
-    return context && context->format().alpha();
-}
\ No newline at end of file
deleted file mode 100644
--- a/widget/qt/mozqglwidgetwrapper.h
+++ /dev/null
@@ -1,30 +0,0 @@
-/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
-/* vim: set ts=4 et sw=4 tw=80: */
-/* 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 MOZQGLWIDGETWRAPPER_H
-#define MOZQGLWIDGETWRAPPER_H
-
-/*
- * qgl.h and GLDefs.h has conflicts in type defines
- * QGLWidget wrapper class helps to avoid including qgl.h with mozilla gl includes
- */
-
-class QGLWidget;
-class QGraphicsView;
-class MozQGLWidgetWrapper
-{
-public:
-    MozQGLWidgetWrapper();
-    ~MozQGLWidgetWrapper();
-    void makeCurrent();
-    void setViewport(QGraphicsView*);
-    static bool hasGLContext(QGraphicsView*);
-    static bool isRGBAContext();
-private:
-    QGLWidget* mWidget;
-};
-
-#endif
deleted file mode 100644
--- a/widget/qt/mozqorientationsensorfilter.cpp
+++ /dev/null
@@ -1,94 +0,0 @@
-/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
-/* vim: set ts=4 et sw=4 tw=80: */
-/* 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 "mozqorientationsensorfilter.h"
-#ifdef MOZ_ENABLE_MEEGOTOUCH
-#include <MApplication>
-#include <MWindow>
-#include <MSceneManager>
-#endif
-#include "nsXULAppAPI.h"
-
-using namespace QtMobility;
-
-int MozQOrientationSensorFilter::mWindowRotationAngle = 0;
-QTransform MozQOrientationSensorFilter::mWindowRotationTransform;
-
-bool
-MozQOrientationSensorFilter::filter(QOrientationReading* reading)
-{
-    switch (reading->orientation()) {
-    //The Top edge of the device is pointing up.
-    case QOrientationReading::TopDown:
-        mWindowRotationAngle = 90;
-        break;
-    //The Top edge of the device is pointing down.
-    case QOrientationReading::TopUp:
-        mWindowRotationAngle = 270;
-        break;
-    //The Left edge of the device is pointing up.
-    case QOrientationReading::LeftUp:
-        mWindowRotationAngle = 180;
-        break;
-    //The Right edge of the device is pointing up.
-    case QOrientationReading::RightUp:
-        mWindowRotationAngle = 0;
-        break;
-    //The Face of the device is pointing up.
-    case QOrientationReading::FaceUp:
-    //The Face of the device is pointing down.
-    case QOrientationReading::FaceDown:
-    //The orientation is unknown.
-    case QOrientationReading::Undefined:
-    default:
-        return true;
-    }
-
-    mWindowRotationTransform = QTransform();
-    mWindowRotationTransform.rotate(mWindowRotationAngle);
-
-#ifdef MOZ_ENABLE_MEEGOTOUCH
-    if (XRE_GetProcessType() == GeckoProcessType_Default) {
-        MWindow* window = MApplication::activeWindow();
-        if (window && window->sceneManager()) {
-            window->sceneManager()->
-                setOrientationAngle((M::OrientationAngle)mWindowRotationAngle,
-                                    MSceneManager::ImmediateTransition);
-        }
-    }
-#else
-    Q_EMIT orientationChanged();
-#endif
-
-    return true; // don't store the reading in the sensor
-}
-
-int
-MozQOrientationSensorFilter::GetWindowRotationAngle()
-{
-#ifdef MOZ_ENABLE_MEEGOTOUCH
-    if (XRE_GetProcessType() == GeckoProcessType_Default) {
-        MWindow* window = MApplication::activeWindow();
-        if (window) {
-            M::OrientationAngle angle = window->orientationAngle();
-            if (mWindowRotationAngle != angle) {
-                mWindowRotationAngle = angle;
-                mWindowRotationTransform = QTransform();
-                mWindowRotationTransform.rotate(mWindowRotationAngle);
-            }
-        }
-    }
-#endif
-    return mWindowRotationAngle;
-}
-
-QTransform&
-MozQOrientationSensorFilter::GetRotationTransform()
-{
-    GetWindowRotationAngle();
-    return mWindowRotationTransform;
-}
-
deleted file mode 100644
--- a/widget/qt/mozqorientationsensorfilter.h
+++ /dev/null
@@ -1,47 +0,0 @@
-/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
-/* vim: set ts=4 et sw=4 tw=80: */
-/* 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 MOZQORIENTATIONMODULE_H
-#define MOZQORIENTATIONMODULE_H
-
-#include <QtSensors/QOrientationReading>
-#include <QtSensors/QOrientationFilter>
-#include <QObject>
-#include <QTransform>
-
-
-class MozQOrientationSensorFilter : public QObject
-                                  , public QtMobility::QOrientationFilter
-{
-    Q_OBJECT
-
-public:
-    MozQOrientationSensorFilter()
-    {
-        mWindowRotationAngle = 0;
-    }
-
-    virtual ~MozQOrientationSensorFilter(){}
-
-    virtual bool filter(QtMobility::QOrientationReading* reading);
-
-    static int GetWindowRotationAngle();
-    static QTransform& GetRotationTransform();
-
-Q_SIGNALS:
-    void orientationChanged();
-
-private:
-    bool filter(QtMobility::QSensorReading *reading)
-    {
-        return filter(static_cast<QtMobility::QOrientationReading*>(reading));
-    }
-
-    static int mWindowRotationAngle;
-    static QTransform mWindowRotationTransform;
-};
-
-#endif
--- a/widget/qt/mozqwidget.cpp
+++ b/widget/qt/mozqwidget.cpp
@@ -1,404 +1,183 @@
 /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
 /* vim: set ts=4 et sw=4 tw=80: */
 /* 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 <QGraphicsSceneHoverEvent>
-#include <QGraphicsSceneMouseEvent>
-#if (QT_VERSION < QT_VERSION_CHECK(5, 0, 0))
-#include <QInputContext>
-#endif
-#include <QtCore/QTimer>
-// Solve conflict of qgl.h and GLDefs.h
-#define GLdouble_defined 1
+#include <QtCore/QCoreApplication>
+#include <QtGui/QResizeEvent>
+
 #include "mozqwidget.h"
 #include "nsWindow.h"
 
-#include "nsIObserverService.h"
-#include "mozilla/Services.h"
-#include "mozilla/TextEvents.h"
-
-
-#ifdef MOZ_ENABLE_QTMOBILITY
-#include "mozqorientationsensorfilter.h"
-#ifdef MOZ_X11
-#include <QX11Info>
-#include <X11/Xlib.h>
-#include <X11/Xatom.h>
-# undef KeyPress
-# undef KeyRelease
-# undef CursorShape
-#endif //MOZ_X11
-#endif //MOZ_ENABLE_QTMOBILITY
-
-/*
-  Pure Qt is lacking a clear API to get the current state of the VKB (opened
-  or closed).
-*/
-static bool gKeyboardOpen = false;
+using namespace mozilla::widget;
 
-/*
-  In case we could not open the keyboard, we will try again when the focus
-  event is sent.  This can happen if the keyboard is asked for before the
-  window is focused. This global is used to track that case.
-*/
-static bool gFailedOpenKeyboard = false;
- 
-/*
-  For websites that focus editable elements during other operations for a very
-  short time, we add some decoupling to prevent the VKB from appearing and 
-  reappearing for a very short time. This global is set when the keyboard should
-  be opened and if it is still set when a timer runs out, the VKB is really
-  shown.
-*/
-static bool gPendingVKBOpen = false;
-
-/*
-  Contains the last preedit String, this is needed in order to generate KeyEvents
-*/
-static QString gLastPreeditString;
-
-MozQWidget::MozQWidget(nsWindow* aReceiver, QGraphicsItem* aParent)
-    : mReceiver(aReceiver)
+MozQWidget::MozQWidget(nsWindow* aReceiver, QWindow* aParent)
+  : QWindow(aParent)
+  , mReceiver(aReceiver)
+  , mUpdatePending(false)
 {
-     setParentItem(aParent);
-#if (QT_VERSION >= QT_VERSION_CHECK(4, 6, 0))
-     setFlag(QGraphicsItem::ItemAcceptsInputMethod);
-     setAcceptTouchEvents(true);
-#endif
-     setAcceptHoverEvents(true);
+    mReceiver->GetWindowType(mWindowType);
 }
 
 MozQWidget::~MozQWidget()
 {
-    if (mReceiver)
-        mReceiver->QWidgetDestroyed();
-}
-
-void MozQWidget::paint(QPainter* aPainter, const QStyleOptionGraphicsItem* aOption, QWidget* aWidget /*= 0*/)
-{
-    if (mReceiver)
-        mReceiver->DoPaint(aPainter, aOption, aWidget);
-}
-
-void MozQWidget::activate()
-{
-    // ensure that the keyboard is hidden when we activate the window
-    hideVKB();
-    mReceiver->DispatchActivateEventOnTopLevelWindow();
-}
-
-void MozQWidget::deactivate()
-{
-    // ensure that the keyboard is hidden when we deactivate the window
-    hideVKB();
-    mReceiver->DispatchDeactivateEventOnTopLevelWindow();
-}
-
-void MozQWidget::resizeEvent(QGraphicsSceneResizeEvent* aEvent)
-{
-    mReceiver->OnResizeEvent(aEvent);
-}
-
-void MozQWidget::contextMenuEvent(QGraphicsSceneContextMenuEvent* aEvent)
-{
-    mReceiver->contextMenuEvent(aEvent);
 }
 
-void MozQWidget::dragEnterEvent(QGraphicsSceneDragDropEvent* aEvent)
-{
-    mReceiver->OnDragEnter(aEvent);
-}
-
-void MozQWidget::dragLeaveEvent(QGraphicsSceneDragDropEvent* aEvent)
+void MozQWidget::render(QPainter* painter)
 {
-    mReceiver->OnDragLeaveEvent(aEvent);
-}
-
-void MozQWidget::dragMoveEvent(QGraphicsSceneDragDropEvent* aEvent)
-{
-    mReceiver->OnDragMotionEvent(aEvent);
+    Q_UNUSED(painter);
 }
 
-void MozQWidget::dropEvent(QGraphicsSceneDragDropEvent* aEvent)
-{
-    mReceiver->OnDragDropEvent(aEvent);
-}
-
-void MozQWidget::focusInEvent(QFocusEvent* aEvent)
+void MozQWidget::renderLater()
 {
-    mReceiver->OnFocusInEvent(aEvent);
-
-    // The application requested the VKB during startup but did not manage
-    // to open it, because there was no focused window yet so we do it now by
-    // requesting the VKB without any timeout.
-    if (gFailedOpenKeyboard)
-        requestVKB(0, this);
-}
-
-#ifdef MOZ_ENABLE_QTMOBILITY
-void MozQWidget::orientationChanged()
-{
-    if (!scene() || !scene()->views().size()) {
+    if (!isExposed() || eWindowType_child != mWindowType || !isVisible()) {
         return;
     }
 
-    NS_ASSERTION(scene()->views().size() == 1, "Not exactly one view for our scene!");
-    QTransform& transform = MozQOrientationSensorFilter::GetRotationTransform();
-    QRect scrTrRect = transform.mapRect(scene()->views()[0]->rect());
+    if (!mUpdatePending) {
+        mUpdatePending = true;
+        QCoreApplication::postEvent(this, new QEvent(QEvent::UpdateRequest));
+    }
+}
 
-    setTransformOriginPoint(scene()->views()[0]->size().width() / 2, scene()->views()[0]->size().height() / 2);
-    scene()->views()[0]->setTransform(transform);
-    int orientation = MozQOrientationSensorFilter::GetWindowRotationAngle();
-    if (orientation == 0 || orientation ==  180) {
-        setPos(0,0);
-    } else {
-        setPos(-(scrTrRect.size().width() - scrTrRect.size().height()) / 2,
-               (scrTrRect.size().width() - scrTrRect.size().height()) / 2);
-    }
-    resize(scrTrRect.size());
-    scene()->setSceneRect(QRectF(QPointF(0, 0), scrTrRect.size()));
-#ifdef MOZ_X11
-    Display* display = QX11Info::display();
-    if (!display) {
+void MozQWidget::renderNow()
+{
+    if (!isExposed() || eWindowType_child != mWindowType || !isVisible()) {
         return;
     }
 
-    Atom orientationAngleAtom = XInternAtom(display, "_MEEGOTOUCH_ORIENTATION_ANGLE", False);
-    XChangeProperty(display, scene()->views()[0]->effectiveWinId(),
-                    orientationAngleAtom, XA_CARDINAL, 32,
-                    PropModeReplace, (unsigned char*)&orientation, 1);
-#endif
+    mReceiver->OnPaint();
 }
-#endif
 
-void MozQWidget::focusOutEvent(QFocusEvent* aEvent)
+bool MozQWidget::event(QEvent* event)
 {
-    mReceiver->OnFocusOutEvent(aEvent);
-    //OtherFocusReason most like means VKB was closed manual (done button)
-    if (aEvent->reason() == Qt::OtherFocusReason && gKeyboardOpen) {
-        hideVKB();
+    switch (event->type()) {
+    case QEvent::UpdateRequest:
+        mUpdatePending = false;
+        renderNow();
+        return true;
+    default:
+        return QWindow::event(event);
     }
 }
 
-void MozQWidget::hoverEnterEvent(QGraphicsSceneHoverEvent* aEvent)
+void MozQWidget::exposeEvent(QExposeEvent* event)
 {
-    mReceiver->OnEnterNotifyEvent(aEvent);
-}
+    Q_UNUSED(event);
+    if (!isExposed() || eWindowType_child != mWindowType || !isVisible()) {
+        return;
+    }
+    LOG(("MozQWidget::%s [%p] flags:%x\n", __FUNCTION__, (void *)this, flags()));
+    renderNow();
 
-void MozQWidget::hoverLeaveEvent(QGraphicsSceneHoverEvent* aEvent)
-{
-    mReceiver->OnLeaveNotifyEvent(aEvent);
 }
 
-void MozQWidget::hoverMoveEvent(QGraphicsSceneHoverEvent* aEvent)
+void MozQWidget::resizeEvent(QResizeEvent* event)
 {
-    mReceiver->OnMotionNotifyEvent(aEvent->pos(), aEvent->modifiers());
+    LOG(("MozQWidget::%s [%p]\n", __FUNCTION__, (void *)this));
+    mReceiver->resizeEvent(event);
+    QWindow::resizeEvent(event);
 }
 
-void MozQWidget::keyPressEvent(QKeyEvent* aEvent)
+void MozQWidget::focusInEvent(QFocusEvent* event)
 {
-    mReceiver->OnKeyPressEvent(aEvent);
-}
-
-void MozQWidget::keyReleaseEvent(QKeyEvent* aEvent)
-{
-    mReceiver->OnKeyReleaseEvent(aEvent);
+    LOG(("MozQWidget::%s [%p]\n", __FUNCTION__, (void *)this));
+    mReceiver->focusInEvent(event);
+    QWindow::focusInEvent(event);
 }
 
-void MozQWidget::inputMethodEvent(QInputMethodEvent* aEvent)
+void MozQWidget::focusOutEvent(QFocusEvent* event)
 {
-    QString currentPreeditString = aEvent->preeditString();
-    QString currentCommitString = aEvent->commitString();
+    LOG(("MozQWidget::%s [%p]\n", __FUNCTION__, (void *)this));
+    mReceiver->focusOutEvent(event);
+    QWindow::focusOutEvent(event);
+}
 
-    //first check for some controllkeys send as text...
-    if (currentCommitString == " ") {
-        sendPressReleaseKeyEvent(Qt::Key_Space, currentCommitString.unicode());
-    } else if (currentCommitString == "\n") {
-        sendPressReleaseKeyEvent(Qt::Key_Return, currentCommitString.unicode());
-    } else if (currentCommitString.isEmpty()) {
-        //if its no controllkey than check if current Commit is empty
-        //if yes than we have some preedit text here
-        if (currentPreeditString.length() == 1 && gLastPreeditString.isEmpty()) {
-            //Preedit text can change its entire look'a'like
-            //check if length of new compared to the old is 1,
-            //means that its a new startup
-            sendPressReleaseKeyEvent(0, currentPreeditString.unicode());
-        } else if (currentPreeditString.startsWith(gLastPreeditString)) {
-            //Length was not 1 or not a new startup
-            //check if the current preedit starts with the last one,
-            //if so: Add new letters (note: this can be more then one new letter)
-            const QChar * text = currentPreeditString.unicode();
-            for (int i = gLastPreeditString.length(); i < currentPreeditString.length(); i++) {
-                sendPressReleaseKeyEvent(0, &text[i]);
-            }
-        } else {
-            //last possible case, we had a PreeditString which was now completely changed.
-            //first, check if just one letter was removed (normal Backspace case!)
-            //if so: just send the backspace
-            QString tempLastPre = gLastPreeditString;
-            tempLastPre.truncate(gLastPreeditString.length()-1);
-            if (currentPreeditString == tempLastPre) {
-                sendPressReleaseKeyEvent(Qt::Key_Backspace);
-            } else if (currentPreeditString != tempLastPre) {
-                //more than one character changed, so just renew everything
-                //delete all preedit
-                for (int i = 0; i < gLastPreeditString.length(); i++) {
-                    sendPressReleaseKeyEvent(Qt::Key_Backspace);
-                }
-                //send new Preedit
-                const QChar * text = currentPreeditString.unicode();
-                for (int i = 0; i < currentPreeditString.length(); i++) {
-                    sendPressReleaseKeyEvent(0, &text[i]);
-                }
-            }
-        }
-    } else if (gLastPreeditString != currentCommitString) {
-        //User commited something
-        if (currentCommitString.length() == 1 && gLastPreeditString.isEmpty()) {
-            //if commit string ist one and there is no Preedit String
-            //case i.e. when no error correction is enabled in the system (default meego.com)
-            sendPressReleaseKeyEvent(0, currentCommitString.unicode());
-        } else {
-            //There is a Preedit, first remove it
-            for (int i = 0; i < gLastPreeditString.length(); i++) {
-                sendPressReleaseKeyEvent(Qt::Key_Backspace);
-            }
-            //Now push commited String into
-            const QChar * text = currentCommitString.unicode();
-            for (int i = 0; i < currentCommitString.length(); i++) {
-                sendPressReleaseKeyEvent(0, &text[i]);
-            }
-        }
-    }
+void MozQWidget::hideEvent(QHideEvent* event)
+{
+    LOG(("MozQWidget::%s [%p]\n", __FUNCTION__, (void *)this));
+    mReceiver->hideEvent(event);
+    QWindow::hideEvent(event);
+}
 
-    //save preedit for next round.
-    gLastPreeditString = currentPreeditString;
+void MozQWidget::keyPressEvent(QKeyEvent* event)
+{
+    LOG(("MozQWidget::%s [%p]\n", __FUNCTION__, (void *)this));
+    mReceiver->keyPressEvent(event);
+    QWindow::keyPressEvent(event);
+}
 
-    //pre edit is continues string of new chars pressed by the user.
-    //if pre edit is changing rapidly without commit string first then user choose some overed text
-    //if commitstring comes directly after, forget about it
-    QGraphicsWidget::inputMethodEvent(aEvent);
+void MozQWidget::keyReleaseEvent(QKeyEvent* event)
+{
+    LOG(("MozQWidget::%s [%p]\n", __FUNCTION__, (void *)this));
+    mReceiver->keyReleaseEvent(event);
+    QWindow::keyReleaseEvent(event);
 }
 
-void MozQWidget::sendPressReleaseKeyEvent(int key,
-                                          const QChar* letter,
-                                          bool autorep,
-                                          ushort count)
+void MozQWidget::mouseDoubleClickEvent(QMouseEvent* event)
 {
-    Qt::KeyboardModifiers modifiers  = Qt::NoModifier;
-    if (letter && letter->isUpper()) {
-        modifiers = Qt::ShiftModifier;
-    }
-
-    if (letter) {
-        // Handle as TextEvent
-        mozilla::WidgetCompositionEvent start(true, NS_COMPOSITION_START,
-                                              mReceiver);
-        mReceiver->DispatchEvent(&start);
+    LOG(("MozQWidget::%s [%p]\n", __FUNCTION__, (void *)this));
+    mReceiver->mouseDoubleClickEvent(event);
+    QWindow::mouseDoubleClickEvent(event);
+}
 
-        mozilla::WidgetTextEvent text(true, NS_TEXT_TEXT, mReceiver);
-        QString commitString = QString(*letter);
-        text.theText.Assign(commitString.utf16());
-        mReceiver->DispatchEvent(&text);
-
-        mozilla::WidgetCompositionEvent end(true, NS_COMPOSITION_END,
-                                            mReceiver);
-        mReceiver->DispatchEvent(&end);
-        return;
-    }
-
-    QKeyEvent press(QEvent::KeyPress, key, modifiers, QString(), autorep, count);
-    mReceiver->OnKeyPressEvent(&press);
-    QKeyEvent release(QEvent::KeyRelease, key, modifiers, QString(), autorep, count);
-    mReceiver->OnKeyReleaseEvent(&release);
+void MozQWidget::mouseMoveEvent(QMouseEvent* event)
+{
+    mReceiver->mouseMoveEvent(event);
+    QWindow::mouseMoveEvent(event);
 }
 
-void MozQWidget::mouseDoubleClickEvent(QGraphicsSceneMouseEvent* aEvent)
+void MozQWidget::mousePressEvent(QMouseEvent* event)
 {
-    // Qt sends double click event, but not second press event.
-    mReceiver->OnButtonPressEvent(aEvent);
-    mReceiver->OnMouseDoubleClickEvent(aEvent);
+    LOG(("MozQWidget::%s [%p]\n", __FUNCTION__, (void *)this));
+    mReceiver->mousePressEvent(event);
+    QWindow::mousePressEvent(event);
 }
 
-void MozQWidget::mouseMoveEvent(QGraphicsSceneMouseEvent* aEvent)
-{
-    mReceiver->OnMotionNotifyEvent(aEvent->pos(), aEvent->modifiers());
-}
-
-void MozQWidget::mousePressEvent(QGraphicsSceneMouseEvent* aEvent)
+void MozQWidget::mouseReleaseEvent(QMouseEvent* event)
 {
-    mReceiver->OnButtonPressEvent(aEvent);
-}
-
-void MozQWidget::mouseReleaseEvent(QGraphicsSceneMouseEvent* aEvent)
-{
-    mReceiver->OnButtonReleaseEvent(aEvent);
+    LOG(("MozQWidget::%s [%p]\n", __FUNCTION__, (void *)this));
+    mReceiver->mouseReleaseEvent(event);
+    QWindow::mouseReleaseEvent(event);
 }
 
-bool MozQWidget::event ( QEvent * event )
+void MozQWidget::moveEvent(QMoveEvent* event)
 {
-    // check receiver, since due to deleteLater() call it's possible, that
-    // events pass loop after receiver's destroy and while widget is still alive
-    if (!mReceiver)
-        return QGraphicsWidget::event(event);
+    LOG(("MozQWidget::%s [%p]\n", __FUNCTION__, (void *)this));
+    mReceiver->moveEvent(event);
+    QWindow::moveEvent(event);
+}
 
-#if (QT_VERSION >= QT_VERSION_CHECK(4, 6, 0))
-    switch (event->type())
-    {
-    case QEvent::TouchBegin:
-    case QEvent::TouchEnd:
-    case QEvent::TouchUpdate:
-    {
-        // Do not send this event to other handlers, this is needed
-        // to be able to receive the gesture events
-        bool handled = false;
-        mReceiver->OnTouchEvent(static_cast<QTouchEvent *>(event),handled);
-        return handled;
-    }
-    case (QEvent::Gesture):
-    {
-        bool handled = false;
-        mReceiver->OnGestureEvent(static_cast<QGestureEvent*>(event),handled);
-        return handled;
-    }
-    default:
-        break;
-    }
-#endif
-    return QGraphicsWidget::event(event);
+void MozQWidget::showEvent(QShowEvent* event)
+{
+    LOG(("MozQWidget::%s [%p]\n", __FUNCTION__, (void *)this));
+    mReceiver->showEvent(event);
+    QWindow::showEvent(event);
 }
 
-void MozQWidget::wheelEvent(QGraphicsSceneWheelEvent* aEvent)
+void MozQWidget::wheelEvent(QWheelEvent* event)
 {
-    mReceiver->OnScrollEvent(aEvent);
-}
-
-void MozQWidget::closeEvent(QCloseEvent* aEvent)
-{
-    mReceiver->OnCloseEvent(aEvent);
+    LOG(("MozQWidget::%s [%p]\n", __FUNCTION__, (void *)this));
+    mReceiver->wheelEvent(event);
+    QWindow::wheelEvent(event);
 }
 
-void MozQWidget::hideEvent(QHideEvent* aEvent)
+void MozQWidget::tabletEvent(QTabletEvent* event)
 {
-    if (mReceiver) {
-        mReceiver->hideEvent(aEvent);
-    }
-    QGraphicsWidget::hideEvent(aEvent);
+    LOG(("MozQWidget::%s [%p]\n", __FUNCTION__, (void *)this));
+    QWindow::tabletEvent(event);
 }
 
-void MozQWidget::showEvent(QShowEvent* aEvent)
+void MozQWidget::touchEvent(QTouchEvent* event)
 {
-    if (mReceiver) {
-        mReceiver->showEvent(aEvent);
-    }
-    QGraphicsWidget::showEvent(aEvent);
+    LOG(("MozQWidget::%s [%p]\n", __FUNCTION__, (void *)this));
+    QWindow::touchEvent(event);
 }
 
 void MozQWidget::SetCursor(nsCursor aCursor)
 {
     Qt::CursorShape cursor = Qt::ArrowCursor;
     switch(aCursor) {
     case eCursor_standard:
         cursor = Qt::ArrowCursor;
@@ -445,180 +224,8 @@ void MozQWidget::SetCursor(nsCursor aCur
     case eCursor_zoom_out:
 
     default:
         break;
     }
 
     setCursor(cursor);
 }
-
-void MozQWidget::SetCursor(const QPixmap& aCursor, int aHotX, int aHotY)
-{
-    QCursor bitmapCursor(aCursor, aHotX, aHotY);
-    setCursor(bitmapCursor);
-}
-
-void MozQWidget::setModal(bool modal)
-{
-#if QT_VERSION >= 0x040600
-    setPanelModality(modal ? QGraphicsItem::SceneModal : QGraphicsItem::NonModal);
-#else
-    LOG(("Modal QGraphicsWidgets not supported in Qt < 4.6\n"));
-#endif
-}
-
-QVariant MozQWidget::inputMethodQuery(Qt::InputMethodQuery aQuery) const
-{
-    // Additional MeeGo Touch queries, which do not depend on actually
-    // having a focused input field.
-    switch ((int) aQuery) {
-    case 10001: // VisualizationPriorityQuery.
-        // Tells if input method widget wants to have high priority
-        // for visualization. Input methods should honor this and stay
-        // out of widgets space.
-        // Return false, eg. the input method can overlap QGraphicsWKView.
-        return QVariant(false);
-    case 10003: // ImCorrectionEnabledQuery.
-        // Explicit correction enabling for text entries.
-        return QVariant(false);
-    case 10004: // ImModeQuery.
-        // Retrieval mode: normal (0), direct [minics hardware keyboard] (1) or proxy (2)
-        return QVariant::fromValue(0);
-    case 10006: // InputMethodToolbarQuery.
-        // Custom toolbar file name for text entry.
-        return QVariant();
-    }
-
-    // Standard Qt queries dependent on having a focused web text input.
-    switch (aQuery) {
-    case Qt::ImFont:
-        return QVariant(QFont());
-    case Qt::ImMaximumTextLength:
-        return QVariant(); // Means no limit.
-    }
-
-    // Additional MeeGo Touch queries dependent on having a focused web text input
-    switch ((int) aQuery) {
-    case 10002: // PreeditRectangleQuery.
-        // Retrieve bounding rectangle for current preedit text.
-        return QVariant(QRect());
-    }
-
-    return QVariant();
-}
-
-/**
-  Request the VKB and starts a timer with the given timeout in milliseconds.
-  If the request is not canceled when the timer runs out, the VKB is actually
-  shown.
-*/
-void MozQWidget::requestVKB(int aTimeout, QObject* aWidget)
-{
-    if (!gPendingVKBOpen) {
-        gPendingVKBOpen = true;
-
-        if (aTimeout == 0 || !aWidget) {
-            showVKB();
-        } else {
-            QTimer::singleShot(aTimeout, aWidget, SLOT(showVKB()));
-        }
-    }
-}
-
-void MozQWidget::showVKB()
-{
-    // skip showing of keyboard if not pending
-    if (!gPendingVKBOpen) {
-        return;
-    }
-
-    gPendingVKBOpen = false;
-
-#if (QT_VERSION >= QT_VERSION_CHECK(4, 6, 0)) && (QT_VERSION < QT_VERSION_CHECK(5, 0, 0))
-    QWidget* focusWidget = qApp->focusWidget();
-
-    if (focusWidget) {
-        QInputContext *inputContext = qApp->inputContext();
-        if (!inputContext) {
-            NS_WARNING("Requesting SIP: but no input context");
-            return;
-        }
-
-        QEvent request(QEvent::RequestSoftwareInputPanel);
-        inputContext->filterEvent(&request);
-        focusWidget->setAttribute(Qt::WA_InputMethodEnabled, true);
-        inputContext->setFocusWidget(focusWidget);
-        gKeyboardOpen = true;
-        gFailedOpenKeyboard = false;
-    }
-    else
-    {
-        // No focused widget yet, so we have to open the VKB later on.
-        gFailedOpenKeyboard = true;
-    }
-#else
-    LOG(("VKB not supported in Qt < 4.6\n"));
-#endif
-}
-
-void MozQWidget::hideVKB()
-{
-    if (gPendingVKBOpen) {
-        // do not really open
-        gPendingVKBOpen = false;
-    }
-
-    if (!gKeyboardOpen) {
-        return;
-    }
-
-#if (QT_VERSION >= QT_VERSION_CHECK(4, 6, 0)) && (QT_VERSION < QT_VERSION_CHECK(5, 0, 0))
-    QInputContext *inputContext = qApp->inputContext();
-    if (!inputContext) {
-        NS_WARNING("Closing SIP: but no input context");
-        return;
-    }
-
-    QEvent request(QEvent::CloseSoftwareInputPanel);
-    inputContext->filterEvent(&request);
-    inputContext->reset();
-    gKeyboardOpen = false;
-#else
-    LOG(("VKB not supported in Qt < 4.6\n"));
-#endif
-}
-
-bool MozQWidget::isVKBOpen()
-{
-    return gKeyboardOpen;
-}
-
-void
-MozQWidget::NotifyVKB(const QRect& rect)
-{
-    QRegion region(scene()->views()[0]->rect());
-    region -= rect;
-    QRectF bounds = mapRectFromScene(region.boundingRect());
-        nsCOMPtr<nsIObserverService> observerService = mozilla::services::GetObserverService();
-    if (observerService) {
-        QString rect = QString("{\"left\": %1, \"top\": %2, \"right\": %3, \"bottom\": %4}")
-                               .arg(bounds.x()).arg(bounds.y()).arg(bounds.width()).arg(bounds.height());
-        observerService->NotifyObservers(nullptr, "softkb-change", rect.utf16());
-    }
-}
-
-void MozQWidget::SwitchToForeground()
-{
-    nsCOMPtr<nsIObserverService> os = mozilla::services::GetObserverService();
-    if (!os)
-        return;
-    os->NotifyObservers(nullptr, "application-foreground", nullptr);
-}
-
-void MozQWidget::SwitchToBackground()
-{
-    nsCOMPtr<nsIObserverService> os = mozilla::services::GetObserverService();
-    if (!os)
-        return;
-    os->NotifyObservers(nullptr, "application-background", nullptr);
-}
-
--- a/widget/qt/mozqwidget.h
+++ b/widget/qt/mozqwidget.h
@@ -2,84 +2,70 @@
 /* vim: set ts=4 et sw=4 tw=80: */
 /* 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 MOZQWIDGET_H
 #define MOZQWIDGET_H
 
-#include "moziqwidget.h"
 #include "nsIWidget.h"
 
-class MozQWidget : public IMozQWidget
+#include <QtGui/QWindow>
+
+QT_BEGIN_NAMESPACE
+class QPainter;
+class QExposeEvent;
+class QResizeEvent;
+QT_END_NAMESPACE
+
+namespace mozilla {
+namespace widget {
+
+class nsWindow;
+
+class MozQWidget : public QWindow
 {
     Q_OBJECT
 public:
-    MozQWidget(nsWindow* aReceiver, QGraphicsItem *aParent);
-
+    explicit MozQWidget(nsWindow* aReceiver, QWindow* aParent = 0);
     ~MozQWidget();
 
-    /**
-     * Mozilla helper.
-     */
-    virtual void setModal(bool);
-    virtual void SetCursor(nsCursor aCursor);
-    virtual void dropReceiver() { mReceiver = 0x0; };
-    virtual nsWindow* getReceiver() { return mReceiver; };
-
-    virtual void activate();
-    virtual void deactivate();
+    virtual void render(QPainter* painter);
 
-    /**
-     * VirtualKeyboardIntegration
-     */
-    static void requestVKB(int aTimeout = 0, QObject* aWidget = 0);
-    static void hideVKB();
-    virtual bool isVKBOpen();
-
-    virtual void NotifyVKB(const QRect& rect);
-    virtual void SwitchToForeground();
-    virtual void SwitchToBackground();
+    virtual nsWindow* getReceiver() { return mReceiver; };
+    virtual void dropReceiver() { mReceiver = nullptr; };
+    virtual void SetCursor(nsCursor aCursor);
 
 public Q_SLOTS:
-    static void showVKB();
-
-#ifdef MOZ_ENABLE_QTMOBILITY
-    void orientationChanged();
-#endif
+    void renderLater();
+    void renderNow();
 
 protected:
-    virtual void contextMenuEvent(QGraphicsSceneContextMenuEvent* aEvent);
-    virtual void dragEnterEvent(QGraphicsSceneDragDropEvent* aEvent);
-    virtual void dragLeaveEvent(QGraphicsSceneDragDropEvent* aEvent);
-    virtual void dragMoveEvent(QGraphicsSceneDragDropEvent* aEvent);
-    virtual void dropEvent(QGraphicsSceneDragDropEvent* aEvent);
-    virtual void focusInEvent(QFocusEvent* aEvent);
-    virtual void focusOutEvent(QFocusEvent* aEvent);
-    virtual void hoverEnterEvent(QGraphicsSceneHoverEvent* aEvent);
-    virtual void hoverLeaveEvent(QGraphicsSceneHoverEvent* aEvent);
-    virtual void hoverMoveEvent(QGraphicsSceneHoverEvent* aEvent);
-    virtual void keyPressEvent(QKeyEvent* aEvent);
-    virtual void keyReleaseEvent(QKeyEvent* aEvent);
-    virtual void mouseDoubleClickEvent(QGraphicsSceneMouseEvent* aEvent);
-    virtual void mouseMoveEvent(QGraphicsSceneMouseEvent* aEvent);
-    virtual void mousePressEvent(QGraphicsSceneMouseEvent* aEvent);
-    virtual void mouseReleaseEvent(QGraphicsSceneMouseEvent* aEvent);
-    virtual void inputMethodEvent(QInputMethodEvent* aEvent);
-
-    virtual void wheelEvent(QGraphicsSceneWheelEvent* aEvent);
-    virtual void paint(QPainter* aPainter, const QStyleOptionGraphicsItem* aOption, QWidget* aWidget = 0);
-    virtual void resizeEvent(QGraphicsSceneResizeEvent* aEvent);
-    virtual void closeEvent(QCloseEvent* aEvent);
-    virtual void hideEvent(QHideEvent* aEvent);
-    virtual void showEvent(QShowEvent* aEvent);
-    virtual bool event(QEvent* aEvent);
-    virtual QVariant inputMethodQuery(Qt::InputMethodQuery aQuery) const;
-
-    void SetCursor(const QPixmap& aPixmap, int, int);
+    virtual bool event(QEvent* event);
+    virtual void exposeEvent(QExposeEvent* event);
+    virtual void focusInEvent(QFocusEvent* event);
+    virtual void focusOutEvent(QFocusEvent* event);
+    virtual void hideEvent(QHideEvent* event);
+    virtual void keyPressEvent(QKeyEvent* event);
+    virtual void keyReleaseEvent(QKeyEvent* event);
+    virtual void mouseDoubleClickEvent(QMouseEvent* event);
+    virtual void mouseMoveEvent(QMouseEvent* event);
+    virtual void mousePressEvent(QMouseEvent* event);
+    virtual void mouseReleaseEvent(QMouseEvent* event);
+    virtual void moveEvent(QMoveEvent* event);
+    virtual void resizeEvent(QResizeEvent* event);
+    virtual void showEvent(QShowEvent* event);
+    virtual void tabletEvent(QTabletEvent* event);
+    virtual void touchEvent(QTouchEvent* event);
+    virtual void wheelEvent(QWheelEvent* event);
 
 private:
-    void sendPressReleaseKeyEvent(int key, const QChar* letter = 0, bool autorep = false, ushort count = 1);
-    nsWindow *mReceiver;
+    nsWindow* mReceiver;
+    bool mUpdatePending;
+    nsWindowType mWindowType;
 };
 
-#endif
+} // namespace widget
+} // namespace mozilla
+
+#endif // MOZQWIDGET_H
+
--- a/widget/qt/nsAppShell.cpp
+++ b/widget/qt/nsAppShell.cpp
@@ -1,17 +1,17 @@
 /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
 /* vim:expandtab:shiftwidth=4:tabstop=4:
  */
 /* 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 "nsAppShell.h"
-#include <qapplication.h>
+#include <QGuiApplication>
 #include <unistd.h>
 #include <fcntl.h>
 #include <errno.h>
 
 #include <qabstracteventdispatcher.h>
 #include <qthread.h>
 
 #include "prenv.h"
@@ -44,21 +44,17 @@ nsAppShell::Init()
         gWidgetLog = PR_NewLogModule("Widget");
     if (!gWidgetFocusLog)
         gWidgetFocusLog = PR_NewLogModule("WidgetFocus");
     if (!gWidgetIMLog)
         gWidgetIMLog = PR_NewLogModule("WidgetIM");
     if (!gWidgetDrawLog)
         gWidgetDrawLog = PR_NewLogModule("WidgetDraw");
 #endif
-#if (QT_VERSION >= QT_VERSION_CHECK(4, 4, 0))
     sPokeEvent = QEvent::registerEventType();
-#else
-    sPokeEvent = QEvent::User+5000;
-#endif
 
     nsQAppInstance::AddRef();
 
     return nsBaseAppShell::Init();
 }
 
 void
 nsAppShell::ScheduleNativeEventCallback()
--- a/widget/qt/nsBidiKeyboard.cpp
+++ b/widget/qt/nsBidiKeyboard.cpp
@@ -1,17 +1,17 @@
 /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
 /* vim:expandtab:shiftwidth=4:tabstop=4:
  */
 /* 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 <Qt>
-#include <QApplication>
+#include <QGuiApplication>
 
 #include "nsBidiKeyboard.h"
 
 NS_IMPL_ISUPPORTS1(nsBidiKeyboard, nsIBidiKeyboard)
 
 nsBidiKeyboard::nsBidiKeyboard() : nsIBidiKeyboard()
 {
   Reset();
@@ -25,27 +25,23 @@ NS_IMETHODIMP nsBidiKeyboard::Reset()
 {
   return NS_OK;
 }
 
 NS_IMETHODIMP nsBidiKeyboard::IsLangRTL(bool *aIsRTL)
 {
     *aIsRTL = false;
 
-#if (QT_VERSION < QT_VERSION_CHECK(5,0,0))
-    Qt::LayoutDirection layoutDir = QApplication::keyboardInputDirection();
-#else
     QInputMethod* input = qApp->inputMethod();
     Qt::LayoutDirection layoutDir = input ? input->inputDirection() : Qt::LeftToRight;
-#endif
 
     if (layoutDir == Qt::RightToLeft) {
         *aIsRTL = true;
     }
-    
+
     return NS_OK;
 }
 
 NS_IMETHODIMP nsBidiKeyboard::GetHaveBidiKeyboards(bool* aResult)
 {
   // not implemented yet
   return NS_ERROR_NOT_IMPLEMENTED;
 }
--- a/widget/qt/nsClipboard.cpp
+++ b/widget/qt/nsClipboard.cpp
@@ -1,13 +1,13 @@
 /* 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 <QApplication>
+#include <QGuiApplication>
 #include <QMimeData>
 #include <QString>
 #include <QStringList>
 #include <QByteArray>
 #include <QImage>
 #include <QImageWriter>
 #include <QBuffer>
 
@@ -85,17 +85,17 @@ nsClipboard::SetNativeClipboardData( nsI
     nsresult rv = aTransferable->FlavorsTransferableCanExport( getter_AddRefs(flavorList) );
 
     if (NS_FAILED(rv))
     {
         NS_WARNING("nsClipboard::SetNativeClipboardData(): no FlavorsTransferable !");
         return NS_ERROR_FAILURE;
     }
 
-    QClipboard *cb = QApplication::clipboard();
+    QClipboard *cb = QGuiApplication::clipboard();
     QMimeData *mimeData = new QMimeData;
 
     uint32_t flavorCount = 0;
     flavorList->Count(&flavorCount);
     bool imageAdded = false;
 
     for (uint32_t i = 0; i < flavorCount; ++i)
     {
@@ -120,34 +120,34 @@ nsClipboard::SetNativeClipboardData( nsI
                 rv = aTransferable->GetTransferData(flavorStr,getter_AddRefs(clip),&len);
                 nsCOMPtr<nsISupportsString> wideString;
                 wideString = do_QueryInterface(clip);
                 if (!wideString || NS_FAILED(rv))
                     continue;
 
                 nsAutoString utf16string;
                 wideString->GetData(utf16string);
-                QString str = QString::fromUtf16(utf16string.get());
+                QString str = QString::fromUtf16((const ushort*)utf16string.get());
 
                 // Add text to the mimeData
                 mimeData->setText(str);
             }
 
             // html?
             else if (!strcmp(flavorStr.get(), kHTMLMime))
             {
                 rv = aTransferable->GetTransferData(flavorStr,getter_AddRefs(clip),&len);
                 nsCOMPtr<nsISupportsString> wideString;
                 wideString = do_QueryInterface(clip);
                 if (!wideString || NS_FAILED(rv))
                     continue;
 
                 nsAutoString utf16string;
                 wideString->GetData(utf16string);
-                QString str = QString::fromUtf16(utf16string.get());
+                QString str = QString::fromUtf16((const ushort*)utf16string.get());
 
                 // Add html to the mimeData
                 mimeData->setHtml(str);
             }
 
             // image?
             else if (!imageAdded // image is added only once to the clipboard
                      && (!strcmp(flavorStr.get(), kNativeImageMime)
@@ -248,17 +248,17 @@ nsClipboard::GetNativeClipboardData(nsIT
         getter_AddRefs(flavorList));
 
     if (NS_FAILED(errCode))
     {
         NS_WARNING("nsClipboard::GetNativeClipboardData(): no FlavorsTransferable!");
         return NS_ERROR_FAILURE;
     }
 
-    QClipboard *cb = QApplication::clipboard();
+    QClipboard *cb = QGuiApplication::clipboard();
     const QMimeData *mimeData = cb->mimeData(clipboardMode);
 
     // Walk through flavors and see which flavor matches the one being pasted
     uint32_t flavorCount;
     flavorList->Count(&flavorCount);
     nsAutoCString foundFlavor;
 
     for (uint32_t i = 0; i < flavorCount; ++i)
@@ -400,17 +400,17 @@ NS_IMETHODIMP
 nsClipboard::HasDataMatchingFlavors(const char** aFlavorList, uint32_t aLength,
                                     int32_t aWhichClipboard, bool *_retval)
 {
     *_retval = false;
     if (aWhichClipboard != kGlobalClipboard)
         return NS_OK;
 
     // Which kind of data in the clipboard
-    QClipboard *cb = QApplication::clipboard();
+    QClipboard *cb = QGuiApplication::clipboard();
     const QMimeData *mimeData = cb->mimeData();
     const char *flavor=nullptr;
     QStringList formats = mimeData->formats();
     for (uint32_t i = 0; i < aLength; ++i)
     {
         flavor = aFlavorList[i];
         if (flavor)
         {
@@ -539,17 +539,17 @@ nsClipboard::EmptyClipboard(int32_t aWhi
     return NS_OK;
 }
 
 NS_IMETHODIMP
 nsClipboard::SupportsSelectionClipboard(bool *_retval)
 {
     NS_ENSURE_ARG_POINTER(_retval);
 
-    QClipboard *cb = QApplication::clipboard();
+    QClipboard *cb = QGuiApplication::clipboard();
     if (cb->supportsSelection())
     {
         *_retval = true; // we support the selection clipboard 
     }
     else
     {
         *_retval = false;
     }
deleted file mode 100644
--- a/widget/qt/nsCommonWidget.cpp
+++ /dev/null
@@ -1,10 +0,0 @@
-/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
-/* vim:expandtab:shiftwidth=4:tabstop=4:
- */
-/* 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 "nsCommonWidget.h"
-#include "nsQtKeyUtils.h"
-
deleted file mode 100644
--- a/widget/qt/nsCommonWidget.h
+++ /dev/null
@@ -1,22 +0,0 @@
-/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
-/* vim:expandtab:shiftwidth=4:tabstop=4:
- */
-/* 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 __nsCommonWidget_h__
-#define __nsCommonWidget_h__
-
-
-
-class nsCommonWidget : public nsBaseWidget {
-public:
-    nsCommonWidget();
-    virtual ~nsCommonWidget();
-
-
-protected:
-};
-
-#endif /* __nsCommonWidget_h__ */
deleted file mode 100644
--- a/widget/qt/nsDragService.cpp
+++ /dev/null
@@ -1,286 +0,0 @@
-/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
-/* vim:expandtab:shiftwidth=4:tabstop=4:
- */
-/* 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 "qmimedata.h"
-#include "qwidget.h"
-#include "qapplication.h"
-#include "qthread.h"
-
-#include "nsDragService.h"
-#include "nsISupportsPrimitives.h"
-#include "nsXPIDLString.h"
-#include "nsIDOMMouseEvent.h"
-
-NS_IMPL_ADDREF_INHERITED(nsDragService, nsBaseDragService)
-NS_IMPL_RELEASE_INHERITED(nsDragService, nsBaseDragService)
-NS_IMPL_QUERY_INTERFACE2(nsDragService, nsIDragService, nsIDragSession )
-
-nsDragService::nsDragService() : mDrag(nullptr), mHiddenWidget(nullptr)
-{
-}
-
-nsDragService::~nsDragService()
-{
-    /* destructor code */
-    delete mHiddenWidget;
-}
-
-NS_IMETHODIMP
-nsDragService::SetDropActionType( uint32_t aActionType )
-{
-    mDropAction = Qt::IgnoreAction;
-
-    if (aActionType & DRAGDROP_ACTION_COPY)
-    {
-        mDropAction |= Qt::CopyAction;
-    }
-    if (aActionType & DRAGDROP_ACTION_MOVE)
-    {
-        mDropAction |= Qt::MoveAction;
-    }
-    if (aActionType & DRAGDROP_ACTION_LINK)
-    {
-        mDropAction |= Qt::LinkAction;
-    }
-
-    return NS_OK;
-}
-
-NS_IMETHODIMP
-nsDragService::SetupDragSession(
-                                nsISupportsArray *aTransferables,
-                                uint32_t aActionType)
-{
-    uint32_t itemCount = 0;
-    aTransferables->Count(&itemCount);
-    if (0 == itemCount)
-    {
-        NS_WARNING("No items to drag?");
-        return NS_ERROR_FAILURE;
-    }
-
-    if (1 != itemCount)
-    {
-        NS_WARNING("Dragging more than one item, cannot do (yet?)");
-        return NS_ERROR_NOT_IMPLEMENTED;
-    }
-
-    SetDropActionType(aActionType);
-
-    QMimeData *mimeData = new QMimeData;
-
-    nsCOMPtr<nsISupports> genericItem;
-    aTransferables->GetElementAt(0, getter_AddRefs(genericItem));
-    nsCOMPtr<nsITransferable> transferable(do_QueryInterface(genericItem));
-
-    if (transferable)
-    {
-        nsCOMPtr <nsISupportsArray> flavorList;
-        transferable->FlavorsTransferableCanExport(getter_AddRefs(flavorList));
-
-        if (flavorList)
-        {
-            uint32_t flavorCount;
-            flavorList->Count( &flavorCount );
-
-            for (uint32_t flavor=0; flavor < flavorCount; flavor++)
-            {
-                nsCOMPtr<nsISupports> genericWrapper;
-                flavorList->GetElementAt(flavor, getter_AddRefs(genericWrapper));
-                nsCOMPtr<nsISupportsCString> currentFlavor;
-                currentFlavor = do_QueryInterface(genericWrapper);
-
-                if (currentFlavor)
-                {
-                    nsCOMPtr<nsISupports> data;
-                    uint32_t dataLen = 0;
-                    nsXPIDLCString flavorStr;
-                    currentFlavor->ToString(getter_Copies(flavorStr));
-
-                    // Is it some flavor we think we could support?
-                    if (!strcmp(kURLMime, flavorStr.get())
-                     || !strcmp(kURLDataMime, flavorStr.get())
-                     || !strcmp(kURLDescriptionMime, flavorStr.get())
-                     || !strcmp(kHTMLMime, flavorStr.get())
-                     || !strcmp(kUnicodeMime, flavorStr.get())
-                        )
-                    {
-                        transferable->GetTransferData(flavorStr,getter_AddRefs(data),&dataLen);
-
-                        nsCOMPtr<nsISupportsString> wideString;
-                        wideString = do_QueryInterface(data);
-                        if (!wideString)
-                        {
-                            return NS_ERROR_FAILURE;
-                        }
-
-                        nsAutoString utf16string;
-                        wideString->GetData(utf16string);
-                        QByteArray ba((const char*) utf16string.get(), dataLen);
-
-                        mimeData->setData(flavorStr.get(), ba);
-                    }
-                }
-            }
-        }
-    }
-
-    if (qApp->thread() != QThread::currentThread()) {
-        NS_WARNING("Cannot initialize drag session in non main thread");
-        return NS_OK;
-    }
-
-    if (!mHiddenWidget) {
-      mHiddenWidget = new QWidget();
-    }
-    mDrag = new QDrag( mHiddenWidget ); // TODO: Better drag source here?
-    mDrag->setMimeData(mimeData);
-
-    // mDrag and mimeData SHOULD NOT be destroyed. They are destroyed by QT.
-
-    return NS_OK;
-}
-
-/* void invokeDragSession (in nsIDOMNode aDOMNode, in nsISupportsArray aTransferables, in nsIScriptableRegion aRegion, in unsigned long aActionType); */
-NS_IMETHODIMP
-nsDragService::InvokeDragSession(
-                                nsIDOMNode *aDOMNode,
-                                nsISupportsArray *aTransferables,
-                                nsIScriptableRegion *aRegion,
-                                uint32_t aActionType)
-{
-    nsBaseDragService::InvokeDragSession( 
-                                        aDOMNode,
-                                        aTransferables,
-                                        aRegion,
-                                        aActionType);
-
-    SetupDragSession( aTransferables, aActionType);
-
-    return NS_OK;
-}
-
-NS_IMETHODIMP
-nsDragService::ExecuteDrag()
-{
-    if (qApp->thread() == QThread::currentThread()) {
-        mDrag->exec(mDropAction);
-    }
-
-    return NS_OK;
-}
-
-/* void invokeDragSessionWithImage ( nsIDOMNode DOMNode , nsISupportsArray transferableArray , nsIScriptableRegion region , uint32_t actionType , nsIDOMNode image , int32_t imageX , int32_t imageY , nsIDOMMouseEvent dragEvent ); */
-NS_IMETHODIMP
-nsDragService::InvokeDragSessionWithImage(
-                        nsIDOMNode *aDOMNode,
-                        nsISupportsArray*aTransferables,
-                        nsIScriptableRegion* aRegion,
-                        uint32_t aActionType,
-                        nsIDOMNode* aImage,
-                        int32_t aImageX,
-                        int32_t aImageY,
-                        nsIDOMDragEvent* aDragEvent,
-                        nsIDOMDataTransfer* aDataTransfer)
-{
-    nsBaseDragService::InvokeDragSessionWithImage(
-                                        aDOMNode, aTransferables,
-                                        aRegion, aActionType,
-                                        aImage,
-                                        aImageX, aImageY,
-                                        aDragEvent,
-                                        aDataTransfer);
-
-    SetupDragSession( aTransferables, aActionType);
-
-    // Setup Image, and other stuff
-    if (aImage)
-    {
-        // Use the custom image 
-        // (aImageX,aImageY) specifies the offset "within the image where
-        // the cursor would be positioned"
-
-        // So, convert the aImage to QPixmap and X and Y to q QPoint
-        // and then:
-        // mDrag->setPixmap( pixmap ) or mDrag->setDragCursor( pixmap );
-        // mDrad->setHotSpot( point );
-        // TODO: Not implemented yet as this cannot be currently tested
-        NS_WARNING("Support for drag image not implemented");
-    }
-
-    return ExecuteDrag();
-}
-
-NS_IMETHODIMP
-nsDragService::InvokeDragSessionWithSelection(nsISelection* aSelection,
-                                              nsISupportsArray* aTransferableArray,
-                                              uint32_t aActionType,
-                                              nsIDOMDragEvent* aDragEvent,
-                                              nsIDOMDataTransfer* aDataTransfer)
-{
-    nsBaseDragService::InvokeDragSessionWithSelection(
-                                        aSelection,
-                                        aTransferableArray,
-                                        aActionType,
-                                        aDragEvent,
-                                        aDataTransfer);
-
-    SetupDragSession( aTransferableArray, aActionType);
-
-    // Setup selection related properties
-    // There is however nothing that needs to be set
-
-    return ExecuteDrag();
-}
-
-/* nsIDragSession getCurrentSession (); */
-NS_IMETHODIMP
-nsDragService::GetCurrentSession(nsIDragSession **_retval)
-{
-    return NS_ERROR_NOT_IMPLEMENTED;
-}
-
-/* void startDragSession (); */
-NS_IMETHODIMP
-nsDragService::StartDragSession()
-{
-    return nsBaseDragService::StartDragSession();
-}
-
-/* void endDragSession (in bool aDoneDrag); */
-NS_IMETHODIMP
-nsDragService::EndDragSession(bool aDoneDrag)
-{
-    return nsBaseDragService::EndDragSession(aDoneDrag);
-}
-
-/* void fireDragEventAtSource (in unsigned long aMsg); */
-NS_IMETHODIMP
-nsDragService::FireDragEventAtSource(uint32_t aMsg)
-{
-    return nsBaseDragService::FireDragEventAtSource(aMsg);
-}
-
-/* TODO: What is this? */
-NS_IMETHODIMP
-nsDragService::Suppress()
-{
-    return nsBaseDragService::Suppress();
-}
-
-/* TODO: What is this? */
-NS_IMETHODIMP
-nsDragService::Unsuppress()
-{
-    return nsBaseDragService::Unsuppress();
-}
-
-NS_IMETHODIMP
-nsDragService::DragMoved(int32_t aX, int32_t aY)
-{
-    return nsBaseDragService::DragMoved(aX, aY);
-}
deleted file mode 100644
--- a/widget/qt/nsDragService.h
+++ /dev/null
@@ -1,36 +0,0 @@
-/* -*- Mode: c++; tab-width: 2; indent-tabs-mode: nil; -*- */
-/* 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 nsDragService_h__
-#define nsDragService_h__
-
-#include <qdrag.h>
-
-#include "nsBaseDragService.h"
-
-/* Header file */
-class nsDragService : public nsBaseDragService
-{
-public:
-    NS_DECL_ISUPPORTS
-    NS_DECL_NSIDRAGSERVICE
-
-    nsDragService();
-
-private:
-    ~nsDragService();
-
-protected:
-    /* additional members */
-    NS_IMETHODIMP SetupDragSession(nsISupportsArray *aTransferables, uint32_t aActionType);
-    NS_IMETHODIMP SetDropActionType(uint32_t aActionType);
-    NS_IMETHODIMP ExecuteDrag();
-
-    QDrag *mDrag;
-    Qt::DropActions mDropAction;
-    QWidget *mHiddenWidget;
-};
-
-#endif // nsDragService_h__
deleted file mode 100644
--- a/widget/qt/nsFilePicker.cpp
+++ /dev/null
@@ -1,297 +0,0 @@
-/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
- *
- * 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 <QStringList>
-#include <QGraphicsWidget>
-#include <QGraphicsScene>
-#include <QGraphicsView>
-#include <QTemporaryFile>
-
-#ifdef MOZ_ENABLE_CONTENTMANAGER
-#include "nsMFilePicker.h"
-#define MozFileDialog MeegoFileDialog
-#else
-#include <QFileDialog>
-#define MozFileDialog QFileDialog
-#endif
-
-
-#include "nsFilePicker.h"
-#include "nsNetUtil.h"
-#include "nsIWidget.h"
-#include "prlog.h"
-
-#ifdef PR_LOGGING
-static PRLogModuleInfo* sFilePickerLog = nullptr;
-#endif
-
-#include "nsDirectoryServiceDefs.h"
-
-//-----------------------------
-
-/* Implementation file */
-NS_IMPL_ISUPPORTS1(nsFilePicker, nsIFilePicker)
-
-nsFilePicker::nsFilePicker()
-{
-#ifdef PR_LOGGING
-    if (!sFilePickerLog)
-        sFilePickerLog = PR_NewLogModule("nsQtFilePicker");
-#endif
-}
-
-nsFilePicker::~nsFilePicker()
-{
-}
-
-NS_IMETHODIMP
-nsFilePicker::Init(nsIDOMWindow* parent, const nsAString& title, int16_t mode)
-{
-    return nsBaseFilePicker::Init(parent, title, mode);
-}
-
-/* void appendFilters (in long filterMask); */
-NS_IMETHODIMP
-nsFilePicker::AppendFilters(int32_t filterMask)
-{
-    return nsBaseFilePicker::AppendFilters(filterMask);
-}
-
-/* void appendFilter (in AString title, in AString filter); */
-NS_IMETHODIMP
-nsFilePicker::AppendFilter(const nsAString& aTitle, const nsAString& aFilter)
-{
-    if (aFilter.Equals(NS_LITERAL_STRING("..apps"))) {
-        // No platform specific thing we can do here, really....
-        return NS_OK;
-    }
-
-    nsAutoCString filter, name;
-    CopyUTF16toUTF8(aFilter, filter);
-    CopyUTF16toUTF8(aTitle, name);
-
-    mFilters.AppendElement(filter);
-    mFilterNames.AppendElement(name);
-
-    return NS_OK;
-}
-
-/* attribute AString defaultString; */
-NS_IMETHODIMP
-nsFilePicker::GetDefaultString(nsAString& aDefaultString)
-{
-    return NS_ERROR_FAILURE;
-}
-
-NS_IMETHODIMP
-nsFilePicker::SetDefaultString(const nsAString& aDefaultString)
-{
-    mDefault = aDefaultString;
-
-    return NS_OK;
-}
-
-/* attribute AString defaultExtension; */
-NS_IMETHODIMP
-nsFilePicker::GetDefaultExtension(nsAString& aDefaultExtension)
-{
-    aDefaultExtension = mDefaultExtension;
-
-    return NS_OK;
-}
-
-NS_IMETHODIMP
-nsFilePicker::SetDefaultExtension(const nsAString& aDefaultExtension)
-{
-    mDefaultExtension = aDefaultExtension;
-
-    return NS_OK;
-}
-
-/* attribute long filterIndex; */
-NS_IMETHODIMP
-nsFilePicker::GetFilterIndex(int32_t* aFilterIndex)
-{
-    *aFilterIndex = mSelectedType;
-
-    return NS_OK;
-}
-
-NS_IMETHODIMP
-nsFilePicker::SetFilterIndex(int32_t aFilterIndex)
-{
-    mSelectedType = aFilterIndex;
-
-    return NS_OK;
-}
-
-/* readonly attribute nsIFile file; */
-NS_IMETHODIMP
-nsFilePicker::GetFile(nsIFile* *aFile)
-{
-    NS_ENSURE_ARG_POINTER(aFile);
-
-    *aFile = nullptr;
-    if (mFile.IsEmpty()) {
-        return NS_OK;
-    }
-
-    nsCOMPtr<nsIFile> file(do_CreateInstance("@mozilla.org/file/local;1"));
-    NS_ENSURE_TRUE(file, NS_ERROR_FAILURE);
-
-    file->InitWithNativePath(mFile);
-
-    NS_ADDREF(*aFile = file);
-
-    return NS_OK;
-}
-
-/* readonly attribute nsIFileURL fileURL; */
-NS_IMETHODIMP
-nsFilePicker::GetFileURL(nsIURI* *aFileURL)
-{
-    nsCOMPtr<nsIFile> file;
-    GetFile(getter_AddRefs(file));
-
-    nsCOMPtr<nsIURI> uri;
-    NS_NewFileURI(getter_AddRefs(uri), file);
-    NS_ENSURE_TRUE(uri, NS_ERROR_FAILURE);
-
-    return CallQueryInterface(uri, aFileURL);
-}
-
-/* readonly attribute nsISimpleEnumerator files; */
-NS_IMETHODIMP
-nsFilePicker::GetFiles(nsISimpleEnumerator* *aFiles)
-{
-    NS_ENSURE_ARG_POINTER(aFiles);
-
-    if (mMode == nsIFilePicker::modeOpenMultiple) {
-        return NS_NewArrayEnumerator(aFiles, mFiles);
-    }
-
-    return NS_ERROR_FAILURE;
-}
-
-/* short show (); */
-NS_IMETHODIMP
-nsFilePicker::Show(int16_t* aReturn)
-{
-    nsAutoCString directory;
-    if (mDisplayDirectory) {
-        mDisplayDirectory->GetNativePath(directory);
-    }
-
-    QStringList filters;
-    uint32_t count = mFilters.Length();
-    for (uint32_t i = 0; i < count; ++i) {
-        filters.append(mFilters[i].get());
-    }
-
-    QGraphicsWidget* parentWidget = 0;
-    if (mParent) {
-        parentWidget = static_cast<QGraphicsWidget*>
-            (mParent->GetNativeData(NS_NATIVE_WIDGET));
-    }
-
-    QWidget* parentQWidget = 0;
-    if (parentWidget && parentWidget->scene()) {
-        if (parentWidget->scene()->views().size()>0) {
-            parentQWidget = parentWidget->scene()->views()[0];
-        }
-    }
-
-    QStringList files;
-    QString selected;
-
-    switch (mMode) {
-    case nsIFilePicker::modeOpen:
-        selected = MozFileDialog::getOpenFileName(parentQWidget, mCaption,
-                                                  directory.get(), filters.join(";"));
-        if (selected.isNull()) {
-            *aReturn = nsIFilePicker::returnCancel;
-            return NS_OK;
-        }
-        break;
-    case nsIFilePicker::modeOpenMultiple:
-        files = MozFileDialog::getOpenFileNames(parentQWidget, mCaption,
-                                                directory.get(), filters.join(";"));
-        if (files.empty()) {
-            *aReturn = nsIFilePicker::returnCancel;
-            return NS_OK;
-        }
-        selected = files[0];
-        break;
-    case nsIFilePicker::modeSave:
-    {
-        nsCOMPtr<nsIFile> targetFile;
-        NS_GetSpecialDirectory(NS_UNIX_XDG_DOCUMENTS_DIR,
-                               getter_AddRefs(targetFile));
-        if (!targetFile) {
-            // failed to get the XDG directory, using $HOME for now
-            NS_GetSpecialDirectory(NS_UNIX_HOME_DIR,
-                                   getter_AddRefs(targetFile));
-        }
-
-        if (targetFile) {
-            targetFile->Append(mDefault);
-            nsString targetPath;
-            targetFile->GetPath(targetPath);
-
-            bool exists = false;
-            targetFile->Exists(&exists);
-            if (exists) {
-                // file exists already create temporary filename
-                QTemporaryFile temp(QString::fromUtf16(targetPath.get()));
-                temp.open();
-                selected = temp.fileName();
-                temp.close();
-            } else {
-                selected = QString::fromUtf16(targetPath.get());
-            }
-        }
-    }
-    break;
-    case nsIFilePicker::modeGetFolder:
-        selected = MozFileDialog::getExistingDirectory(parentQWidget, mCaption,
-                                                       directory.get());
-        if (selected.isNull()) {
-            *aReturn = nsIFilePicker::returnCancel;
-            return NS_OK;
-        }
-    break;
-    default:
-    break;
-    }
-
-    if (!selected.isEmpty()) {
-        QString path = QFile::encodeName(selected);
-        mFile.Assign(path.toUtf8().data());
-    }
-
-    *aReturn = nsIFilePicker::returnOK;
-    if (mMode == modeSave) {
-        nsCOMPtr<nsIFile> file;
-        GetFile(getter_AddRefs(file));
-        if (file) {
-            bool exists = false;
-            file->Exists(&exists);
-            if (exists) {
-                *aReturn = nsIFilePicker::returnReplace;
-            }
-        }
-    }
-
-    return NS_OK;
-}
-
-void nsFilePicker::InitNative(nsIWidget *aParent, const nsAString &aTitle)
-{
-    PR_LOG(sFilePickerLog, PR_LOG_DEBUG, ("nsFilePicker::InitNative"));
-    nsAutoString str(aTitle);
-    mCaption = QString::fromUtf16(str.get());
-    mParent = aParent;
-}
deleted file mode 100644
--- a/widget/qt/nsFilePicker.h
+++ /dev/null
@@ -1,59 +0,0 @@
-/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
- *
- * 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 NSFILEPICKER_H
-#define NSFILEPICKER_H
-
-#include <QPointer>
-#include "nsBaseFilePicker.h"
-#include "nsCOMArray.h"
-#include "nsString.h"
-
-class QFileDialog;
-
-class nsFilePicker : public nsBaseFilePicker
-{
-public:
-    nsFilePicker();
-
-    NS_DECL_ISUPPORTS
-
-    // nsIFilePicker (less what's in nsBaseFilePicker)
-    NS_IMETHODIMP Init(nsIDOMWindow* parent, const nsAString& title, int16_t mode);
-    NS_IMETHODIMP AppendFilters(int32_t filterMask);
-    NS_IMETHODIMP AppendFilter(const nsAString& aTitle, const nsAString& aFilter);
-    NS_IMETHODIMP GetDefaultString(nsAString& aDefaultString);
-    NS_IMETHODIMP SetDefaultString(const nsAString& aDefaultString);
-    NS_IMETHODIMP GetDefaultExtension(nsAString& aDefaultExtension);
-    NS_IMETHODIMP SetDefaultExtension(const nsAString& aDefaultExtension);
-    NS_IMETHODIMP GetFilterIndex(int32_t* aFilterIndex);
-    NS_IMETHODIMP SetFilterIndex(int32_t aFilterIndex);
-    NS_IMETHODIMP GetFile(nsIFile* *aFile);
-    NS_IMETHODIMP GetFileURL(nsIURI* *aFileURL);
-    NS_IMETHODIMP GetFiles(nsISimpleEnumerator* *aFiles);
-    NS_IMETHODIMP Show(int16_t* aReturn);
-
-private:
-    ~nsFilePicker();
-    void InitNative(nsIWidget*, const nsAString&);
-
-protected:
-    QPointer<QFileDialog> mDialog;
-    nsCOMArray<nsIFile> mFiles;
-
-    int16_t   mSelectedType;
-    nsCString mFile;
-    nsString  mTitle;
-    nsString  mDefault;
-    nsString  mDefaultExtension;
-
-    nsTArray<nsCString> mFilters;
-    nsTArray<nsCString> mFilterNames;
-
-    QString mCaption;
-    nsIWidget* mParent;
-};
-
-#endif // NSFILEPICKER_H
--- a/widget/qt/nsLookAndFeel.cpp
+++ b/widget/qt/nsLookAndFeel.cpp
@@ -1,521 +1,460 @@
-/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
-/* 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/. */
+/* -*- Mode: C++; tab-width: 20; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
+/* Copyright 2012 Mozilla Foundation and Mozilla contributors
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
 
-// Qt headers must be included before anything that might pull in our
-// malloc wrappers.
-#include <QApplication>
+#include <QGuiApplication>
 #include <QFont>
-#include <QPalette>
-#include <QStyle>
-
-#undef NS_LOOKANDFEEL_DEBUG
-#ifdef NS_LOOKANDFEEL_DEBUG
-#include <QDebug>
-#endif
+#include <QScreen>
 
 #include "nsLookAndFeel.h"
 #include "nsStyleConsts.h"
-
-#include <qglobal.h>
+#include "gfxFont.h"
+#include "gfxFontConstants.h"
+#include "mozilla/gfx/2D.h"
 
-#define QCOLOR_TO_NS_RGB(c)                     \
-  ((nscolor)NS_RGB(c.red(),c.green(),c.blue()))
+static const char16_t UNICODE_BULLET = 0x2022;
 
 nsLookAndFeel::nsLookAndFeel()
-  : nsXPLookAndFeel(),
-    mDefaultFontCached(false), mButtonFontCached(false),
-    mFieldFontCached(false), mMenuFontCached(false)
+    : nsXPLookAndFeel()
 {
 }
 
 nsLookAndFeel::~nsLookAndFeel()
 {
 }
 
 nsresult
 nsLookAndFeel::NativeGetColor(ColorID aID, nscolor &aColor)
 {
-  nsresult res = NS_OK;
-
-  if (!qApp)
-    return NS_ERROR_FAILURE;
-
-  QPalette palette = qApp->palette();
-
-  switch (aID) {
-    case eColorID_WindowBackground:
-      aColor = QCOLOR_TO_NS_RGB(palette.color(QPalette::Normal, QPalette::Window));
-      break;
+    nsresult rv = NS_OK;
 
-    case eColorID_WindowForeground:
-      aColor = QCOLOR_TO_NS_RGB(palette.color(QPalette::Normal, QPalette::Window));
-      break;
-
-    case eColorID_WidgetBackground:
-      aColor = QCOLOR_TO_NS_RGB(palette.color(QPalette::Normal, QPalette::Window));
-      break;
-
-    case eColorID_WidgetForeground:
-      aColor = QCOLOR_TO_NS_RGB(palette.color(QPalette::Normal, QPalette::WindowText));
-      break;
+#define BASE_ACTIVE_COLOR     NS_RGB(0xaa,0xaa,0xaa)
+#define BASE_NORMAL_COLOR     NS_RGB(0xff,0xff,0xff)
+#define BASE_SELECTED_COLOR   NS_RGB(0xaa,0xaa,0xaa)
+#define BG_ACTIVE_COLOR       NS_RGB(0xff,0xff,0xff)
+#define BG_INSENSITIVE_COLOR  NS_RGB(0xaa,0xaa,0xaa)
+#define BG_NORMAL_COLOR       NS_RGB(0xff,0xff,0xff)
+#define BG_PRELIGHT_COLOR     NS_RGB(0xee,0xee,0xee)
+#define BG_SELECTED_COLOR     NS_RGB(0x99,0x99,0x99)
+#define DARK_NORMAL_COLOR     NS_RGB(0x88,0x88,0x88)
+#define FG_INSENSITIVE_COLOR  NS_RGB(0x44,0x44,0x44)
+#define FG_NORMAL_COLOR       NS_RGB(0x00,0x00,0x00)
+#define FG_PRELIGHT_COLOR     NS_RGB(0x77,0x77,0x77)
+#define FG_SELECTED_COLOR     NS_RGB(0xaa,0xaa,0xaa)
+#define LIGHT_NORMAL_COLOR    NS_RGB(0xaa,0xaa,0xaa)
+#define TEXT_ACTIVE_COLOR     NS_RGB(0x99,0x99,0x99)
+#define TEXT_NORMAL_COLOR     NS_RGB(0x00,0x00,0x00)
+#define TEXT_SELECTED_COLOR   NS_RGB(0x00,0x00,0x00)
 
+    switch (aID) {
+        // These colors don't seem to be used for anything anymore in Mozilla
+        // (except here at least TextSelectBackground and TextSelectForeground)
+        // The CSS2 colors below are used.
+    case eColorID_WindowBackground:
+        aColor = BASE_NORMAL_COLOR;
+        break;
+    case eColorID_WindowForeground:
+        aColor = TEXT_NORMAL_COLOR;
+        break;
+    case eColorID_WidgetBackground:
+        aColor = BG_NORMAL_COLOR;
+        break;
+    case eColorID_WidgetForeground:
+        aColor = FG_NORMAL_COLOR;
+        break;
     case eColorID_WidgetSelectBackground:
-      aColor = QCOLOR_TO_NS_RGB(palette.color(QPalette::Normal, QPalette::Window));
-      break;
-
+        aColor = BG_SELECTED_COLOR;
+        break;
     case eColorID_WidgetSelectForeground:
-      aColor = QCOLOR_TO_NS_RGB(palette.color(QPalette::Normal, QPalette::WindowText));
-      break;
-
+        aColor = FG_SELECTED_COLOR;
+        break;
     case eColorID_Widget3DHighlight:
-      aColor = NS_RGB(0xa0,0xa0,0xa0);
-      break;
-
+        aColor = NS_RGB(0xa0,0xa0,0xa0);
+        break;
     case eColorID_Widget3DShadow:
-      aColor = NS_RGB(0x40,0x40,0x40);
-      break;
-
+        aColor = NS_RGB(0x40,0x40,0x40);
+        break;
     case eColorID_TextBackground:
-      aColor = QCOLOR_TO_NS_RGB(palette.color(QPalette::Normal, QPalette::Window));
-      break;
-
+        // not used?
+        aColor = BASE_NORMAL_COLOR;
+        break;
     case eColorID_TextForeground:
-      aColor = QCOLOR_TO_NS_RGB(palette.color(QPalette::Normal, QPalette::WindowText));
-      break;
-
+        // not used?
+        aColor = TEXT_NORMAL_COLOR;
+        break;
     case eColorID_TextSelectBackground:
     case eColorID_IMESelectedRawTextBackground:
     case eColorID_IMESelectedConvertedTextBackground:
-      aColor = QCOLOR_TO_NS_RGB(palette.color(QPalette::Normal, QPalette::Highlight));
-      break;
-
+        // still used
+        aColor = BASE_SELECTED_COLOR;
+        break;
     case eColorID_TextSelectForeground:
     case eColorID_IMESelectedRawTextForeground:
     case eColorID_IMESelectedConvertedTextForeground:
-      aColor = QCOLOR_TO_NS_RGB(palette.color(QPalette::Normal, QPalette::HighlightedText));
-      break;
-
+        // still used
+        aColor = TEXT_SELECTED_COLOR;
+        break;
     case eColorID_IMERawInputBackground:
     case eColorID_IMEConvertedTextBackground:
-      aColor = NS_TRANSPARENT;
-      break;
-
+        aColor = NS_TRANSPARENT;
+        break;
     case eColorID_IMERawInputForeground:
     case eColorID_IMEConvertedTextForeground:
-      aColor = NS_SAME_AS_FOREGROUND_COLOR;
-      break;
-
+        aColor = NS_SAME_AS_FOREGROUND_COLOR;
+        break;
     case eColorID_IMERawInputUnderline:
     case eColorID_IMEConvertedTextUnderline:
-      aColor = NS_SAME_AS_FOREGROUND_COLOR;
-      break;
-
+        aColor = NS_SAME_AS_FOREGROUND_COLOR;
+        break;
     case eColorID_IMESelectedRawTextUnderline:
     case eColorID_IMESelectedConvertedTextUnderline:
-      aColor = NS_TRANSPARENT;
-      break;
-
+        aColor = NS_TRANSPARENT;
+        break;
     case eColorID_SpellCheckerUnderline:
       aColor = NS_RGB(0xff, 0, 0);
       break;
 
+        // css2  http://www.w3.org/TR/REC-CSS2/ui.html#system-colors
     case eColorID_activeborder:
-      aColor = QCOLOR_TO_NS_RGB(palette.color(QPalette::Normal, QPalette::Window));
-      break;
-
+        // active window border
+        aColor = BG_NORMAL_COLOR;
+        break;
     case eColorID_activecaption:
-      aColor = QCOLOR_TO_NS_RGB(palette.color(QPalette::Normal, QPalette::Window));
-      break;
-
+        // active window caption background
+        aColor = BG_NORMAL_COLOR;
+        break;
     case eColorID_appworkspace:
-      aColor = QCOLOR_TO_NS_RGB(palette.color(QPalette::Normal, QPalette::Window));
-      break;
-
+        // MDI background color
+        aColor = BG_NORMAL_COLOR;
+        break;
     case eColorID_background:
-      aColor = QCOLOR_TO_NS_RGB(palette.color(QPalette::Normal, QPalette::Window));
-      break;
-
+        // desktop background
+        aColor = BG_NORMAL_COLOR;
+        break;
     case eColorID_captiontext:
-      aColor = QCOLOR_TO_NS_RGB(palette.color(QPalette::Normal, QPalette::Text));
-      break;
-
+        // text in active window caption, size box, and scrollbar arrow box (!)
+        aColor = FG_NORMAL_COLOR;
+        break;
     case eColorID_graytext:
-      aColor = QCOLOR_TO_NS_RGB(palette.color(QPalette::Disabled, QPalette::Text));
-      break;
-
+        // disabled text in windows, menus, etc.
+        aColor = FG_INSENSITIVE_COLOR;
+        break;
     case eColorID_highlight:
-      aColor = QCOLOR_TO_NS_RGB(palette.color(QPalette::Normal, QPalette::Highlight));
-      break;
-
+        // background of selected item
+        aColor = BASE_SELECTED_COLOR;
+        break;
     case eColorID_highlighttext:
-      aColor = QCOLOR_TO_NS_RGB(palette.color(QPalette::Normal, QPalette::HighlightedText));
-      break;
-
+        // text of selected item
+        aColor = TEXT_SELECTED_COLOR;
+        break;
     case eColorID_inactiveborder:
-      aColor = QCOLOR_TO_NS_RGB(palette.color(QPalette::Disabled, QPalette::Window));
-      break;
-
+        // inactive window border
+        aColor = BG_NORMAL_COLOR;
+        break;
     case eColorID_inactivecaption:
-      aColor = QCOLOR_TO_NS_RGB(palette.color(QPalette::Disabled, QPalette::Window));
-      break;
-
+        // inactive window caption
+        aColor = BG_INSENSITIVE_COLOR;
+        break;
     case eColorID_inactivecaptiontext:
-      aColor = QCOLOR_TO_NS_RGB(palette.color(QPalette::Disabled, QPalette::Text));
-      break;
-
+        // text in inactive window caption
+        aColor = FG_INSENSITIVE_COLOR;
+        break;
     case eColorID_infobackground:
-#if (QT_VERSION >= QT_VERSION_CHECK(4, 4, 0))
-      aColor = QCOLOR_TO_NS_RGB(palette.color(QPalette::Normal, QPalette::ToolTipBase));
-#else
-      aColor = QCOLOR_TO_NS_RGB(palette.color(QPalette::Normal, QPalette::Base));
-#endif
-      break;
-
+        // tooltip background color
+        aColor = BG_NORMAL_COLOR;
+        break;
     case eColorID_infotext:
-#if (QT_VERSION >= QT_VERSION_CHECK(4, 4, 0))
-      aColor = QCOLOR_TO_NS_RGB(palette.color(QPalette::Normal, QPalette::ToolTipText));
-#else
-      aColor = QCOLOR_TO_NS_RGB(palette.color(QPalette::Normal, QPalette::Text));
-#endif
-      break;
-
+        // tooltip text color
+        aColor = TEXT_NORMAL_COLOR;
+        break;
     case eColorID_menu:
-      aColor = QCOLOR_TO_NS_RGB(palette.color(QPalette::Normal, QPalette::Window));
-      break;
-
+        // menu background
+        aColor = BG_NORMAL_COLOR;
+        break;
     case eColorID_menutext:
-    case eColorID__moz_menubartext:
-      aColor = QCOLOR_TO_NS_RGB(palette.color(QPalette::Normal, QPalette::Text));
-      break;
-
+        // menu text
+        aColor = TEXT_NORMAL_COLOR;
+        break;
     case eColorID_scrollbar:
-      aColor = QCOLOR_TO_NS_RGB(palette.color(QPalette::Normal, QPalette::Mid));
-      break;
+        // scrollbar gray area
+        aColor = BG_ACTIVE_COLOR;
+        break;
 
     case eColorID_threedface:
     case eColorID_buttonface:
-      aColor = QCOLOR_TO_NS_RGB(palette.color(QPalette::Normal, QPalette::Button));
-      break;
-
-    case eColorID_buttonhighlight:
-    case eColorID_threedhighlight:
-      aColor = QCOLOR_TO_NS_RGB(palette.color(QPalette::Normal, QPalette::Dark));
-      break;
+        // 3-D face color
+        aColor = BG_NORMAL_COLOR;
+        break;
 
     case eColorID_buttontext:
-      aColor = QCOLOR_TO_NS_RGB(palette.color(QPalette::Normal, QPalette::ButtonText));
-      break;
+        // text on push buttons
+        aColor = TEXT_NORMAL_COLOR;
+        break;
+
+    case eColorID_buttonhighlight:
+        // 3-D highlighted edge color
+    case eColorID_threedhighlight:
+        // 3-D highlighted outer edge color
+        aColor = LIGHT_NORMAL_COLOR;
+        break;
+
+    case eColorID_threedlightshadow:
+        // 3-D highlighted inner edge color
+        aColor = BG_NORMAL_COLOR;
+        break;
 
     case eColorID_buttonshadow:
+        // 3-D shadow edge color
     case eColorID_threedshadow:
-      aColor = QCOLOR_TO_NS_RGB(palette.color(QPalette::Normal, QPalette::Dark));
-      break;
+        // 3-D shadow inner edge color
+        aColor = DARK_NORMAL_COLOR;
+        break;
 
     case eColorID_threeddarkshadow:
-      aColor = QCOLOR_TO_NS_RGB(palette.color(QPalette::Normal, QPalette::Shadow));
-      break;
-
-    case eColorID_threedlightshadow:
-      aColor = QCOLOR_TO_NS_RGB(palette.color(QPalette::Normal, QPalette::Light));
-      break;
+        // 3-D shadow outer edge color
+        aColor = NS_RGB(0,0,0);
+        break;
 
     case eColorID_window:
     case eColorID_windowframe:
-      aColor = QCOLOR_TO_NS_RGB(palette.color(QPalette::Normal, QPalette::Window));
-      break;
+        aColor = BG_NORMAL_COLOR;
+        break;
 
     case eColorID_windowtext:
-      aColor = QCOLOR_TO_NS_RGB(palette.color(QPalette::Normal, QPalette::Text));
-      break;
-
-      // from the CSS3 working draft (not yet finalized)
-      // http://www.w3.org/tr/2000/wd-css3-userint-20000216.html#color
-
-    case eColorID__moz_buttondefault:
-      aColor = QCOLOR_TO_NS_RGB(palette.color(QPalette::Normal, QPalette::Button));
-      break;
-
-    case eColorID__moz_field:
-    case eColorID__moz_combobox:
-      aColor = QCOLOR_TO_NS_RGB(palette.color(QPalette::Normal, QPalette::Base));
-      break;
-
-    case eColorID__moz_fieldtext:
-    case eColorID__moz_comboboxtext:
-      aColor = QCOLOR_TO_NS_RGB(palette.color(QPalette::Normal, QPalette::Text));
-      break;
-
-    case eColorID__moz_dialog:
-      aColor = QCOLOR_TO_NS_RGB(palette.color(QPalette::Normal, QPalette::Window));
-      break;
-
-    case eColorID__moz_dialogtext:
-      aColor = QCOLOR_TO_NS_RGB(palette.color(QPalette::Normal, QPalette::WindowText));
-      break;
-
-    case eColorID__moz_dragtargetzone:
-      aColor = QCOLOR_TO_NS_RGB(palette.color(QPalette::Normal, QPalette::Window));
-      break;
-
-    case eColorID__moz_buttonhovertext:
-      aColor = QCOLOR_TO_NS_RGB(palette.color(QPalette::Normal, QPalette::ButtonText));
-      break;
-
-    case eColorID__moz_menuhovertext:
-    case eColorID__moz_menubarhovertext:
-      aColor = QCOLOR_TO_NS_RGB(palette.color(QPalette::Normal, QPalette::Text));
-      break;
+        aColor = FG_NORMAL_COLOR;
+        break;
 
+    case eColorID__moz_eventreerow:
+    case eColorID__moz_field:
+        aColor = BASE_NORMAL_COLOR;
+        break;
+    case eColorID__moz_fieldtext:
+        aColor = TEXT_NORMAL_COLOR;
+        break;
+    case eColorID__moz_dialog:
+        aColor = BG_NORMAL_COLOR;
+        break;
+    case eColorID__moz_dialogtext:
+        aColor = FG_NORMAL_COLOR;
+        break;
+    case eColorID__moz_dragtargetzone:
+        aColor = BG_SELECTED_COLOR;
+        break;
+    case eColorID__moz_buttondefault:
+        // default button border color
+        aColor = NS_RGB(0,0,0);
+        break;
+    case eColorID__moz_buttonhoverface:
+        aColor = BG_PRELIGHT_COLOR;
+        break;
+    case eColorID__moz_buttonhovertext:
+        aColor = FG_PRELIGHT_COLOR;
+        break;
+    case eColorID__moz_cellhighlight:
+    case eColorID__moz_html_cellhighlight:
+        aColor = BASE_ACTIVE_COLOR;
+        break;
+    case eColorID__moz_cellhighlighttext:
+    case eColorID__moz_html_cellhighlighttext:
+        aColor = TEXT_ACTIVE_COLOR;
+        break;
+    case eColorID__moz_menuhover:
+        aColor = BG_PRELIGHT_COLOR;
+        break;
+    case eColorID__moz_menuhovertext:
+        aColor = FG_PRELIGHT_COLOR;
+        break;
+    case eColorID__moz_oddtreerow:
+        aColor = NS_TRANSPARENT;
+        break;
+    case eColorID__moz_nativehyperlinktext:
+        aColor = NS_SAME_AS_FOREGROUND_COLOR;
+        break;
+    case eColorID__moz_comboboxtext:
+        aColor = TEXT_NORMAL_COLOR;
+        break;
+    case eColorID__moz_combobox:
+        aColor = BG_NORMAL_COLOR;
+        break;
+    case eColorID__moz_menubartext:
+        aColor = TEXT_NORMAL_COLOR;
+        break;
+    case eColorID__moz_menubarhovertext:
+        aColor = FG_PRELIGHT_COLOR;
+        break;
     default:
-      aColor = 0;
-      res    = NS_ERROR_FAILURE;
-      break;
-  }
-  return res;
-}
+        /* default color is BLACK */
+        aColor = 0;
+        rv = NS_ERROR_FAILURE;
+        break;
+    }
 
-#ifdef NS_LOOKANDFEEL_DEBUG
-static const char *metricToString[] = {
-  "eIntID_CaretBlinkTime",
-  "eIntID_CaretWidth",
-  "eIntID_ShowCaretDuringSelection",
-  "eIntID_SelectTextfieldsOnKeyFocus",
-  "eIntID_SubmenuDelay",
-  "eIntID_MenusCanOverlapOSBar",
-  "eIntID_SkipNavigatingDisabledMenuItem",
-  "eIntID_DragThresholdX",
-  "eIntID_DragThresholdY",
-  "eIntID_UseAccessibilityTheme",
-  "eIntID_ScrollArrowStyle",
-  "eIntID_ScrollSliderStyle",
-  "eIntID_ScrollButtonLeftMouseButtonAction",
-  "eIntID_ScrollButtonMiddleMouseButtonAction",
-  "eIntID_ScrollButtonRightMouseButtonAction",
-  "eIntID_TreeOpenDelay",
-  "eIntID_TreeCloseDelay",
-  "eIntID_TreeLazyScrollDelay",
-  "eIntID_TreeScrollDelay",
-  "eIntID_TreeScrollLinesMax",
-  "eIntID_TabFocusModel",
-  "eIntID_WindowsDefaultTheme",
-  "eIntID_AlertNotificationOrigin",
-  "eIntID_ScrollToClick",
-  "eIntID_IMERawInputUnderlineStyle",
-  "eIntID_IMESelectedRawTextUnderlineStyle",
-  "eIntID_IMEConvertedTextUnderlineStyle",
-  "eIntID_IMESelectedConvertedTextUnderline",
-  "eIntID_ImagesInMenus"
-};
-#endif
+    return rv;
+}
 
 nsresult
 nsLookAndFeel::GetIntImpl(IntID aID, int32_t &aResult)
 {
-#ifdef NS_LOOKANDFEEL_DEBUG
-  qDebug("nsLookAndFeel::GetIntImpl aID = %s", metricToString[aID]);
-#endif
+    nsresult rv = nsXPLookAndFeel::GetIntImpl(aID, aResult);
+    if (NS_SUCCEEDED(rv))
+        return rv;
+
+    rv = NS_OK;
 
-  nsresult res = nsXPLookAndFeel::GetIntImpl(aID, aResult);
-  if (NS_SUCCEEDED(res))
-    return res;
+    switch (aID) {
+        case eIntID_CaretBlinkTime:
+            aResult = 500;
+            break;
 
-  res = NS_OK;
+        case eIntID_CaretWidth:
+            aResult = 1;
+            break;
 
-  switch (aID) {
-    case eIntID_CaretBlinkTime:
-      aResult = 500;
-      break;
+        case eIntID_ShowCaretDuringSelection:
+            aResult = 0;
+            break;
 
-    case eIntID_CaretWidth:
-      aResult = 1;
-      break;
-
-    case eIntID_ShowCaretDuringSelection:
-      aResult = 0;
-      break;
+        case eIntID_SelectTextfieldsOnKeyFocus:
+            // Select textfield content when focused by kbd
+            // used by nsEventStateManager::sTextfieldSelectModel
+            aResult = 1;
+            break;
 
-    case eIntID_SelectTextfieldsOnKeyFocus:
-      // Select textfield content when focused by kbd
-      // used by nsEventStateManager::sTextfieldSelectModel
-      aResult = 1;
-      break;
+        case eIntID_SubmenuDelay:
+            aResult = 200;
+            break;
 
-    case eIntID_SubmenuDelay:
-      aResult = 200;
-      break;
+        case eIntID_TooltipDelay:
+            aResult = 500;
+            break;
 
-    case eIntID_TooltipDelay:
-      aResult = 500;
-      break;
+        case eIntID_MenusCanOverlapOSBar:
+            // we want XUL popups to be able to overlap the task bar.
+            aResult = 1;
+            break;
 
-    case eIntID_MenusCanOverlapOSBar:
-      // we want XUL popups to be able to overlap the task bar.
-      aResult = 1;
-      break;
+        case eIntID_ScrollArrowStyle:
+            aResult = eScrollArrowStyle_Single;
+            break;
 
-    case eIntID_ScrollArrowStyle:
-      aResult = eScrollArrowStyle_Single;
-      break;
+        case eIntID_ScrollSliderStyle:
+            aResult = eScrollThumbStyle_Proportional;
+            break;
 
-    case eIntID_ScrollSliderStyle:
-      aResult = eScrollThumbStyle_Proportional;
-      break;
+        case eIntID_TouchEnabled:
+            aResult = 1;
+            break;
 
-    case eIntID_TouchEnabled:
-      aResult = 0;
-      res = NS_ERROR_NOT_IMPLEMENTED;
-      break;
+        case eIntID_WindowsDefaultTheme:
+        case eIntID_WindowsThemeIdentifier:
+        case eIntID_OperatingSystemVersionIdentifier:
+            aResult = 0;
+            rv = NS_ERROR_NOT_IMPLEMENTED;
+            break;
 
-    case eIntID_WindowsDefaultTheme:
-      aResult = 0;
-      res = NS_ERROR_NOT_IMPLEMENTED;
-      break;
+        case eIntID_IMERawInputUnderlineStyle:
+        case eIntID_IMEConvertedTextUnderlineStyle:
+            aResult = NS_STYLE_TEXT_DECORATION_STYLE_SOLID;
+            break;
 
-    case eIntID_SpellCheckerUnderlineStyle:
-      aResult = NS_STYLE_TEXT_DECORATION_STYLE_WAVY;
-      break;
-
-    case eIntID_ScrollbarButtonAutoRepeatBehavior:
-      aResult = 1;
-      break;
+        case eIntID_IMESelectedRawTextUnderlineStyle:
+        case eIntID_IMESelectedConvertedTextUnderline:
+            aResult = NS_STYLE_TEXT_DECORATION_STYLE_NONE;
+            break;
 
-    default:
-      aResult = 0;
-      res = NS_ERROR_FAILURE;
-  }
-  return res;
+        case eIntID_SpellCheckerUnderlineStyle:
+            aResult = NS_STYLE_TEXT_DECORATION_STYLE_WAVY;
+            break;
+
+        case eIntID_ScrollbarButtonAutoRepeatBehavior:
+            aResult = 0;
+            break;
+
+        default:
+            aResult = 0;
+            rv = NS_ERROR_FAILURE;
+    }
+
+    return rv;
 }
 
-#ifdef NS_LOOKANDFEEL_DEBUG
-static const char *floatMetricToString[] = {
-  "eFloatID_IMEUnderlineRelativeSize"
-};
-#endif
-
 nsresult
 nsLookAndFeel::GetFloatImpl(FloatID aID, float &aResult)
 {
-#ifdef NS_LOOKANDFEEL_DEBUG
-  qDebug("nsLookAndFeel::GetFloatImpl aID = %s", floatMetricToString[aID]);
-#endif
-
   nsresult res = nsXPLookAndFeel::GetFloatImpl(aID, aResult);
   if (NS_SUCCEEDED(res))
     return res;
   res = NS_OK;
 
   switch (aID) {
     case eFloatID_IMEUnderlineRelativeSize:
-      aResult = 1.0f;
-      break;
-
+        aResult = 1.0f;
+        break;
     case eFloatID_SpellCheckerUnderlineRelativeSize:
-      aResult = 1.0f;
-      break;
-
+        aResult = 1.0f;
+        break;
     default:
-      aResult = -1.0;
-      res = NS_ERROR_FAILURE;
-      break;
-  }
+        aResult = -1.0;
+        res = NS_ERROR_FAILURE;
+    }
   return res;
 }
 
-static void
-GetSystemFontInfo(const char *aClassName, nsString *aFontName,
-                  gfxFontStyle *aFontStyle)
-{
-  QFont qFont = QApplication::font(aClassName);
-
-  NS_NAMED_LITERAL_STRING(quote, "\"");
-  nsString family((char16_t*)qFont.family().data());
-  *aFontName = quote + family + quote;
-
-  aFontStyle->systemFont = true;
-  aFontStyle->style = NS_FONT_STYLE_NORMAL;
-  aFontStyle->weight = qFont.weight();
-  // FIXME: Set aFontStyle->stretch correctly!
-  aFontStyle->stretch = NS_FONT_STRETCH_NORMAL;
-  // use pixel size directly if it is set, otherwise compute from point size
-  if (qFont.pixelSize() != -1) {
-    aFontStyle->size = qFont.pixelSize();
-  } else {
-    aFontStyle->size = qFont.pointSizeF() * 96.0f / 72.0f;
-  }
-}
-
+/*virtual*/
 bool
 nsLookAndFeel::GetFontImpl(FontID aID, nsString& aFontName,
                            gfxFontStyle& aFontStyle,
                            float aDevPixPerCSSPixel)
 {
-  const char *className = nullptr;
-  nsString *cachedFontName = nullptr;
-  gfxFontStyle *cachedFontStyle = nullptr;
-  bool *isCached = nullptr;
+  QFont qFont = QGuiApplication::font();
 
-  switch (aID) {
-    case eFont_Menu:         // css2
-    case eFont_PullDownMenu: // css3
-      cachedFontName = &mMenuFontName;
-      cachedFontStyle = &mMenuFontStyle;
-      isCached = &mMenuFontCached;
-      className = "QAction";
-      break;
-
-    case eFont_Field:        // css3
-    case eFont_List:         // css3
-      cachedFontName = &mFieldFontName;
-      cachedFontStyle = &mFieldFontStyle;
-      isCached = &mFieldFontCached;
-      className = "QlineEdit";
-      break;
+  NS_NAMED_LITERAL_STRING(quote, "\"");
+  nsString family((char16_t*)qFont.family().data());
+  aFontName = quote + family + quote;
 
-    case eFont_Button:       // css3
-      cachedFontName = &mButtonFontName;
-      cachedFontStyle = &mButtonFontStyle;
-      isCached = &mButtonFontCached;
-      className = "QPushButton";
-      break;
-
-    case eFont_Caption:      // css2
-    case eFont_Icon:         // css2
-    case eFont_MessageBox:   // css2
-    case eFont_SmallCaption: // css2
-    case eFont_StatusBar:    // css2
-    case eFont_Window:       // css3
-    case eFont_Document:     // css3
-    case eFont_Workspace:    // css3
-    case eFont_Desktop:      // css3
-    case eFont_Info:         // css3
-    case eFont_Dialog:       // css3
-    case eFont_Tooltips:     // moz
-    case eFont_Widget:       // moz
-      cachedFontName = &mDefaultFontName;
-      cachedFontStyle = &mDefaultFontStyle;
-      isCached = &mDefaultFontCached;
-      className = "Qlabel";
-      break;
+  aFontStyle.systemFont = true;
+  aFontStyle.style = qFont.style();
+  aFontStyle.weight = qFont.weight();
+  aFontStyle.stretch = qFont.stretch();
+  // use pixel size directly if it is set, otherwise compute from point size
+  if (qFont.pixelSize() != -1) {
+    aFontStyle.size = qFont.pixelSize();
+  } else {
+    aFontStyle.size = qFont.pointSizeF() * qApp->primaryScreen()->logicalDotsPerInch() / 72.0f;
   }
 
-  if (!*isCached) {
-    GetSystemFontInfo(className, cachedFontName, cachedFontStyle);
-    *isCached = true;
-  }
-
-  aFontName = *cachedFontName;
-  aFontStyle = *cachedFontStyle;
   return true;
 }
 
-void
-nsLookAndFeel::RefreshImpl()
+/*virtual*/
+bool
+nsLookAndFeel::GetEchoPasswordImpl() {
+    return true;
+}
+
+/*virtual*/
+uint32_t
+nsLookAndFeel::GetPasswordMaskDelayImpl()
 {
-  nsXPLookAndFeel::RefreshImpl();
-  mDefaultFontCached = false;
-  mButtonFontCached = false;
-  mFieldFontCached = false;
-  mMenuFontCached = false;
+    // Same value on Android framework
+    return 1500;
 }
+
+/* virtual */
+char16_t
+nsLookAndFeel::GetPasswordCharacterImpl()
+{
+    return UNICODE_BULLET;
+}
--- a/widget/qt/nsLookAndFeel.h
+++ b/widget/qt/nsLookAndFeel.h
@@ -1,40 +1,40 @@
 /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
-/* 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/. */
+/* Copyright 2012 Mozilla Foundation and Mozilla contributors
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
 #ifndef __nsLookAndFeel
 #define __nsLookAndFeel
 
 #include "nsXPLookAndFeel.h"
-#include "gfxFont.h"
 
-class nsLookAndFeel: public nsXPLookAndFeel
+class nsLookAndFeel : public nsXPLookAndFeel
 {
 public:
     nsLookAndFeel();
     virtual ~nsLookAndFeel();
 
-    virtual nsresult NativeGetColor(ColorID aID, nscolor &aResult);
+    virtual bool GetFontImpl(FontID aID, nsString& aName, gfxFontStyle& aStyle,
+                             float aDevPixPerCSSPixel);
     virtual nsresult GetIntImpl(IntID aID, int32_t &aResult);
     virtual nsresult GetFloatImpl(FloatID aID, float &aResult);
-    virtual bool GetFontImpl(FontID aID, nsString& aFontName,
-                             gfxFontStyle& aFontStyle,
-                             float aDevPixPerCSSPixel);
-    virtual void RefreshImpl();
+    virtual bool GetEchoPasswordImpl();
+    virtual uint32_t GetPasswordMaskDelayImpl();
+    virtual char16_t GetPasswordCharacterImpl();
 
-private:
-    bool mDefaultFontCached;
-    bool mButtonFontCached;
-    bool mFieldFontCached;
-    bool mMenuFontCached;
-    nsString mDefaultFontName;
-    nsString mButtonFontName;
-    nsString mFieldFontName;
-    nsString mMenuFontName;
-    gfxFontStyle mDefaultFontStyle;
-    gfxFontStyle mButtonFontStyle;
-    gfxFontStyle mFieldFontStyle;
-    gfxFontStyle mMenuFontStyle;
+protected:
+    virtual nsresult NativeGetColor(ColorID aID, nscolor &aColor);
 };
 
 #endif
deleted file mode 100644
--- a/widget/qt/nsMFilePicker.cpp
+++ /dev/null
@@ -1,284 +0,0 @@
-/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*-
- * vim: sw=2 ts=4 et :
- */
-/* 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 <QWidget>
-#include "nsMFilePicker.h"
-
-
-// Use Qt Tracker API to get attachment data from tracker:
-#include <QtSparql/QSparqlConnection>
-#include <QtSparql/QSparqlQuery>
-#include <QtSparql/QSparqlResult>
-
-#include <MApplication>
-#include <MApplicationPage>
-#include <MApplicationWindow>
-#include <MSceneManager>
-
-#include <QFileInfo>
-#include <QPointer>
-
-#include <SelectSingleContentItemPage.h>
-#include <SelectMultipleContentItemsPage.h>
-
-MeegoFileDialog::MeegoFileDialog(QObject* aParent)
-  : QObject(aParent)
-  , mMode(Mode_Unknown)
-{
-}
-
-MeegoFileDialog::~MeegoFileDialog()
-{
-}
-
-int
-MeegoFileDialog::exec()
-{
-    MApplicationPage* page = nullptr;
-    switch(mMode) {
-    case Mode_OpenFile:
-        page = createOpenFilePage();
-        break;
-    case Mode_OpenFiles:
-        page = createOpenFilesPage();
-        break;
-    case Mode_OpenDirectory:
-        page = createOpenDirectoryPage();
-        break;
-    default:
-        return 0;
-    }
-
-    page->setTitle(mCaption);
-
-    QPointer<MApplicationWindow> appWindow = new MApplicationWindow(MApplication::activeWindow());
-    QObject::connect(MApplication::activeWindow(), SIGNAL(switcherEntered()), this, SLOT(backButtonClicked()));
-    appWindow->show();
-
-    // a not so pretty Hack to build up a back button
-    // by using a empty scene window for a pseudo history stack
-    MSceneWindow* fakeWindow = new MSceneWindow();
-    // tell fake window to disappear when page back was clicked.
-    connect(page, SIGNAL(backButtonClicked()), fakeWindow, SLOT(disappear()));
-    // let new page appear on pseudo Application Window
-    appWindow->sceneManager()->appearSceneWindowNow(page);
-
-    // get, manipulate and set history stack
-    QList<MSceneWindow*> sceneWindowHistory = appWindow->sceneManager()->pageHistory();
-    sceneWindowHistory.insert(0, fakeWindow);
-    appWindow->sceneManager()->setPageHistory(sceneWindowHistory);
-
-    // start own eventloop
-    QEventLoop eventLoop;
-    mEventLoop = &eventLoop;
-    QPointer<MeegoFileDialog> guard = this;
-    (void) eventLoop.exec(QEventLoop::DialogExec);
-    if (guard.isNull()) {
-        return 0;
-    }
-    if (page) {
-        page->disappear();
-        delete page;
-    }
-    if (appWindow) {
-        delete appWindow;
-    }
-    mEventLoop = 0;
-    return 0;
-}
-
-MApplicationPage*
-MeegoFileDialog::createOpenFilePage()
-{
-    QStringList itemType("http://www.semanticdesktop.org/ontologies/2007/03/22/nfo#FileDataObject");
-
-    SelectSingleContentItemPage* page =
-        new SelectSingleContentItemPage(QString(),
-                                        itemType);
-
-    connect(page, SIGNAL(contentItemSelected(const QString&)),
-            this, SLOT  (contentItemSelected(const QString&)));
-
-    connect(page, SIGNAL(backButtonClicked()),
-            this, SLOT  (backButtonClicked()));
-
-    return page;
-}
-
-MApplicationPage*
-MeegoFileDialog::createOpenFilesPage()
-{
-    QStringList itemType("http://www.semanticdesktop.org/ontologies/2007/03/22/nfo#Folder");
-
-    SelectMultipleContentItemsPage* page = new SelectMultipleContentItemsPage(QString(), itemType);
-    connect(page, SIGNAL(contentItemsSelected(const QStringList&)),
-            this, SLOT  (contentItemsSelected(const QStringList&)));
-
-    connect(page, SIGNAL(backButtonClicked()),
-            this, SLOT  (backButtonClicked()));
-
-    return page;
-}
-
-MApplicationPage*
-MeegoFileDialog::createOpenDirectoryPage()
-{
-    QStringList itemType("http://www.semanticdesktop.org/ontologies/2007/03/22/nfo#Folder");
-
-    SelectSingleContentItemPage* page = new SelectSingleContentItemPage(QString(), itemType);
-    connect(page, SIGNAL(contentItemSelected(const QString&)),
-            this, SLOT  (contentItemSelected(const QString&)));
-
-    connect(page, SIGNAL(backButtonClicked()),
-            this, SLOT  (backButtonClicked()));
-
-    return page;
-}
-
-QStringList
-MeegoFileDialog::selectedFileNames() const
-{
-    return mSelectedFileNames;
-}
-
-bool
-MeegoFileDialog::hasSelectedFileNames() const
-{
-    return !mSelectedFileNames.isEmpty();
-}
-
-void
-MeegoFileDialog::contentItemSelected(const QString& aContentItem)
-{
-    mSelectedFileNames.clear();
-
-    if (aContentItem.isEmpty()) {
-        finishEventLoop();
-        return;
-    }
-
-    QUrl fileUrl = trackerIdToFilename(aContentItem);
-    QFileInfo fileInfo(fileUrl.toLocalFile());
-    if (fileInfo.isFile()) {
-        mSelectedFileNames << fileInfo.canonicalFilePath();
-    }
-
-    finishEventLoop();
-}
-
-void
-MeegoFileDialog::contentItemsSelected(const QStringList& aContentItems)
-{
-    mSelectedFileNames.clear();
-
-    foreach (QString contentItem, aContentItems) {
-        QUrl fileUrl = trackerIdToFilename(contentItem);
-        QFileInfo fileInfo(fileUrl.toLocalFile());
-        if (fileInfo.isFile()) {
-            mSelectedFileNames << fileInfo.canonicalFilePath();
-        }
-    }
-
-    finishEventLoop();
-}
-
-void
-MeegoFileDialog::backButtonClicked()
-{
-    mSelectedFileNames.clear();
-    finishEventLoop();
-}
-
-/* static */ QString
-MeegoFileDialog::getOpenFileName(QWidget* parent,
-                                 const QString& caption,
-                                 const QString& dir,
-                                 const QString& filter)
-{
-    QPointer<MeegoFileDialog> picker = new MeegoFileDialog(parent);
-
-    QString result;
-    picker->mMode = MeegoFileDialog::Mode_OpenFile;
-    picker->mCaption = caption;
-    picker->exec();
-
-    // Need separate 'if' because picker might have been destroyed by its parent during exec()
-    if (picker) {
-        if (picker->hasSelectedFileNames()) {
-            result = picker->selectedFileNames().first();
-        }
-        delete picker;
-    }
-
-    return result;
-}
-
-/* static */ QString
-MeegoFileDialog::getExistingDirectory(QWidget* parent,const QString& caption, const QString& dir)
-{
-    QPointer<MeegoFileDialog> picker = new MeegoFileDialog(parent);
-
-    QString result;
-    picker->mMode = MeegoFileDialog::Mode_OpenDirectory;
-    picker->mCaption = caption;
-    picker->exec();
-
-    // Need separate 'if' because picker might have been destroyed by its parent during exec()
-    if (picker) {
-        if (picker->hasSelectedFileNames()) {
-            result = picker->selectedFileNames().first();
-        }
-        delete picker;
-    }
-
-    return result;
-}
-
-/* static */ QStringList
-MeegoFileDialog::getOpenFileNames(QWidget* parent,
-                                  const QString& caption,
-                                  const QString& dir,
-                                  const QString& filter)
-{
-    QPointer<MeegoFileDialog> picker = new MeegoFileDialog(parent);
-
-    QStringList result;
-    picker->mMode = MeegoFileDialog::Mode_OpenFiles;
-    picker->mCaption = caption;
-    picker->exec();
-
-    // Need separate 'if' because picker might have been destroyed by its parent during exec()
-    if (picker) {
-        if (picker->hasSelectedFileNames()) {
-            result = picker->selectedFileNames();
-        }
-        delete picker;
-    }
-
-    return result;
-}
-
-QUrl
-MeegoFileDialog::trackerIdToFilename(const QString& trackerId)
-{
-    QSparqlQuery query("SELECT ?u WHERE { ?:tUri nie:url ?u . }");
-    query.bindValue("tUri", QUrl(trackerId)); // That puts <trackerId> into the query
-    QSparqlConnection connection("QTRACKER"); // Exact string needed to make connection to tracker
-    QSparqlResult* result = connection.exec(query);
-
-    result->waitForFinished();
-    result->first();
-
-    QUrl resultFile;
-    if (result->isValid()) {
-        resultFile = QUrl(result->binding(0).value().toString());
-    }
-    delete result;
-
-    return resultFile;
-}
deleted file mode 100644
--- a/widget/qt/nsMFilePicker.h
+++ /dev/null
@@ -1,64 +0,0 @@
-/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*-
- * vim: sw=2 ts=4 et :
- */
-/* 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 NSMFILEDIALOG_H
-#define NSMFILEDIALOG_H
-
-#include <QEventLoop>
-#include <QStringList>
-#include <QUrl>
-
-class MApplicationPage;
-class MeegoFileDialog : public QObject
-{
-    Q_OBJECT
-public:
-
-    enum MeegoFileDialogMode {
-        Mode_Unknown = -1,
-        Mode_OpenFile = 0,
-        Mode_OpenFiles = 1,
-        Mode_OpenDirectory = 2
-        // No Mode_SaveFile - the content picker can't handle that
-    };
-
-    MeegoFileDialog(QObject* aParent = 0);
-    virtual ~MeegoFileDialog();
-
-    QStringList selectedFileNames() const;
-    bool hasSelectedFileNames() const;
-
-    static QString getOpenFileName(QWidget* parent, const QString &caption, const QString& dir, const QString& filter);
-    static QStringList getOpenFileNames(QWidget* parent, const QString& caption, const QString& dir, const QString& filter);
-    static QString getExistingDirectory(QWidget* parent, const QString& caption, const QString& dir);
-
-    int exec();
-
-private Q_SLOTS:
-    void contentItemSelected(const QString& aItem);
-    void contentItemsSelected(const QStringList& aItems);
-    void backButtonClicked();
-
-private:
-    QUrl trackerIdToFilename(const QString& trackerId);
-    MApplicationPage* createOpenFilePage();
-    MApplicationPage* createOpenFilesPage();
-    MApplicationPage* createOpenDirectoryPage();
-    void finishEventLoop() {
-        if (!mEventLoop)
-            return;
-        mEventLoop->exit(0);
-        mEventLoop = 0;
-    }
-
-    QEventLoop* mEventLoop;
-    MeegoFileDialogMode mMode;
-    QString mCaption;
-    QStringList mSelectedFileNames;
-};
-
-#endif // NSMFILEDIALOG_H
deleted file mode 100644
--- a/widget/qt/nsNativeThemeQt.cpp
+++ /dev/null
@@ -1,688 +0,0 @@
-/* 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 <QApplication>
-#include <QStyle>
-#include <QPalette>
-#include <QRect>
-#include <QPainter>
-#include <QStyleOption>
-#include <QStyleOptionFrameV2>
-#include <QStyleOptionButton>
-#include <QFlags>
-#include <QStyleOptionComboBox>
-
-#include "nsIFrame.h"
-
-#include "nsCoord.h"
-#include "nsNativeThemeQt.h"
-#include "nsPresContext.h"
-
-#include "nsRect.h"
-#include "nsSize.h"
-#include "nsTransform2D.h"
-#include "nsThemeConstants.h"
-#include "nsIServiceManager.h"
-#include "nsIDOMHTMLInputElement.h"
-
-
-#include "gfxASurface.h"
-#include "gfxContext.h"
-#include "gfxQtPlatform.h"
-#include "gfxQPainterSurface.h"
-#ifdef MOZ_X11
-#include "gfxXlibSurface.h"
-#endif
-#include "nsRenderingContext.h"
-
-nsNativeThemeQt::nsNativeThemeQt()
-{
-    mNoBackgroundPalette.setColor(QPalette::Window, Qt::transparent);
-    ThemeChanged();
-}
-
-nsNativeThemeQt::~nsNativeThemeQt()
-{
-}
-
-NS_IMPL_ISUPPORTS_INHERITED1(nsNativeThemeQt, nsNativeTheme, nsITheme)
-
-static inline QRect qRectInPixels(const nsRect &aRect,
-                                  const int32_t p2a)
-{
-    return QRect(NSAppUnitsToIntPixels(aRect.x, p2a),
-                 NSAppUnitsToIntPixels(aRect.y, p2a),
-                 NSAppUnitsToIntPixels(aRect.width, p2a),
-                 NSAppUnitsToIntPixels(aRect.height, p2a));
-}
-
-static inline QImage::Format
-_qimage_from_gfximage_format (gfxImageFormat aFormat)
-{
-    switch (aFormat) {
-    case gfxImageFormat::ARGB32:
-        return QImage::Format_ARGB32_Premultiplied;
-    case gfxImageFormat::RGB24:
-        return QImage::Format_RGB32;
-    case gfxImageFormat::RGB16_565:
-        return QImage::Format_RGB16;
-    case gfxImageFormat::A8:
-        return QImage::Format_Indexed8;
-    case gfxImageFormat::A1:
-#ifdef WORDS_BIGENDIAN
-        return QImage::Format_Mono;
-#else
-        return QImage::Format_MonoLSB;
-#endif
-    default:
-        return QImage::Format_Invalid;
-    }
-
-    return QImage::Format_Mono;
-}
-
-NS_IMETHODIMP
-nsNativeThemeQt::DrawWidgetBackground(nsRenderingContext* aContext,
-                                      nsIFrame* aFrame,
-                                      uint8_t aWidgetType,
-                                      const nsRect& aRect,
-                                      const nsRect& aClipRect)
-{
-    gfxContext* context = aContext->ThebesContext();
-    nsRefPtr<gfxASurface> surface = context->CurrentSurface();
-
-#ifdef CAIRO_HAS_QT_SURFACE
-    if (surface->GetType() == gfxSurfaceType::QPainter) {
-        gfxQPainterSurface* qSurface = (gfxQPainterSurface*) (surface.get());
-        QPainter *painter = qSurface->GetQPainter();
-        NS_ASSERTION(painter, "Where'd my QPainter go?");
-        if (!painter)
-            return NS_ERROR_FAILURE;
-        return DrawWidgetBackground(painter, aContext,
-                                    aFrame, aWidgetType,
-                                    aRect, aClipRect);
-    } else
-#endif
-    if (surface->GetType() == gfxSurfaceType::Image) {
-        gfxImageSurface* qSurface = (gfxImageSurface*) (surface.get());
-        QImage tempQImage(qSurface->Data(),
-                          qSurface->Width(),
-                          qSurface->Height(),
-                          qSurface->Stride(),
-                          _qimage_from_gfximage_format(qSurface->Format()));
-        QPainter painter(&tempQImage);
-        return DrawWidgetBackground(&painter, aContext,
-                                    aFrame, aWidgetType,
-                                    aRect, aClipRect);
-    }
-#if defined(MOZ_X11) && defined(Q_WS_X11)
-    else if (surface->GetType() == gfxSurfaceType::Xlib) {
-        gfxXlibSurface* qSurface = (gfxXlibSurface*) (surface.get());
-        QPixmap pixmap(QPixmap::fromX11Pixmap(qSurface->XDrawable()));
-        QPainter painter(&pixmap);
-        return DrawWidgetBackground(&painter, aContext,
-                                    aFrame, aWidgetType,
-                                    aRect, aClipRect);
-    }
-#endif
-
-    return NS_ERROR_NOT_IMPLEMENTED;
-}
-
-nsresult
-nsNativeThemeQt::DrawWidgetBackground(QPainter *qPainter,
-                                      nsRenderingContext* aContext,
-                                      nsIFrame* aFrame,
-                                      uint8_t aWidgetType,
-                                      const nsRect& aRect,
-                                      const nsRect& aClipRect)
-
-{
-    gfxContext* context = aContext->ThebesContext();
-    nsRefPtr<gfxASurface> surface = context->CurrentSurface();
-
-    context->UpdateSurfaceClip();
-
-    QStyle* style = qApp->style();
-
-    qPainter->save();
-
-    gfxPoint offs = surface->GetDeviceOffset();
-    qPainter->translate(offs.x, offs.y);
-
-    gfxMatrix ctm = context->CurrentMatrix();
-    if (!ctm.HasNonTranslation()) {
-        ctm.x0 = NSToCoordRound(ctm.x0);
-        ctm.y0 = NSToCoordRound(ctm.y0);
-    }
-
-    QMatrix qctm(ctm.xx, ctm.yx, ctm.xy, ctm.yy, ctm.x0, ctm.y0);
-    qPainter->setWorldMatrix(qctm, true);
-
-    int32_t p2a = aContext->AppUnitsPerDevPixel();
-
-    QRect r = qRectInPixels(aRect, p2a);
-    QRect cr = qRectInPixels(aClipRect, p2a);
-
-    QStyle::State extraFlags = QStyle::State_None;
-
-    switch (aWidgetType) {
-    case NS_THEME_RADIO:
-    case NS_THEME_CHECKBOX: {
-        QStyleOptionButton opt;
-        InitButtonStyle (aWidgetType, aFrame, r, opt);
-
-        if (aWidgetType == NS_THEME_CHECKBOX)
-        {
-            style->drawPrimitive (QStyle::PE_IndicatorCheckBox, &opt, qPainter);
-        } else {
-            style->drawPrimitive (QStyle::PE_IndicatorRadioButton, &opt, qPainter);
-        }
-        break;
-    }
-    case NS_THEME_BUTTON:
-    case NS_THEME_BUTTON_BEVEL: {
-        QStyleOptionButton opt;
-        InitButtonStyle (aWidgetType, aFrame, r, opt);
-
-        if (aWidgetType == NS_THEME_BUTTON) {
-            style->drawPrimitive(QStyle::PE_PanelButtonCommand, &opt, qPainter);
-            if (IsDefaultButton(aFrame))
-                style->drawPrimitive(QStyle::PE_FrameDefaultButton, &opt, qPainter);
-        } else {
-            style->drawPrimitive(QStyle::PE_PanelButtonBevel, &opt, qPainter);
-            style->drawPrimitive(QStyle::PE_FrameButtonBevel, &opt, qPainter);
-        }
-        break;
-    }
-    case NS_THEME_SCROLLBAR: {
-        qPainter->fillRect(r, qApp->palette().brush(QPalette::Normal, QPalette::Window));
-        break;
-    }
-    case NS_THEME_SCROLLBAR_TRACK_HORIZONTAL: {
-        qPainter->fillRect(r, qApp->palette().brush(QPalette::Active, QPalette::Window));
-        break;
-    }
-    case NS_THEME_SCROLLBAR_TRACK_VERTICAL: {
-        qPainter->fillRect(r, qApp->palette().brush(QPalette::Active, QPalette::Window));
-        break;
-    }
-    case NS_THEME_SCROLLBAR_BUTTON_LEFT: {
-        QStyleOptionSlider opt;
-        InitPlainStyle(aWidgetType, aFrame, r, (QStyleOption&)opt, QStyle::State_Horizontal);
-        opt.orientation = Qt::Horizontal;
-        style->drawControl(QStyle::CE_ScrollBarSubLine, &opt, qPainter, nullptr);
-        break;
-        }
-    case NS_THEME_SCROLLBAR_BUTTON_RIGHT: {
-        QStyleOptionSlider opt;
-        InitPlainStyle(aWidgetType, aFrame, r, (QStyleOption&)opt, QStyle::State_Horizontal);
-        opt.orientation = Qt::Horizontal;
-        style->drawControl(QStyle::CE_ScrollBarAddLine, &opt, qPainter, nullptr);
-        break;
-        }
-    case NS_THEME_SCROLLBAR_BUTTON_UP: {
-        QStyleOptionSlider opt;
-        InitPlainStyle(aWidgetType, aFrame, r, (QStyleOption&)opt);
-        opt.orientation = Qt::Vertical;
-        style->drawControl(QStyle::CE_ScrollBarSubLine, &opt, qPainter, nullptr);
-        break;
-    }
-    case NS_THEME_SCROLLBAR_BUTTON_DOWN: {
-        QStyleOptionSlider opt;
-        InitPlainStyle(aWidgetType, aFrame, r, (QStyleOption&)opt);
-        opt.orientation = Qt::Vertical;
-        style->drawControl(QStyle::CE_ScrollBarAddLine, &opt, qPainter, nullptr);
-        break;
-    }
-    case NS_THEME_SCROLLBAR_THUMB_HORIZONTAL: {
-        extraFlags |= QStyle::State_Horizontal;
-        QStyleOptionSlider option;
-        InitPlainStyle(aWidgetType, aFrame, r, (QStyleOption&)option, extraFlags);
-        option.orientation = Qt::Horizontal;
-        style->drawControl(QStyle::CE_ScrollBarSlider, &option, qPainter, nullptr);
-        break;
-        }
-    case NS_THEME_SCROLLBAR_THUMB_VERTICAL: {
-        QStyleOptionSlider option;
-        InitPlainStyle(aWidgetType, aFrame, r, (QStyleOption&)option, extraFlags);
-        option.orientation = Qt::Vertical;
-        style->drawControl(QStyle::CE_ScrollBarSlider, &option, qPainter, nullptr);
-        break;
-    }
-    case NS_THEME_DROPDOWN: {
-        QStyleOptionComboBox comboOpt;
-        
-        InitComboStyle(aWidgetType, aFrame, r, comboOpt);
-
-        style->drawComplexControl(QStyle::CC_ComboBox, &comboOpt, qPainter);
-        break;
-    }
-    case NS_THEME_DROPDOWN_BUTTON: {
-        QStyleOptionComboBox option;
-
-        InitComboStyle(aWidgetType, aFrame, r, option);
-
-        style->drawPrimitive(QStyle::PE_FrameDefaultButton, &option, qPainter);
-        style->drawPrimitive(QStyle::PE_IndicatorSpinDown, &option, qPainter);
-        break;
-    }
-    case NS_THEME_DROPDOWN_TEXT:
-    case NS_THEME_DROPDOWN_TEXTFIELD:
-    case NS_THEME_NUMBER_INPUT:
-    case NS_THEME_TEXTFIELD:
-    case NS_THEME_TEXTFIELD_MULTILINE:
-    case NS_THEME_LISTBOX: {
-        QStyleOptionFrameV2 frameOpt;
-        nsEventStates eventState = GetContentState(aFrame, aWidgetType);
-
-        if (!IsDisabled(aFrame, eventState))
-            frameOpt.state |= QStyle::State_Enabled;
-
-        frameOpt.rect = r;
-        frameOpt.features = QStyleOptionFrameV2::Flat;
-
-        if (aWidgetType == NS_THEME_NUMBER_INPUT ||
-            aWidgetType == NS_THEME_TEXTFIELD ||
-            aWidgetType == NS_THEME_TEXTFIELD_MULTILINE) {
-            QRect contentRect = style->subElementRect(QStyle::SE_LineEditContents, &frameOpt);
-            contentRect.adjust(mFrameWidth, mFrameWidth, -mFrameWidth, -mFrameWidth);
-            qPainter->fillRect(contentRect, QBrush(Qt::white));
-        }
-        
-        frameOpt.palette = mNoBackgroundPalette;
-        style->drawPrimitive(QStyle::PE_FrameLineEdit, &frameOpt, qPainter, nullptr);
-        break;
-    }
-    case NS_THEME_MENUPOPUP: {
-        QStyleOptionMenuItem option;
-        InitPlainStyle(aWidgetType, aFrame, r, (QStyleOption&)option, extraFlags);
-        style->drawPrimitive(QStyle::PE_FrameMenu, &option, qPainter, nullptr);
-        break;
-    }
-    default:
-        break;
-    }
-
-    qPainter->restore();
-    return NS_OK;
-}
-
-NS_IMETHODIMP
-nsNativeThemeQt::GetWidgetBorder(nsDeviceContext* ,
-                                 nsIFrame* aFrame,
-                                 uint8_t aWidgetType,
-                                 nsIntMargin* aResult)
-{
-    (*aResult).top = (*aResult).bottom = (*aResult).left = (*aResult).right = 0;
-
-    QStyle* style = qApp->style();
-    switch(aWidgetType) {
-//     case NS_THEME_TEXTFIELD:
-//     case NS_THEME_LISTBOX:
-    case NS_THEME_MENUPOPUP: {
-       (*aResult).top = (*aResult).bottom = (*aResult).left = (*aResult).right = style->pixelMetric(QStyle::PM_MenuPanelWidth);
-       break;
-    }
-    default:
-        break;
-    }
-
-    return NS_OK;
-}
-
-bool
-nsNativeThemeQt::GetWidgetPadding(nsDeviceContext* ,
-                                  nsIFrame*, uint8_t aWidgetType,
-                                  nsIntMargin* aResult)
-{
-    // XXX: Where to get padding values, framewidth?
-    if (aWidgetType == NS_THEME_NUMBER_INPUT ||
-        aWidgetType == NS_THEME_TEXTFIELD ||
-        aWidgetType == NS_THEME_TEXTFIELD_MULTILINE ||
-        aWidgetType == NS_THEME_DROPDOWN) {
-        aResult->SizeTo(2, 2, 2, 2);
-        return true;
-    }
-
-    return false;
-}
-
-NS_IMETHODIMP
-nsNativeThemeQt::GetMinimumWidgetSize(nsRenderingContext* aContext, nsIFrame* aFrame,
-                                      uint8_t aWidgetType,
-                                      nsIntSize* aResult, bool* aIsOverridable)
-{
-    (*aResult).width = (*aResult).height = 0;
-    *aIsOverridable = true;
-
-    QStyle *s = qApp->style();
-
-    int32_t p2a = aContext->AppUnitsPerDevPixel();
-
-    switch (aWidgetType) {
-    case NS_THEME_RADIO:
-    case NS_THEME_CHECKBOX: {
-        nsRect frameRect = aFrame->GetRect();
-
-        QRect qRect = qRectInPixels(frameRect, p2a);
-
-        QStyleOptionButton option;
-
-        InitButtonStyle(aWidgetType, aFrame, qRect, option);
-
-        QRect rect = s->subElementRect(
-            (aWidgetType == NS_THEME_CHECKBOX) ?
-                QStyle::SE_CheckBoxIndicator :
-                QStyle::SE_RadioButtonIndicator,
-            &option,
-            nullptr);
-
-        (*aResult).width = rect.width();
-        (*aResult).height = rect.height();
-        break;
-    }
-    case NS_THEME_BUTTON: {
-        nsRect frameRect = aFrame->GetRect();
-
-        QRect qRect = qRectInPixels(frameRect, p2a);
-
-        QStyleOptionButton option;
-
-        InitButtonStyle(aWidgetType, aFrame, qRect, option);
-
-        QRect rect = s->subElementRect(
-            QStyle::SE_PushButtonFocusRect,
-            &option,
-            nullptr);
-
-        (*aResult).width = rect.width();
-        (*aResult).height = rect.height();
-        break;
-    }
-    case NS_THEME_SCROLLBAR_BUTTON_UP:
-    case NS_THEME_SCROLLBAR_BUTTON_DOWN: {
-        (*aResult).width = s->pixelMetric(QStyle::PM_ScrollBarExtent);
-        (*aResult).height = (*aResult).width;
-        //*aIsOverridable = false;
-        break;
-    }
-    case NS_THEME_SCROLLBAR_BUTTON_LEFT:
-    case NS_THEME_SCROLLBAR_BUTTON_RIGHT: {
-        (*aResult).height = s->pixelMetric(QStyle::PM_ScrollBarExtent);
-        (*aResult).width = (*aResult).height;
-        //*aIsOverridable = false;
-        break;
-        }
-    case NS_THEME_SCROLLBAR_THUMB_VERTICAL: {
-        (*aResult).width = s->pixelMetric(QStyle::PM_ScrollBarExtent);
-        (*aResult).height = s->pixelMetric(QStyle::PM_ScrollBarSliderMin);
-        //*aIsOverridable = false;
-        break;
-        }
-    case NS_THEME_SCROLLBAR_THUMB_HORIZONTAL: {
-        (*aResult).width = s->pixelMetric(QStyle::PM_ScrollBarSliderMin);
-        (*aResult).height = s->pixelMetric(QStyle::PM_ScrollBarExtent);
-        //*aIsOverridable = false;
-        break;
-        }
-    case NS_THEME_SCROLLBAR_TRACK_VERTICAL: {
-        (*aResult).width = s->pixelMetric(QStyle::PM_ScrollBarExtent);
-        (*aResult).height = s->pixelMetric(QStyle::PM_SliderLength);
-        break;
-        }
-    case NS_THEME_SCROLLBAR_TRACK_HORIZONTAL: {
-        (*aResult).width = s->pixelMetric(QStyle::PM_SliderLength);
-        (*aResult).height = s->pixelMetric(QStyle::PM_ScrollBarExtent);
-        break;
-        }
-    case NS_THEME_DROPDOWN_BUTTON: {
-        QStyleOptionComboBox comboOpt;
-        
-        nsRect frameRect = aFrame->GetRect();
-        QRect qRect = qRectInPixels(frameRect, p2a);
-        comboOpt.rect = qRect;
-
-        InitComboStyle(aWidgetType, aFrame, qRect, comboOpt);
-
-        QRect subRect = s->subControlRect(QStyle::CC_ComboBox, &comboOpt,
-                                          QStyle::SC_ComboBoxArrow, nullptr);
-  
-        (*aResult).width = subRect.width();
-        (*aResult).height = subRect.height();
-        //*aIsOverridable = false;
-        break;
-    }
-    case NS_THEME_DROPDOWN: {
-        QStyleOptionComboBox comboOpt;
-
-        nsRect frameRect = aFrame->GetRect();
-        QRect qRect = qRectInPixels(frameRect, p2a);
-        comboOpt.rect = qRect;
-
-        InitComboStyle(aWidgetType, aFrame, qRect, comboOpt);
-
-        QRect subRect = s->subControlRect(QStyle::CC_ComboBox, 
-                                          &comboOpt, 
-                                          QStyle::SC_ComboBoxFrame, 
-                                          nullptr);
-
-        (*aResult).width = subRect.width();
-        (*aResult).height = subRect.height();
-        //*aIsOverridable = false;
-        break;
-    }
-    case NS_THEME_DROPDOWN_TEXT: {
-        QStyleOptionComboBox comboOpt;
-        
-        nsRect frameRect = aFrame->GetRect();
-
-        QRect qRect = qRectInPixels(frameRect, p2a);
-        
-        comboOpt.rect = qRect;
-
-        QRect subRect = s->subControlRect(QStyle::CC_ComboBox, &comboOpt,
-                                          QStyle::SC_ComboBoxEditField, nullptr);
-       
-        (*aResult).width = subRect.width();
-        (*aResult).height = subRect.height();
-        //*aIsOverridable = false;
-        break;
-    }
-    case NS_THEME_DROPDOWN_TEXTFIELD: {
-        QStyleOptionComboBox comboOpt;
-        
-        nsRect frameRect = aFrame->GetRect();
-
-        QRect qRect = qRectInPixels(frameRect, p2a);
-
-        comboOpt.rect = qRect;
-
-        QRect subRect = s->subControlRect(QStyle::CC_ComboBox, &comboOpt,
-                                          QStyle::SC_ComboBoxArrow, nullptr);
-        QRect subRect2 = s->subControlRect(QStyle::CC_ComboBox, &comboOpt,
-                                           QStyle::SC_ComboBoxFrame, nullptr);
-
-        (*aResult).width = subRect.width() + subRect2.width();
-        (*aResult).height = std::max(subRect.height(), subRect2.height());
-        //*aIsOverridable = false;
-        break;
-    }
-    case NS_THEME_NUMBER_INPUT:
-    case NS_THEME_TEXTFIELD:
-    case NS_THEME_TEXTFIELD_MULTILINE:
-        break;
-    }
-    return NS_OK;
-}
-
-NS_IMETHODIMP
-nsNativeThemeQt::WidgetStateChanged(nsIFrame* aFrame, uint8_t aWidgetType,
-                                    nsIAtom* aAttribute, bool* aShouldRepaint)
-{
-    *aShouldRepaint = true;
-    return NS_OK;
-}
-
-
-NS_IMETHODIMP
-nsNativeThemeQt::ThemeChanged()
-{
-    QStyle *s = qApp->style();
-    if (s)
-      mFrameWidth = s->pixelMetric(QStyle::PM_DefaultFrameWidth);
-    return NS_OK;
-}
-
-bool
-nsNativeThemeQt::ThemeSupportsWidget(nsPresContext* aPresContext,
-                                     nsIFrame* aFrame,
-                                     uint8_t aWidgetType)
-{
-    switch (aWidgetType) {
-    case NS_THEME_SCROLLBAR:
-    case NS_THEME_SCROLLBAR_BUTTON_UP:
-    case NS_THEME_SCROLLBAR_BUTTON_DOWN:
-    case NS_THEME_SCROLLBAR_BUTTON_LEFT:
-    case NS_THEME_SCROLLBAR_BUTTON_RIGHT:
-    case NS_THEME_SCROLLBAR_THUMB_HORIZONTAL:
-    case NS_THEME_SCROLLBAR_THUMB_VERTICAL:
-    //case NS_THEME_SCROLLBAR_GRIPPER_HORIZONTAL:
-    //case NS_THEME_SCROLLBAR_GRIPPER_VERTICAL:
-    case NS_THEME_SCROLLBAR_TRACK_HORIZONTAL:
-    case NS_THEME_SCROLLBAR_TRACK_VERTICAL:
-    case NS_THEME_RADIO:
-    case NS_THEME_CHECKBOX:
-    case NS_THEME_BUTTON_BEVEL:
-    case NS_THEME_BUTTON:
-    case NS_THEME_DROPDOWN:
-    case NS_THEME_DROPDOWN_BUTTON:
-    case NS_THEME_DROPDOWN_TEXT:
-    case NS_THEME_DROPDOWN_TEXTFIELD:
-    case NS_THEME_NUMBER_INPUT:
-    case NS_THEME_TEXTFIELD:
-    case NS_THEME_TEXTFIELD_MULTILINE:
-    case NS_THEME_LISTBOX:
-    case NS_THEME_MENUPOPUP:
-        return !IsWidgetStyled(aPresContext, aFrame, aWidgetType);
-    default:
-        break;
-    }
-    return false;
-}
-
-bool
-nsNativeThemeQt::WidgetIsContainer(uint8_t aWidgetType)
-{
-//     if (aWidgetType == NS_THEME_DROPDOWN_BUTTON ||
-//         aWidgetType == NS_THEME_RADIO ||
-//         aWidgetType == NS_THEME_CHECKBOX) {
-//         return false;
-//     }
-
-   return true;
-}
-
-bool
-nsNativeThemeQt::ThemeDrawsFocusForWidget(uint8_t aWidgetType)
-{
-    if (aWidgetType == NS_THEME_DROPDOWN ||
-        aWidgetType == NS_THEME_BUTTON || 
-        aWidgetType == NS_THEME_TREEVIEW_HEADER_CELL) { 
-        return true;
-    }
-
-    return false;
-}
-
-bool
-nsNativeThemeQt::ThemeNeedsComboboxDropmarker()
-{
-    return true;
-}
-
-void
-nsNativeThemeQt::InitButtonStyle(uint8_t aWidgetType,
-                                 nsIFrame* aFrame,
-                                 QRect rect,
-                                 QStyleOptionButton &opt)
-{
-    nsEventStates eventState = GetContentState(aFrame, aWidgetType);
-
-    opt.rect = rect;
-    opt.palette = mNoBackgroundPalette;
-
-    bool isDisabled = IsDisabled(aFrame, eventState);
-
-    if (!isDisabled)
-        opt.state |= QStyle::State_Enabled;
-    if (eventState.HasState(NS_EVENT_STATE_HOVER))
-        opt.state |= QStyle::State_MouseOver;
-    if (eventState.HasState(NS_EVENT_STATE_FOCUS))
-        opt.state |= QStyle::State_HasFocus;
-    if (!isDisabled && eventState.HasState(NS_EVENT_STATE_ACTIVE))
-        // Don't allow sunken when disabled
-        opt.state |= QStyle::State_Sunken;
-
-    switch (aWidgetType) {
-    case NS_THEME_RADIO:
-    case NS_THEME_CHECKBOX:
-        if (IsChecked(aFrame))
-            opt.state |= QStyle::State_On;
-        else
-            opt.state |= QStyle::State_Off;
-
-        break;
-    default:
-        if (!eventState.HasState(NS_EVENT_STATE_ACTIVE))
-            opt.state |= QStyle::State_Raised;
-        break;
-    }
-}
-
-void
-nsNativeThemeQt::InitPlainStyle(uint8_t aWidgetType,
-                                nsIFrame* aFrame,
-                                QRect rect,
-                                QStyleOption &opt,
-                                QStyle::State extraFlags)
-{
-    nsEventStates eventState = GetContentState(aFrame, aWidgetType);
-
-    opt.rect = rect;
-
-    if (!IsDisabled(aFrame, eventState))
-        opt.state |= QStyle::State_Enabled;
-    if (eventState.HasState(NS_EVENT_STATE_HOVER))
-        opt.state |= QStyle::State_MouseOver;
-    if (eventState.HasState(NS_EVENT_STATE_FOCUS))
-        opt.state |= QStyle::State_HasFocus;
-
-    opt.state |= extraFlags;
-}
-
-void
-nsNativeThemeQt::InitComboStyle(uint8_t aWidgetType,
-                                nsIFrame* aFrame,
-                                QRect rect,
-                                QStyleOptionComboBox &opt)
-{
-    nsEventStates eventState = GetContentState(aFrame, aWidgetType);
-    bool isDisabled = IsDisabled(aFrame, eventState);
-
-    if (!isDisabled)
-        opt.state |= QStyle::State_Enabled;
-    if (eventState.HasState(NS_EVENT_STATE_HOVER))
-        opt.state |= QStyle::State_MouseOver;
-    if (eventState.HasState(NS_EVENT_STATE_FOCUS))
-        opt.state |= QStyle::State_HasFocus;
-    if (!eventState.HasState(NS_EVENT_STATE_ACTIVE))
-        opt.state |= QStyle::State_Raised;
-    if (!isDisabled && eventState.HasState(NS_EVENT_STATE_ACTIVE))
-        // Don't allow sunken when disabled
-        opt.state |= QStyle::State_Sunken;
-
-    opt.rect = rect;
-    opt.palette = mNoBackgroundPalette;
-}
deleted file mode 100644
--- a/widget/qt/nsNativeThemeQt.h
+++ /dev/null
@@ -1,99 +0,0 @@
-/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
- *
- * 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 <QStyle>
-#include <QPalette>
-
-#include "nsITheme.h"
-#include "nsCOMPtr.h"
-#include "nsIAtom.h"
-#include "nsNativeTheme.h"
-
-class QComboBox;
-class QStyleOptionButton;
-class QStyleOptionComboBox;
-class QRect;
-class nsIFrame;
-class nsDeviceContext;
-
-class nsNativeThemeQt : private nsNativeTheme,
-                        public nsITheme
-{
-public:
-  NS_DECL_ISUPPORTS_INHERITED
-
-  // The nsITheme interface.
-  NS_IMETHOD DrawWidgetBackground(nsRenderingContext* aContext,
-                                  nsIFrame* aFrame,
-                                  uint8_t aWidgetType,
-                                  const nsRect& aRect,
-                                  const nsRect& aClipRect);
-
-  NS_IMETHOD GetWidgetBorder(nsDeviceContext* aContext,
-                             nsIFrame* aFrame,
-                             uint8_t aWidgetType,
-                             nsIntMargin* aResult);
-
-  NS_IMETHOD GetMinimumWidgetSize(nsRenderingContext* aContext, nsIFrame* aFrame,
-                                  uint8_t aWidgetType,
-                                  nsIntSize* aResult,
-                                  bool* aIsOverridable);
-
-  NS_IMETHOD WidgetStateChanged(nsIFrame* aFrame, uint8_t aWidgetType,
-                                nsIAtom* aAttribute, bool* aShouldRepaint);
-
-  NS_IMETHOD ThemeChanged();
-
-  bool ThemeSupportsWidget(nsPresContext* aPresContext,
-                             nsIFrame* aFrame,
-                             uint8_t aWidgetType);
-
-  bool WidgetIsContainer(uint8_t aWidgetType);
-
-  virtual NS_HIDDEN_(bool) GetWidgetPadding(nsDeviceContext* aContext,
-                                              nsIFrame* aFrame,
-                                              uint8_t aWidgetType,
-                                              nsIntMargin* aResult);
-
-  NS_IMETHOD_(bool) ThemeDrawsFocusForWidget(uint8_t aWidgetType) MOZ_OVERRIDE;
-
-  bool ThemeNeedsComboboxDropmarker();
-
-  nsNativeThemeQt();
-  virtual ~nsNativeThemeQt();
-
-private:
-
-  inline nsresult DrawWidgetBackground(QPainter *qPainter,
-                                       nsRenderingContext* aContext,
-                                       nsIFrame* aFrame,
-                                       uint8_t aWidgetType,
-                                       const nsRect& aRect,
-                                       const nsRect& aClipRect);
-
-  void InitButtonStyle(uint8_t widgetType,
-                       nsIFrame* aFrame,
-                       QRect rect,
-                       QStyleOptionButton &opt);
-
-  void InitPlainStyle(uint8_t aWidgetType,
-                      nsIFrame* aFrame,
-                      QRect rect,
-                      QStyleOption &opt,
-                      QStyle::State extraFlags = QStyle::State_None);
-
-  void InitComboStyle(uint8_t aWidgetType,
-                      nsIFrame* aFrame,
-                      QRect rect,
-                      QStyleOptionComboBox &opt);
-
-private:
-
-  int32_t mFrameWidth;
-
-  QPalette mNoBackgroundPalette;
-};
-
--- a/widget/qt/nsQtKeyUtils.cpp
+++ b/widget/qt/nsQtKeyUtils.cpp
@@ -1,14 +1,15 @@
 /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
  *
  * 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 <qnamespace.h>
 #include "mozilla/ArrayUtils.h"
 #include "mozilla/TextEvents.h"
 
 #include "nsWindow.h"
 #include "nsQtKeyUtils.h"
 
 using namespace mozilla;
 using namespace mozilla::widget;
@@ -466,23 +467,19 @@ QtKeyCodeToDOMKeyNameIndex(int aKeysym)
         case Qt::Key_AudioCycleTrack:
         case Qt::Key_Time:
         case Qt::Key_Hibernate:
         case Qt::Key_View:
         case Qt::Key_TopMenu:
         case Qt::Key_PowerDown:
         case Qt::Key_Suspend:
         case Qt::Key_ContrastAdjust:
-
-#if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0))
         case Qt::Key_TouchpadToggle:
         case Qt::Key_TouchpadOn:
         case Qt::Key_TouchpadOff:
-#endif
-
         case Qt::Key_unknown:
         case Qt::Key_Call:
         case Qt::Key_CameraFocus:
         case Qt::Key_Context1:
         case Qt::Key_Context2:
         case Qt::Key_Context3:
         case Qt::Key_Context4:
         case Qt::Key_Flip:
--- a/widget/qt/nsScreenManagerQt.cpp
+++ b/widget/qt/nsScreenManagerQt.cpp
@@ -1,66 +1,67 @@
 /* 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 "qdesktopwidget.h"
-#include "qapplication.h"
+#include <QGuiApplication>
+#include <QScreen>
 
 #include "nsScreenManagerQt.h"
 #include "nsScreenQt.h"
 
 nsScreenManagerQt::nsScreenManagerQt()
 {
+    mInitialized = false;
     desktop = 0;
     screens = 0;
 }
 
 nsScreenManagerQt::~nsScreenManagerQt()
 {
     delete [] screens;
 }
 
 // addref, release, QI
 NS_IMPL_ISUPPORTS1(nsScreenManagerQt, nsIScreenManager)
 
 void nsScreenManagerQt::init()
 {
-    if (desktop)
+    if (mInitialized)
         return;
 
-    desktop = QApplication::desktop();
-    nScreens = desktop->numScreens();
+    nScreens = QGuiApplication::screens().size();
     screens = new nsCOMPtr<nsIScreen>[nScreens];
 
     for (int i = 0; i < nScreens; ++i)
         screens[i] = new nsScreenQt(i);
+    mInitialized = true;
 }
 
 //
 // ScreenForRect
 //
 // Returns the screen that contains the rectangle. If the rect overlaps
 // multiple screens, it picks the screen with the greatest area of intersection.
 //
 // The coordinates are in pixels (not twips) and in screen coordinates.
 //
 NS_IMETHODIMP
 nsScreenManagerQt::ScreenForRect(int32_t inLeft, int32_t inTop,
-				 int32_t inWidth, int32_t inHeight,
-				 nsIScreen **outScreen)
+                                 int32_t inWidth, int32_t inHeight,
+                                 nsIScreen **outScreen)
 {
-    if (!desktop)
+    if (!mInitialized)
         init();
 
     QRect r(inLeft, inTop, inWidth, inHeight);
     int best = 0;
     int area = 0;
     for (int i = 0; i < nScreens; ++i) {
-        const QRect& rect = desktop->screenGeometry(i);
+        const QRect& rect = QGuiApplication::screens()[i]->geometry();
         QRect intersection = r&rect;
         int a = intersection.width()*intersection.height();
         if (a > area) {
             best = i;
             area = a;
         }
     }
 
@@ -90,27 +91,27 @@ nsScreenManagerQt::GetPrimaryScreen(nsIS
 // Returns how many physical screens are available.
 //
 NS_IMETHODIMP
 nsScreenManagerQt::GetNumberOfScreens(uint32_t *aNumberOfScreens)
 {
     if (!desktop)
         init();
 
-    *aNumberOfScreens = desktop->numScreens();
+    *aNumberOfScreens = nScreens;
     return NS_OK;
 }
 
 NS_IMETHODIMP
 nsScreenManagerQt::GetSystemDefaultScale(float *aDefaultScale)
 {
     *aDefaultScale = 1.0f;
     return NS_OK;
 }
 
 NS_IMETHODIMP
-nsScreenManagerQt :: ScreenForNativeWidget (void *aWidget, nsIScreen **outScreen)
+nsScreenManagerQt::ScreenForNativeWidget(void *aWidget, nsIScreen **outScreen)
 {
     // I don't know how to go from GtkWindow to nsIScreen, especially
     // given xinerama and stuff, so let's just do this
-    QRect rect = static_cast<QWidget*>(aWidget)->geometry();
+    QRect rect(0, 0, 1, 1);
     return ScreenForRect(rect.x(), rect.y(), rect.width(), rect.height(), outScreen);
 }
--- a/widget/qt/nsScreenManagerQt.h
+++ b/widget/qt/nsScreenManagerQt.h
@@ -24,11 +24,12 @@ public:
 
 private:
 
   void init ();
 
   nsCOMPtr<nsIScreen> *screens;
   QDesktopWidget *desktop;
   int nScreens;
+  bool mInitialized;
 };
 
 #endif  // nsScreenManagerQt_h___
--- a/widget/qt/nsScreenQt.cpp
+++ b/widget/qt/nsScreenQt.cpp
@@ -1,121 +1,67 @@
 /* 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 <qcolor.h>
-#include <qcolormap.h>
-#include <qrect.h>
-#include <qdesktopwidget.h>
-#include <qapplication.h>
+#include <QColor>
+#include <QRect>
+#include <QGuiApplication>
 #include <QTransform>
+#include <QScreen>
 
 #include "nsScreenQt.h"
 #include "nsXULAppAPI.h"
 
-#ifdef MOZ_ENABLE_QTMOBILITY
-#include "mozqorientationsensorfilter.h"
-#endif
-
-#ifdef MOZ_ENABLE_QMSYSTEM2
-#include <qmdisplaystate.h>
-using namespace mozilla;
-
-const int DISPLAY_BLANK_TIMEOUT = 10800; /*3 * 60 * 60 seconds*/
-const int DISPLAY_DIM_TIMEOUT = 10620; /*3 * 59 * 60 seconds*/
-
-#endif
-
 nsScreenQt::nsScreenQt(int aScreen)
     : mScreen(aScreen)
-#ifdef MOZ_ENABLE_QMSYSTEM2
-    , mDisplayState(nullptr)
-#endif
 {
     // nothing else to do. I guess we could cache a bunch of information
     // here, but we want to ask the device at runtime in case anything
     // has changed.
 }
 
 nsScreenQt::~nsScreenQt()
 {
-#ifdef MOZ_ENABLE_QMSYSTEM2
-    delete mDisplayState;
-    mDisplayState = nullptr;
-#endif
 }
 
 NS_IMETHODIMP
 nsScreenQt::GetRect(int32_t *outLeft,int32_t *outTop,
                     int32_t *outWidth,int32_t *outHeight)
 {
-    QRect r = QApplication::desktop()->screenGeometry(mScreen);
-#ifdef MOZ_ENABLE_QTMOBILITY
-    r = MozQOrientationSensorFilter::GetRotationTransform().mapRect(r);
-    // just rotating gives us weird negative coordinates, but we want to return
-    // sensible logical coordinates
-    r.moveTo(0, 0);
-#endif
+    QRect r = QGuiApplication::screens()[mScreen]->geometry();
 
     *outTop = r.x();
     *outLeft = r.y();
     *outWidth = r.width();
     *outHeight = r.height();
 
     return NS_OK;
 }
 
 NS_IMETHODIMP
 nsScreenQt::GetAvailRect(int32_t *outLeft,int32_t *outTop,
                          int32_t *outWidth,int32_t *outHeight)
 {
-    QRect r = QApplication::desktop()->screenGeometry(mScreen);
-#ifdef MOZ_ENABLE_QTMOBILITY
-    r = MozQOrientationSensorFilter::GetRotationTransform().mapRect(r);
-#endif
+    QRect r = QGuiApplication::screens()[mScreen]->geometry();
 
     *outTop = r.x();
     *outLeft = r.y();
     *outWidth = r.width();
     *outHeight = r.height();
 
     return NS_OK;
 }
 
 NS_IMETHODIMP
 nsScreenQt::GetPixelDepth(int32_t *aPixelDepth)
 {
     // #############
-    *aPixelDepth = (int32_t)QColormap::instance().depth();
+    *aPixelDepth = QGuiApplication::primaryScreen()->depth();
     return NS_OK;
 }
 
 NS_IMETHODIMP
 nsScreenQt::GetColorDepth(int32_t *aColorDepth)
 {
     // ###############
     return GetPixelDepth(aColorDepth);
 }
-
-#ifdef MOZ_ENABLE_QMSYSTEM2
-void
-nsScreenQt::ApplyMinimumBrightness(uint32_t aType)
-{
-    // resets all we did before,
-    // 1) there is no interface to get default values
-    // 2) user might have changed system settings while fennec is running
-    //    there is no notification about that.
-    delete mDisplayState;
-    mDisplayState = nullptr;
-
-    if( aType == BRIGHTNESS_FULL) {
-        mDisplayState = new MeeGo::QmDisplayState();
-
-        // no way to keep display from blanking than setting a huge timeout
-        // parameter is seconds. setting timeout to huge time this should work for 99.9% of our usecases
-        mDisplayState->setDisplayBlankTimeout( DISPLAY_BLANK_TIMEOUT /*in seconds*/ );
-        mDisplayState->setDisplayDimTimeout( DISPLAY_DIM_TIMEOUT /*in seconds*/ );
-        mDisplayState->setDisplayBrightnessValue( mDisplayState->getMaxDisplayBrightnessValue() );
-        mDisplayState->set(MeeGo::QmDisplayState::On);
-     }
-}
-#endif
--- a/widget/qt/nsScreenQt.h
+++ b/widget/qt/nsScreenQt.h
@@ -3,40 +3,26 @@
  * 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 nsScreenQt_h___
 #define nsScreenQt_h___
 
 #include "nsBaseScreen.h"
 
-#ifdef MOZ_ENABLE_QMSYSTEM2
-namespace MeeGo
-{
-    class QmDisplayState;
-}
-#endif
-
-
 //------------------------------------------------------------------------
 
 class nsScreenQt : public nsBaseScreen
 {
 public:
   nsScreenQt (int aScreen);
   virtual ~nsScreenQt();
 
   NS_IMETHOD GetRect(int32_t* aLeft, int32_t* aTop, int32_t* aWidth, int32_t* aHeight);
   NS_IMETHOD GetAvailRect(int32_t* aLeft, int32_t* aTop, int32_t* aWidth, int32_t* aHeight);
   NS_IMETHOD GetPixelDepth(int32_t* aPixelDepth);
   NS_IMETHOD GetColorDepth(int32_t* aColorDepth);
 
-#ifdef MOZ_ENABLE_QMSYSTEM2
-protected:
-  virtual void ApplyMinimumBrightness(uint32_t aType) MOZ_OVERRIDE;
-private:
-  MeeGo::QmDisplayState* mDisplayState;
-#endif
 private:
   int mScreen;
 };
 
 #endif  // nsScreenQt_h___
deleted file mode 100644
--- a/widget/qt/nsSound.cpp
+++ /dev/null
@@ -1,380 +0,0 @@
-/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
- *
- * 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 <QApplication>
-
-#include <string.h>
-#include <unistd.h>
-
-#include "nscore.h"
-#include "plstr.h"
-#include "prlink.h"
-
-#include "nsSound.h"
-#include "nsString.h"
-
-#include "nsIURL.h"
-#include "nsIFileURL.h"
-#include "nsNetUtil.h"
-#include "nsCOMPtr.h"
-#include "nsNativeCharsetUtils.h"
-#include "nsAutoPtr.h"
-
-/* used with esd_open_sound */
-static int esdref = -1;
-static PRLibrary *elib = nullptr;
-
-// the following from esd.h
-
-#define ESD_BITS8  (0x0000)
-#define ESD_BITS16 (0x0001) 
-#define ESD_MONO (0x0010)
-#define ESD_STEREO (0x0020) 
-#define ESD_STREAM (0x0000)
-#define ESD_PLAY (0x1000)
-
-#define WAV_MIN_LENGTH 44
-
-typedef int (*EsdOpenSoundType)(const char *host);
-typedef int (*EsdCloseType)(int);
-
-/* used to play the sounds from the find symbol call */
-typedef int  (*EsdPlayStreamType) (int, int, const char *, const char *);
-typedef int  (*EsdAudioOpenType)  (void);
-typedef int  (*EsdAudioWriteType) (const void *, int);
-typedef void (*EsdAudioCloseType) (void);
-
-NS_IMPL_ISUPPORTS2(nsSound, nsISound, nsIStreamLoaderObserver)
-
-nsSound::nsSound()
- : mInited( false )
-{
-}
-
-nsSound::~nsSound()
-{
-    /* see above comment */
-    if (esdref != -1) {
-        EsdCloseType EsdClose = (EsdCloseType) PR_FindFunctionSymbol(elib, "esd_close");
-        if (EsdClose)
-            (*EsdClose)(esdref);
-        esdref = -1;
-    }
-}
-
-
-/**
-* unload esd library
-*/
-void
-nsSound::Shutdown()
-{
-    if (elib) {
-        PR_UnloadLibrary(elib);
-        elib = nullptr;
-    }
-}
-
-NS_IMETHODIMP
-nsSound::Init()
-{
-    /* we don't need to do esd_open_sound if we are only going to play files
-       but we will if we want to do things like streams, etc
-    */
-    if (mInited) 
-        return NS_OK;
-    if (elib) 
-        return NS_OK;
-
-    EsdOpenSoundType EsdOpenSound;
-
-    elib = PR_LoadLibrary("libesd.so.0");
-    if (!elib) return NS_ERROR_NOT_AVAILABLE;
-
-    EsdOpenSound = (EsdOpenSoundType) PR_FindFunctionSymbol(elib, "esd_open_sound");
-
-    if (!EsdOpenSound)
-        return NS_ERROR_FAILURE;
-
-    esdref = (*EsdOpenSound)("localhost");
-
-    if (!esdref)
-        return NS_ERROR_FAILURE;
-
-    mInited = true;
-
-    return NS_OK;
-}
-
-NS_METHOD nsSound::Beep()
-{
-    QApplication::beep();
-    return NS_OK;
-}
-
-
-/**
-* This can't be implemented directly with QT.
-* (We can use QSound to play local files but that was not enough.
-* Also support of media formats is limited)
-*
-* Current implementation is copied from GTK side and implementation uses ESD interface.
-*
-* If we have Qtopia then we can drop ESD implementation and use Qtopia "Multimedia API"
-*/
-NS_IMETHODIMP nsSound::OnStreamComplete(nsIStreamLoader *aLoader,
-                                        nsISupports *context,
-                                        nsresult aStatus,
-                                        uint32_t dataLen,
-                                        const uint8_t *data)
-{
-
-#define GET_WORD(s, i) (s[i+1] << 8) | s[i]
-#define GET_DWORD(s, i) (s[i+3] << 24) | (s[i+2] << 16) | (s[i+1] << 8) | s[i]
-
-    // print a load error on bad status, and return
-    if (NS_FAILED(aStatus)) {
-#ifdef DEBUG
-        if (aLoader) {
-            nsCOMPtr<nsIRequest> request;
-            aLoader->GetRequest(getter_AddRefs(request));
-            if (request) {
-                nsCOMPtr<nsIURI> uri;
-                nsCOMPtr<nsIChannel> channel = do_QueryInterface(request);
-                if (channel) {
-                      channel->GetURI(getter_AddRefs(uri));
-                      if (uri) {
-                            nsAutoCString uriSpec;
-                            uri->GetSpec(uriSpec);
-                            printf("Failed to load %s\n", uriSpec.get());
-                      }
-                }
-            }
-        }
-#endif
-        return aStatus;
-    }
-
-    int fd, mask = 0;
-    uint32_t samples_per_sec = 0, avg_bytes_per_sec = 0, chunk_len = 0;
-    uint16_t format, channels = 1, bits_per_sample = 0;
-    const uint8_t *audio = nullptr;
-    size_t audio_len = 0;
-
-    if (dataLen < 4) {
-        NS_WARNING("Sound stream too short to determine its type");
-        return NS_ERROR_FAILURE;
-    }
-
-    if (memcmp(data, "RIFF", 4)) {
-#ifdef DEBUG
-        printf("We only support WAV files currently.\n");
-#endif
-        return NS_ERROR_FAILURE;
-    }
-
-    if (dataLen <= WAV_MIN_LENGTH) {
-        NS_WARNING("WAV files should be longer than 44 bytes.");
-        return NS_ERROR_FAILURE;
-    }
-
-    uint32_t i = 12;
-    while (i + 7 < dataLen) {
-        if (!memcmp(data + i, "fmt ", 4) && !chunk_len) {
-            i += 4;
-
-            /* length of the rest of this subblock (should be 16 for PCM data */
-            chunk_len = GET_DWORD(data, i);
-            i += 4;
-
-            if (chunk_len < 16 || i + chunk_len >= dataLen) {
-                NS_WARNING("Invalid WAV file: bad fmt chunk.");
-                return NS_ERROR_FAILURE;
-            }
-
-            format = GET_WORD(data, i);
-            i += 2;
-
-            channels = GET_WORD(data, i);
-            i += 2;
-
-            samples_per_sec = GET_DWORD(data, i);
-            i += 4;
-
-            avg_bytes_per_sec = GET_DWORD(data, i);
-            i += 4;
-
-            // block align
-            i += 2;
-
-            bits_per_sample = GET_WORD(data, i);
-            i += 2;
-
-            /* we don't support WAVs with odd compression codes */
-            if (chunk_len != 16)
-                NS_WARNING("Extra format bits found in WAV. Ignoring");
-
-            i += chunk_len - 16;
-        } else if (!memcmp(data + i, "data", 4)) {
-            i += 4;
-            if (!chunk_len) {
-                NS_WARNING("Invalid WAV file: no fmt chunk found");
-                return NS_ERROR_FAILURE;
-            }
-
-            audio_len = GET_DWORD(data, i);
-            i += 4;
-
-            /* try to play truncated WAVs */
-            if (i + audio_len > dataLen)
-                audio_len = dataLen - i;
-
-            audio = data + i;
-            break;
-        } else {
-            i += 4;
-            i += GET_DWORD(data, i);
-            i += 4;
-        }
-    }
-
-    if (!audio) {
-        NS_WARNING("Invalid WAV file: no data chunk found");
-        return NS_ERROR_FAILURE;
-    }
-
-    /* No audio data? well, at least the WAV was valid. */
-    if (!audio_len)
-        return NS_OK;
-
-#if 0
-    printf("f: %d | c: %d | sps: %li | abps: %li | ba: %d | bps: %d | rate: %li\n",
-         format, channels, samples_per_sec, avg_bytes_per_sec, block_align, bits_per_sample, rate);
-#endif
-
-    /* open up connection to esd */  
-    EsdPlayStreamType EsdPlayStream = 
-        (EsdPlayStreamType) PR_FindFunctionSymbol(elib, 
-                                                  "esd_play_stream");
-    if (!EsdPlayStream)
-        return NS_ERROR_FAILURE;
-
-    mask = ESD_PLAY | ESD_STREAM;
-
-    if (bits_per_sample == 8)
-        mask |= ESD_BITS8;
-    else 
-        mask |= ESD_BITS16;
-
-    if (channels == 1)
-        mask |= ESD_MONO;
-    else 
-        mask |= ESD_STEREO;
-
-    nsAutoArrayPtr<uint8_t> buf;
-
-    // ESD only handle little-endian data. 
-    // Swap the byte order if we're on a big-endian architecture.
-#ifdef IS_BIG_ENDIAN
-    if (bits_per_sample != 8) {
-        buf = new uint8_t[audio_len];
-        if (!buf)
-            return NS_ERROR_OUT_OF_MEMORY;
-        for (uint32_t j = 0; j + 2 < audio_len; j += 2) {
-            buf[j]     = audio[j + 1];
-            buf[j + 1] = audio[j];
-        }
-
-    audio = buf;
-    }
-#endif
-
-    fd = (*EsdPlayStream)(mask, samples_per_sec, nullptr, "mozillaSound"); 
-  
-    if (fd < 0) {
-      int *esd_audio_format = (int *) PR_FindSymbol(elib, "esd_audio_format");
-      int *esd_audio_rate = (int *) PR_FindSymbol(elib, "esd_audio_rate");
-      EsdAudioOpenType EsdAudioOpen = (EsdAudioOpenType) PR_FindFunctionSymbol(elib, "esd_audio_open");
-      EsdAudioWriteType EsdAudioWrite = (EsdAudioWriteType) PR_FindFunctionSymbol(elib, "esd_audio_write");
-      EsdAudioCloseType EsdAudioClose = (EsdAudioCloseType) PR_FindFunctionSymbol(elib, "esd_audio_close");
-
-      if (!esd_audio_format || !esd_audio_rate ||
-          !EsdAudioOpen || !EsdAudioWrite || !EsdAudioClose)
-          return NS_ERROR_FAILURE;
-
-      *esd_audio_format = mask;
-      *esd_audio_rate = samples_per_sec;
-      fd = (*EsdAudioOpen)();
-
-      if (fd < 0)
-        return NS_ERROR_FAILURE;
-
-      (*EsdAudioWrite)(audio, audio_len);
-      (*EsdAudioClose)();
-    } else {
-      while (audio_len > 0) {
-        size_t written = write(fd, audio, audio_len);
-        if (written <= 0)
-          break;
-        audio += written;
-        audio_len -= written;
-      }
-      close(fd);
-    }
-
-    return NS_OK;
-}
-
-NS_METHOD nsSound::Play(nsIURL *aURL)
-{
-    nsresult rv;
-
-    if (!mInited)
-        Init();
-
-    if (!elib) 
-        return NS_ERROR_NOT_AVAILABLE;
-
-    nsCOMPtr<nsIStreamLoader> loader;
-    rv = NS_NewStreamLoader(getter_AddRefs(loader), aURL, this);
-
-    return rv;
-}
-
-NS_IMETHODIMP nsSound::PlaySystemSound(const nsAString &aSoundAlias)
-{
-    if (NS_IsMozAliasSound(aSoundAlias)) {
-      NS_WARNING("nsISound::playSystemSound is called with \"_moz_\" events, they are obsolete, use nsISound::playEventSound instead");
-      if (aSoundAlias.Equals(NS_SYSSOUND_MAIL_BEEP))
-        return Beep();
-      return NS_OK;
-    }
-
-    nsresult rv;
-    nsCOMPtr <nsIURI> fileURI;
-
-    // create a nsIFile and then a nsIFileURL from that
-    nsCOMPtr <nsIFile> soundFile;
-    rv = NS_NewLocalFile(aSoundAlias, true, 
-                         getter_AddRefs(soundFile));
-    NS_ENSURE_SUCCESS(rv,rv);
-
-    rv = NS_NewFileURI(getter_AddRefs(fileURI), soundFile);
-    NS_ENSURE_SUCCESS(rv,rv);
-
-    nsCOMPtr<nsIFileURL> fileURL = do_QueryInterface(fileURI,&rv);
-    NS_ENSURE_SUCCESS(rv,rv);
-
-    rv = Play(fileURL);
-    return rv;
-
-}
-
-NS_IMETHODIMP nsSound::PlayEventSound(uint32_t aEventId)
-{
-    return aEventId == EVENT_NEW_MAIL_RECEIVED ? Beep() : NS_OK;
-}
-
deleted file mode 100644
--- a/widget/qt/nsSound.h
+++ /dev/null
@@ -1,30 +0,0 @@
-/* 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 __nsSound_h__
-#define __nsSound_h__
-
-#include "nsISound.h"
-#include "nsIStreamLoader.h"
-
-class nsSound : public nsISound,
-                public nsIStreamLoaderObserver
-{
- public:
-
-  nsSound();
-  virtual ~nsSound();
-
-  static void Shutdown();
-
-  NS_DECL_ISUPPORTS
-  NS_DECL_NSISOUND
-  NS_DECL_NSISTREAMLOADEROBSERVER
-
-private:
-  bool mInited;
-
-};
-
-#endif /* __nsSound_h__ */
--- a/widget/qt/nsWidgetFactory.cpp
+++ b/widget/qt/nsWidgetFactory.cpp
@@ -1,82 +1,67 @@
 /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
-/* 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/. */
+/* Copyright 2012 Mozilla Foundation and Mozilla contributors
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
 
-#include "nsWindow.h"
-#include "nsAppShell.h"
+#include "base/basictypes.h"
 
 #include "mozilla/ModuleUtils.h"
-#include "nsIModule.h"
 
 #include "nsCOMPtr.h"
 #include "nsWidgetsCID.h"
-#include "nsHTMLFormatConverter.h"
-#include "nsTransferable.h"
+#include "nsAppShell.h"
+
+#include "nsWindow.h"
 #include "nsLookAndFeel.h"
 #include "nsAppShellSingleton.h"
 #include "nsScreenManagerQt.h"
-#include "nsFilePicker.h"
-#include "nsClipboard.h"
-#include "nsClipboardHelper.h"
 #include "nsIdleServiceQt.h"
-#include "nsDragService.h"
-#include "nsSound.h"
+#include "nsTransferable.h"
 #include "nsBidiKeyboard.h"
-#include "nsNativeThemeQt.h"
+
+#include "nsHTMLFormatConverter.h"
+#include "nsXULAppAPI.h"
+
 #ifdef NS_PRINTING
 #include "nsDeviceContextSpecQt.h"
 #include "nsPrintSession.h"
 #include "nsPrintOptionsQt.h"
 #include "nsPrintDialogQt.h"
 #endif
-#include "nsFilePickerProxy.h"
-#include "nsXULAppAPI.h"
+
+#include "nsClipboard.h"
+#include "nsClipboardHelper.h"
 
 #if defined(MOZ_X11)
 #include "GfxInfoX11.h"
 #endif
 
-// from nsWindow.cpp
-extern bool gDisableNativeTheme;
+using namespace mozilla::widget;
 
 NS_GENERIC_FACTORY_CONSTRUCTOR(nsWindow)
-NS_GENERIC_FACTORY_CONSTRUCTOR(nsChildWindow)
-NS_GENERIC_FACTORY_CONSTRUCTOR(nsPopupWindow)
+NS_GENERIC_FACTORY_CONSTRUCTOR(nsBidiKeyboard)
+NS_GENERIC_FACTORY_CONSTRUCTOR(nsScreenManagerQt)
 NS_GENERIC_FACTORY_CONSTRUCTOR(nsHTMLFormatConverter)
+NS_GENERIC_FACTORY_SINGLETON_CONSTRUCTOR(nsIdleServiceQt, nsIdleServiceQt::GetInstance)
 NS_GENERIC_FACTORY_CONSTRUCTOR(nsTransferable)
-NS_GENERIC_FACTORY_CONSTRUCTOR(nsScreenManagerQt)
 NS_GENERIC_FACTORY_CONSTRUCTOR(nsClipboard)
 NS_GENERIC_FACTORY_CONSTRUCTOR(nsClipboardHelper)
-NS_GENERIC_FACTORY_CONSTRUCTOR(nsDragService)
-NS_GENERIC_FACTORY_CONSTRUCTOR(nsBidiKeyboard)
-NS_GENERIC_FACTORY_SINGLETON_CONSTRUCTOR(nsIdleServiceQt, nsIdleServiceQt::GetInstance)
-NS_GENERIC_FACTORY_CONSTRUCTOR(nsSound)
-
-static nsresult
-nsFilePickerConstructor(nsISupports *aOuter, REFNSIID aIID,
-                        void **aResult)
-{
-  *aResult = nullptr;
-  if (aOuter != nullptr) {
-      return NS_ERROR_NO_AGGREGATION;
-  }
-  nsCOMPtr<nsIFilePicker> picker;
-  
-    if (XRE_GetProcessType() == GeckoProcessType_Content)
-        picker = new nsFilePickerProxy();
-    else 
-        picker = new nsFilePicker;
-
-  return picker->QueryInterface(aIID, aResult);
-}
-
-
 #ifdef NS_PRINTING
 NS_GENERIC_FACTORY_CONSTRUCTOR(nsDeviceContextSpecQt)
 NS_GENERIC_FACTORY_CONSTRUCTOR_INIT(nsPrintOptionsQt, Init)
 NS_GENERIC_FACTORY_CONSTRUCTOR(nsPrinterEnumeratorQt)
 NS_GENERIC_FACTORY_CONSTRUCTOR_INIT(nsPrintSession, Init)
 NS_GENERIC_FACTORY_CONSTRUCTOR_INIT(nsPrintDialogServiceQt, Init)
 #endif
 
@@ -85,132 +70,89 @@ namespace mozilla {
 namespace widget {
 // This constructor should really be shared with all platforms.
 NS_GENERIC_FACTORY_CONSTRUCTOR_INIT(GfxInfo, Init)
 }
 }
 #endif
 
 
-static nsresult
-nsNativeThemeQtConstructor(nsISupports *aOuter, REFNSIID aIID,
-                            void **aResult)
-{
-    nsresult rv;
-    nsNativeThemeQt *inst;
-
-    if (gDisableNativeTheme)
-        return NS_ERROR_NO_INTERFACE;
-
-    *aResult = nullptr;
-    if (nullptr != aOuter)
-        return NS_ERROR_NO_AGGREGATION;
-
-    inst = new nsNativeThemeQt();
-    if (nullptr == inst)
-        return NS_ERROR_OUT_OF_MEMORY;
-
-    NS_ADDREF(inst);
-    rv = inst->QueryInterface(aIID, aResult);
-    NS_RELEASE(inst);
-
-    return rv;
-}
-
+NS_DEFINE_NAMED_CID(NS_APPSHELL_CID);
+NS_DEFINE_NAMED_CID(NS_BIDIKEYBOARD_CID);
 NS_DEFINE_NAMED_CID(NS_WINDOW_CID);
 NS_DEFINE_NAMED_CID(NS_CHILD_CID);
-NS_DEFINE_NAMED_CID(NS_APPSHELL_CID);
-NS_DEFINE_NAMED_CID(NS_FILEPICKER_CID);
-NS_DEFINE_NAMED_CID(NS_SOUND_CID);
+NS_DEFINE_NAMED_CID(NS_SCREENMANAGER_CID);
+NS_DEFINE_NAMED_CID(NS_HTMLFORMATCONVERTER_CID);
+NS_DEFINE_NAMED_CID(NS_IDLE_SERVICE_CID);
 NS_DEFINE_NAMED_CID(NS_TRANSFERABLE_CID);
 NS_DEFINE_NAMED_CID(NS_CLIPBOARD_CID);
 NS_DEFINE_NAMED_CID(NS_CLIPBOARDHELPER_CID);
-NS_DEFINE_NAMED_CID(NS_DRAGSERVICE_CID);
-NS_DEFINE_NAMED_CID(NS_HTMLFORMATCONVERTER_CID);
-NS_DEFINE_NAMED_CID(NS_BIDIKEYBOARD_CID);
-NS_DEFINE_NAMED_CID(NS_SCREENMANAGER_CID);
-NS_DEFINE_NAMED_CID(NS_THEMERENDERER_CID);
-NS_DEFINE_NAMED_CID(NS_IDLE_SERVICE_CID);
-NS_DEFINE_NAMED_CID(NS_POPUP_CID);
+#if defined(MOZ_X11)
+NS_DEFINE_NAMED_CID(NS_GFXINFO_CID);
+#endif
 #ifdef NS_PRINTING
 NS_DEFINE_NAMED_CID(NS_PRINTSETTINGSSERVICE_CID);
 NS_DEFINE_NAMED_CID(NS_PRINTER_ENUMERATOR_CID);
 NS_DEFINE_NAMED_CID(NS_PRINTSESSION_CID);
 NS_DEFINE_NAMED_CID(NS_DEVICE_CONTEXT_SPEC_CID);
 NS_DEFINE_NAMED_CID(NS_PRINTDIALOGSERVICE_CID);
 #endif
 
-#if defined(MOZ_X11)
-NS_DEFINE_NAMED_CID(NS_GFXINFO_CID);
-#endif
-
 static const mozilla::Module::CIDEntry kWidgetCIDs[] = {
-    { &kNS_WINDOW_CID, false, nullptr, nsWindowConstructor },
-    { &kNS_CHILD_CID, false, nullptr, nsChildWindowConstructor },
     { &kNS_APPSHELL_CID, false, nullptr, nsAppShellConstructor },
-    { &kNS_FILEPICKER_CID, false, nullptr, nsFilePickerConstructor },
-    { &kNS_SOUND_CID, false, nullptr, nsSoundConstructor },
-    { &kNS_TRANSFERABLE_CID, false, nullptr, nsTransferableConstructor },
+    { &kNS_BIDIKEYBOARD_CID, false, nullptr, nsBidiKeyboardConstructor },
+    { &kNS_CHILD_CID, false, nullptr, nsWindowConstructor },
     { &kNS_CLIPBOARD_CID, false, nullptr, nsClipboardConstructor },
     { &kNS_CLIPBOARDHELPER_CID, false, nullptr, nsClipboardHelperConstructor },
-    { &kNS_DRAGSERVICE_CID, false, nullptr, nsDragServiceConstructor },
     { &kNS_HTMLFORMATCONVERTER_CID, false, nullptr, nsHTMLFormatConverterConstructor },
-    { &kNS_BIDIKEYBOARD_CID, false, nullptr, nsBidiKeyboardConstructor },
+    { &kNS_IDLE_SERVICE_CID, false, nullptr, nsIdleServiceQtConstructor },
     { &kNS_SCREENMANAGER_CID, false, nullptr, nsScreenManagerQtConstructor },
-    { &kNS_THEMERENDERER_CID, false, nullptr, nsNativeThemeQtConstructor },
-    { &kNS_IDLE_SERVICE_CID, false, nullptr, nsIdleServiceQtConstructor },
-    { &kNS_POPUP_CID, false, nullptr, nsPopupWindowConstructor },
+    { &kNS_TRANSFERABLE_CID, false, nullptr, nsTransferableConstructor },
+    { &kNS_WINDOW_CID, false, nullptr, nsWindowConstructor },
+#if defined(MOZ_X11)
+    { &kNS_GFXINFO_CID, false, nullptr, mozilla::widget::GfxInfoConstructor },
+#endif
 #ifdef NS_PRINTING
-    { &kNS_PRINTSETTINGSSERVICE_CID, false, nullptr, nsPrintOptionsQtConstructor },
+    { &kNS_DEVICE_CONTEXT_SPEC_CID, false, nullptr, nsDeviceContextSpecQtConstructor },
+    { &kNS_PRINTDIALOGSERVICE_CID, false, nullptr, nsPrintDialogServiceQtConstructor },
     { &kNS_PRINTER_ENUMERATOR_CID, false, nullptr, nsPrinterEnumeratorQtConstructor },
     { &kNS_PRINTSESSION_CID, false, nullptr, nsPrintSessionConstructor },
-    { &kNS_DEVICE_CONTEXT_SPEC_CID, false, nullptr, nsDeviceContextSpecQtConstructor },
-    { &kNS_PRINTDIALOGSERVICE_CID, false, nullptr, nsPrintDialogServiceQtConstructor },
-#endif
-#if defined(MOZ_X11)
-    { &kNS_GFXINFO_CID, false, nullptr, mozilla::widget::GfxInfoConstructor },
+    { &kNS_PRINTSETTINGSSERVICE_CID, false, nullptr, nsPrintOptionsQtConstructor },
 #endif
     { nullptr }
 };
 
 static const mozilla::Module::ContractIDEntry kWidgetContracts[] = {
-    { "@mozilla.org/widget/window/qt;1", &kNS_WINDOW_CID },
-    { "@mozilla.org/widgets/child_window/qt;1", &kNS_CHILD_CID },
+    { "@mozilla.org/gfx/screenmanager;1", &kNS_SCREENMANAGER_CID },
     { "@mozilla.org/widget/appshell/qt;1", &kNS_APPSHELL_CID },
-    { "@mozilla.org/filepicker;1", &kNS_FILEPICKER_CID },
-    { "@mozilla.org/sound;1", &kNS_SOUND_CID },
-    { "@mozilla.org/widget/transferable;1", &kNS_TRANSFERABLE_CID },
+    { "@mozilla.org/widget/bidikeyboard;1", &kNS_BIDIKEYBOARD_CID },
     { "@mozilla.org/widget/clipboard;1", &kNS_CLIPBOARD_CID },
     { "@mozilla.org/widget/clipboardhelper;1", &kNS_CLIPBOARDHELPER_CID },
-    { "@mozilla.org/widget/dragservice;1", &kNS_DRAGSERVICE_CID },
     { "@mozilla.org/widget/htmlformatconverter;1", &kNS_HTMLFORMATCONVERTER_CID },
-    { "@mozilla.org/widget/bidikeyboard;1", &kNS_BIDIKEYBOARD_CID },
-    { "@mozilla.org/gfx/screenmanager;1", &kNS_SCREENMANAGER_CID },
-    { "@mozilla.org/chrome/chrome-native-theme;1", &kNS_THEMERENDERER_CID },
     { "@mozilla.org/widget/idleservice;1", &kNS_IDLE_SERVICE_CID },
-    { "@mozilla.org/widgets/popup_window/qt;1", &kNS_POPUP_CID },
+    { "@mozilla.org/widgets/child_window/qt;1", &kNS_CHILD_CID },
+    { "@mozilla.org/widgets/window/qt;1", &kNS_WINDOW_CID },
+    { "@mozilla.org/widget/transferable;1", &kNS_TRANSFERABLE_CID },
+#if defined(MOZ_X11)
+    { "@mozilla.org/gfx/info;1", &kNS_GFXINFO_CID },
+#endif
 #ifdef NS_PRINTING
-    { "@mozilla.org/gfx/printsettings-service;1", &kNS_PRINTSETTINGSSERVICE_CID },
+    { "@mozilla.org/gfx/devicecontextspec;1", &kNS_DEVICE_CONTEXT_SPEC_CID },
     { "@mozilla.org/gfx/printerenumerator;1", &kNS_PRINTER_ENUMERATOR_CID },
     { "@mozilla.org/gfx/printsession;1", &kNS_PRINTSESSION_CID },
-    { "@mozilla.org/gfx/devicecontextspec;1", &kNS_DEVICE_CONTEXT_SPEC_CID },
+    { "@mozilla.org/gfx/printsettings-service;1", &kNS_PRINTSETTINGSSERVICE_CID },
     { NS_PRINTDIALOGSERVICE_CONTRACTID, &kNS_PRINTDIALOGSERVICE_CID },
 #endif
-#if defined(MOZ_X11)
-    { "@mozilla.org/gfx/info;1", &kNS_GFXINFO_CID },
-#endif
     { nullptr }
 };
 
 static void
 nsWidgetQtModuleDtor()
 {
     nsLookAndFeel::Shutdown();
-    nsSound::Shutdown();
-    nsWindow::ReleaseGlobals();
     nsAppShellShutdown();
 }
 
 static const mozilla::Module kWidgetModule = {
     mozilla::Module::kVersion,
     kWidgetCIDs,
     kWidgetContracts,
     nullptr,
--- a/widget/qt/nsWindow.cpp
+++ b/widget/qt/nsWindow.cpp
@@ -6,324 +6,595 @@
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "mozilla/ArrayUtils.h"
 #include "mozilla/MiscEvents.h"
 #include "mozilla/MouseEvents.h"
 #include "mozilla/TextEvents.h"
 #include "mozilla/TouchEvents.h"
 
-#include <QApplication>
-#include <QDesktopWidget>
+#include <QGuiApplication>
 #include <QtGui/QCursor>
 #include <QIcon>
-#include <QGraphicsScene>
-#include <QGraphicsView>
-#include <QGraphicsSceneContextMenuEvent>
-#include <QGraphicsSceneDragDropEvent>
-#include <QGraphicsSceneMouseEvent>
-#include <QGraphicsSceneHoverEvent>
-#include <QGraphicsSceneWheelEvent>
-#include <QGraphicsSceneResizeEvent>
-#include <QStyleOptionGraphicsItem>
+#include <QMouseEvent>
+#include <QWheelEvent>
+#include <QResizeEvent>
 #include <QPaintEngine>
 #include <QMimeData>
-#include "mozqglwidgetwrapper.h"
+#include <QScreen>
 
 #include <QtCore/QDebug>
 #include <QtCore/QEvent>
 #include <QtCore/QVariant>
 #include <algorithm>
-#if (QT_VERSION >= QT_VERSION_CHECK(4, 6, 0))
-#include <QPinchGesture>
-#include <QGestureRecognizer>
-#include "mozSwipeGesture.h"
-static Qt::GestureType gSwipeGestureId = Qt::CustomGesture;
-
-// How many milliseconds mouseevents are blocked after receiving
-// multitouch.
-static const float GESTURES_BLOCK_MOUSE_FOR = 200;
-#ifdef MOZ_ENABLE_QTMOBILITY
-#include <QtSensors/QOrientationSensor>
-using namespace QtMobility;
-#endif // MOZ_ENABLE_QTMOBILITY
-#endif // QT version check 4.6
 
 #ifdef MOZ_X11
 #include <X11/Xlib.h>
+#include <X11/Xutil.h>
 #endif //MOZ_X11
 
 #include "nsXULAppAPI.h"
 
 #include "prlink.h"
 
 #include "nsWindow.h"
 #include "mozqwidget.h"
 
-#ifdef MOZ_ENABLE_QTMOBILITY
-#include "mozqorientationsensorfilter.h"
-#endif
-
 #include "nsIdleService.h"
 #include "nsRenderingContext.h"
 #include "nsIRollupListener.h"
 #include "nsWidgetsCID.h"
 #include "nsQtKeyUtils.h"
 #include "mozilla/Services.h"
 #include "mozilla/Preferences.h"
 #include "mozilla/Likely.h"
 #include "mozilla/layers/LayersTypes.h"
 #include "nsIWidgetListener.h"
+#include "ClientLayerManager.h"
+#include "BasicLayers.h"
 
 #include "nsIStringBundle.h"
 #include "nsGfxCIID.h"
 
 #include "imgIContainer.h"
 #include "nsGfxCIID.h"
 #include "nsIInterfaceRequestorUtils.h"
 #include "nsAutoPtr.h"
 
 #include "gfxQtPlatform.h"
-#ifdef MOZ_X11
-#include "gfxXlibSurface.h"
-#endif
-#include "gfxQPainterSurface.h"
 #include "gfxContext.h"
 #include "gfxImageSurface.h"
 
-#include "nsIDOMSimpleGestureEvent.h" //Gesture support
 #include "nsIDOMWheelEvent.h"
 
+#include "GLContext.h"
+
 #ifdef MOZ_X11
 #include "keysym2ucs.h"
 #endif
 
 #include "gfxUtils.h"
 #include "Layers.h"
 #include "GLContextProvider.h"
-#include "nsFastStartupQt.h"
-
-// If embedding clients want to create widget without real parent window
-// then nsIBaseWindow->Init() should have parent argument equal to PARENTLESS_WIDGET
-#define PARENTLESS_WIDGET (void*)0x13579
-
-#include "nsShmImage.h"
-extern "C" {
-#define PIXMAN_DONT_DEFINE_STDINT
-#include "pixman.h"
-}
 
 using namespace mozilla;
+using namespace mozilla::gl;
 using namespace mozilla::widget;
+using namespace mozilla::gfx;
+using namespace mozilla::layers;
 using mozilla::gl::GLContext;
 
-// Cached offscreen surface
-static nsRefPtr<gfxASurface> gBufferSurface;
-#ifdef MOZ_HAVE_SHMIMAGE
-// If we're using xshm rendering, mThebesSurface wraps gShmImage
-nsRefPtr<nsShmImage> gShmImage;
-#endif
-
-static int gBufferPixmapUsageCount = 0;
-static gfxIntSize gBufferMaxSize(0, 0);
-
-// initialization static functions 
-static nsresult    initialize_prefs        (void);
-
-static NS_DEFINE_IID(kCDragServiceCID,  NS_DRAGSERVICE_CID);
-
-#define NS_WINDOW_TITLE_MAX_LENGTH 4095
-
 #define kWindowPositionSlop 20
 
 // Qt
 static const int WHEEL_DELTA = 120;
 static bool gGlobalsInitialized = false;
-
-static bool
-is_mouse_in_window (MozQWidget* aWindow, double aMouseX, double aMouseY);
-
 static bool sAltGrModifier = false;
 
-#ifdef MOZ_ENABLE_QTMOBILITY
-static QOrientationSensor *gOrientation = nullptr;
-static MozQOrientationSensorFilter gOrientationFilter;
-#endif
-
-static bool
-isContextMenuKeyEvent(const QKeyEvent *qe)
-{
-    uint32_t kc = QtKeyCodeToDOMKeyCode(qe->key());
-    if (qe->modifiers() & (Qt::ControlModifier | Qt::AltModifier | Qt::MetaModifier))
-        return false;
-
-    bool isShift = qe->modifiers() & Qt::ShiftModifier;
-    return (kc == NS_VK_F10 && isShift) ||
-        (kc == NS_VK_CONTEXT_MENU && !isShift);
-}
-
-static void
-InitKeyEvent(WidgetKeyboardEvent &aEvent, QKeyEvent *aQEvent)
-{
-    aEvent.InitBasicModifiers(aQEvent->modifiers() & Qt::ControlModifier,
-                              aQEvent->modifiers() & Qt::AltModifier,
-                              aQEvent->modifiers() & Qt::ShiftModifier,
-                              aQEvent->modifiers() & Qt::MetaModifier);
-    aEvent.mIsRepeat =
-        (aEvent.message == NS_KEY_DOWN || aEvent.message == NS_KEY_PRESS) &&
-        aQEvent->isAutoRepeat();
-    aEvent.time = 0;
-
-    if (sAltGrModifier) {
-        aEvent.modifiers |= (MODIFIER_CONTROL | MODIFIER_ALT);
-    }
-
-    // The transformations above and in qt for the keyval are not invertible
-    // so link to the QKeyEvent (which will vanish soon after return from the
-    // event callback) to give plugins access to hardware_keycode and state.
-    // (An XEvent would be nice but the QKeyEvent is good enough.)
-    aEvent.pluginEvent = (void *)aQEvent;
-}
+static void find_first_visible_parent(QWindow* aItem, QWindow*& aVisibleItem);
+static bool is_mouse_in_window (MozQWidget* aWindow, double aMouseX, double aMouseY);
+static bool isContextMenuKeyEvent(const QKeyEvent *qe);
+static void InitKeyEvent(WidgetKeyboardEvent &aEvent, QKeyEvent *aQEvent);
 
 nsWindow::nsWindow()
 {
     LOG(("%s [%p]\n", __PRETTY_FUNCTION__, (void *)this));
 
     mIsTopLevel       = false;
     mIsDestroyed      = false;
     mIsShown          = false;
     mEnabled          = true;
     mWidget              = nullptr;
-    mIsVisible           = false;
+    mVisible           = false;
     mActivatePending     = false;
     mWindowType          = eWindowType_child;
     mSizeState           = nsSizeMode_Normal;
     mLastSizeMode        = nsSizeMode_Normal;
-    mPluginType          = PluginType_NONE;
     mQCursor             = Qt::ArrowCursor;
     mNeedsResize         = false;
     mNeedsMove           = false;
     mListenForResizes    = false;
     mNeedsShow           = false;
-    mGesturesCancelled   = false;
     mTimerStarted        = false;
-    mPinchEvent.needDispatch = false;
     mMoveEvent.needDispatch = false;
-    
+
     if (!gGlobalsInitialized) {
         gfxPlatform::GetPlatform();
         gGlobalsInitialized = true;
-
-        // It's OK if either of these fail, but it may not be one day.
-        initialize_prefs();
     }
 
     memset(mKeyDownFlags, 0, sizeof(mKeyDownFlags));
 
     mIsTransparent = false;
 
     mCursor = eCursor_standard;
-
-    gBufferPixmapUsageCount++;
-
-#if (QT_VERSION > QT_VERSION_CHECK(4,6,0))
-    if (gSwipeGestureId == Qt::CustomGesture) {
-        // QGestureRecognizer takes ownership
-        MozSwipeGestureRecognizer* swipeRecognizer = new MozSwipeGestureRecognizer;
-        gSwipeGestureId = QGestureRecognizer::registerRecognizer(swipeRecognizer);
-    }
-#endif
-}
-
-static inline gfxImageFormat
-_depth_to_gfximage_format(int32_t aDepth)
-{
-    switch (aDepth) {
-    case 32:
-        return gfxImageFormat::ARGB32;
-    case 24:
-        return gfxImageFormat::RGB24;
-    case 16:
-        return gfxImageFormat::RGB16_565;
-    default:
-        return gfxImageFormat::Unknown;
-    }
-}
-
-static inline QImage::Format
-_gfximage_to_qformat(gfxImageFormat aFormat)
-{
-    switch (aFormat) {
-    case gfxImageFormat::ARGB32:
-        return QImage::Format_ARGB32_Premultiplied;
-    case gfxImageFormat::RGB24:
-        return QImage::Format_ARGB32;
-    case gfxImageFormat::RGB16_565:
-        return QImage::Format_RGB16;
-    default:
-        return QImage::Format_Invalid;
-    }
-}
-
-static bool
-UpdateOffScreenBuffers(int aDepth, QSize aSize, QWidget* aWidget = nullptr)
-{
-    gfxIntSize size(aSize.width(), aSize.height());
-    if (gBufferSurface) {
-        if (gBufferMaxSize.width < size.width ||
-            gBufferMaxSize.height < size.height) {
-            gBufferSurface = nullptr;
-        } else
-            return true;
-    }
-
-    gBufferMaxSize.width = std::max(gBufferMaxSize.width, size.width);
-    gBufferMaxSize.height = std::max(gBufferMaxSize.height, size.height);
-
-    // Check if system depth has related gfxImage format
-    gfxImageFormat format =
-        _depth_to_gfximage_format(aDepth);
-
-    // Use fallback RGB24 format, Qt will do conversion for us
-    if (format == gfxImageFormat::Unknown)
-        format = gfxImageFormat::RGB24;
-
-#ifdef MOZ_HAVE_SHMIMAGE
-    if (aWidget) {
-        if (gfxPlatform::GetPlatform()->ScreenReferenceSurface()->GetType() ==
-            gfxSurfaceType::Image) {
-            gShmImage = nsShmImage::Create(gBufferMaxSize,
-                                           DefaultVisualOfScreen(gfxQtPlatform::GetXScreen(aWidget)),
-                                           aDepth);
-            gBufferSurface = gShmImage->AsSurface();
-            return true;
-        }
-    }
-#endif
-
-    gBufferSurface = gfxPlatform::GetPlatform()->
-        CreateOffscreenSurface(gBufferMaxSize.ToIntSize(),
-                               gfxASurface::ContentFromFormat(format));
-
-    return true;
 }
 
 nsWindow::~nsWindow()
 {
     LOG(("%s [%p]\n", __PRETTY_FUNCTION__, (void *)this));
 
     Destroy();
 }
 
-/* static */ void
-nsWindow::ReleaseGlobals()
+nsresult
+nsWindow::Create(nsIWidget        *aParent,
+                 nsNativeWidget    aNativeParent,
+                 const nsIntRect  &aRect,
+                 nsDeviceContext *aContext,
+                 nsWidgetInitData *aInitData)
+{
+    // only set the base parent if we're not going to be a dialog or a
+    // toplevel
+    nsIWidget *baseParent = aParent;
+
+    // initialize all the common bits of this class
+    BaseCreate(baseParent, aRect, aContext, aInitData);
+
+    mVisible = true;
+
+    // and do our common creation
+    mParent = (nsWindow *)aParent;
+
+    // save our bounds
+    mBounds = aRect;
+
+    // find native parent
+    MozQWidget *parent = nullptr;
+
+    if (aParent != nullptr) {
+        parent = static_cast<MozQWidget*>(aParent->GetNativeData(NS_NATIVE_WIDGET));
+    } else if (aNativeParent != nullptr) {
+        parent = static_cast<MozQWidget*>(aNativeParent);
+        if (parent && mParent == nullptr) {
+            mParent = parent->getReceiver();
+        }
+    }
+
+    LOG(("Create: nsWindow [%p] mWidget:[%p] parent:[%p], natPar:[%p] mParent:%p\n", (void *)this, (void*)mWidget, parent, aNativeParent, mParent));
+
+    // ok, create our QGraphicsWidget
+    mWidget = createQWidget(parent, aInitData);
+
+    if (!mWidget) {
+        return NS_ERROR_OUT_OF_MEMORY;
+    }
+
+
+    // resize so that everything is set to the right dimensions
+    Resize(mBounds.x, mBounds.y, mBounds.width, mBounds.height, false);
+
+    // check if we should listen for resizes
+    mListenForResizes = (aNativeParent ||
+                         (aInitData && aInitData->mListenForResizes));
+
+    return NS_OK;
+}
+
+MozQWidget*
+nsWindow::createQWidget(MozQWidget* parent,
+                        nsWidgetInitData* aInitData)
 {
+    const char *windowName = nullptr;
+    Qt::WindowFlags flags = Qt::Widget;
+
+    // ok, create our windows
+    switch (mWindowType) {
+    case eWindowType_dialog:
+        windowName = "topLevelDialog";
+        flags = Qt::Dialog;
+        break;
+    case eWindowType_popup:
+        windowName = "topLevelPopup";
+        flags = Qt::Popup;
+        break;
+    case eWindowType_toplevel:
+        windowName = "topLevelWindow";
+        flags = Qt::Window;
+        break;
+    case eWindowType_invisible:
+        windowName = "topLevelInvisible";
+        break;
+    case eWindowType_child:
+    case eWindowType_plugin:
+    default: // sheet
+        windowName = "paintArea";
+        break;
+    }
+
+    MozQWidget* widget = new MozQWidget(this, parent);
+    if (!widget) {
+        return nullptr;
+    }
+
+    widget->setObjectName(QString(windowName));
+    if (mWindowType == eWindowType_invisible) {
+        widget->setVisibility(QWindow::Hidden);
+    }
+    if (mWindowType == eWindowType_dialog) {
+        widget->setModality(Qt::WindowModal);
+    }
+
+    widget->create();
+
+    // create a QGraphicsView if this is a new toplevel window
+    LOG(("nsWindow::%s [%p] Created Window: %s, widget:%p, par:%p\n", __FUNCTION__, (void *)this, windowName, widget, parent));
+
+    return widget;
+}
+
+NS_IMETHODIMP
+nsWindow::Destroy(void)
+{
+    if (mIsDestroyed || !mWidget) {
+        return NS_OK;
+    }
+
+    LOG(("nsWindow::Destroy [%p]\n", (void *)this));
+    mIsDestroyed = true;
+
+    /** Need to clean our LayerManager up while still alive */
+    if (mLayerManager) {
+        mLayerManager->Destroy();
+    }
+    mLayerManager = nullptr;
+
+    // It is safe to call DestroyeCompositor several times (here and 
+    // in the parent class) since it will take effect only once.
+    // The reason we call it here is because on gtk platforms we need 
+    // to destroy the compositor before we destroy the gdk window (which
+    // destroys the the gl context attached to it).
+    DestroyCompositor();
+
+    ClearCachedResources();
+
+    nsIRollupListener* rollupListener = nsBaseWidget::GetActiveRollupListener();
+    if (rollupListener) {
+        nsCOMPtr<nsIWidget> rollupWidget = rollupListener->GetRollupWidget();
+        if (static_cast<nsIWidget *>(this) == rollupWidget) {
+            rollupListener->Rollup(0, nullptr, nullptr);
+        }
+    }
+
+    Show(false);
+
+    // walk the list of children and call destroy on them.  Have to be
+    // careful, though -- calling destroy on a kid may actually remove
+    // it from our child list, losing its sibling links.
+    for (nsIWidget* kid = mFirstChild; kid; ) {
+        nsIWidget* next = kid->GetNextSibling();
+        kid->Destroy();
+        kid = next;
+    }
+
+    // Destroy thebes surface now. Badness can happen if we destroy
+    // the surface after its X Window.
+    if (mWidget) {
+        mWidget->dropReceiver();
+
+        // Call deleteLater instead of delete; Qt still needs the object
+        // to be valid even after sending it a Close event.  We could
+        // also set WA_DeleteOnClose, but this gives us more control.
+        mWidget->deleteLater();
+    }
+    mWidget = nullptr;
+
+    OnDestroy();
+
+    return NS_OK;
+}
+
+NS_IMETHODIMP
+nsWindow::Show(bool aState)
+{
+    LOG(("nsWindow::Show [%p] state %d\n", (void *)this, aState));
+    if (aState == mIsShown) {
+        return NS_OK;
+    }
+
+    // Clear our cached resources when the window is hidden.
+    if (mIsShown && !aState) {
+        ClearCachedResources();
+    }
+
+    mIsShown = aState;
+
+    if ((aState && !AreBoundsSane()) || !mWidget) {
+        LOG(("\tbounds are insane or window hasn't been created yet\n"));
+        mNeedsShow = true;
+        return NS_OK;
+    }
+
+    if (aState) {
+        if (mNeedsMove) {
+            NativeResize(mBounds.x, mBounds.y, mBounds.width, mBounds.height,
+                         false);
+        } else if (mNeedsResize) {
+            NativeResize(mBounds.width, mBounds.height, false);
+        }
+    }
+    else {
+        // If someone is hiding this widget, clear any needing show flag.
+        mNeedsShow = false;
+    }
+
+    NativeShow(aState);
+
+    return NS_OK;
+}
+
+bool
+nsWindow::IsVisible() const
+{
+    return mIsShown;
 }
 
-NS_IMPL_ISUPPORTS_INHERITED1(nsWindow, nsBaseWidget, nsISupportsWeakReference)
+NS_IMETHODIMP
+nsWindow::ConstrainPosition(bool aAllowSlop, int32_t *aX, int32_t *aY)
+{
+    if (!mWidget) {
+        return NS_ERROR_FAILURE;
+    }
+
+    int32_t screenWidth  = qApp->primaryScreen()->size().width();
+    int32_t screenHeight = qApp->primaryScreen()->size().height();
+
+    if (aAllowSlop) {
+        if (*aX < (kWindowPositionSlop - mBounds.width))
+            *aX = kWindowPositionSlop - mBounds.width;
+        if (*aX > (screenWidth - kWindowPositionSlop))
+            *aX = screenWidth - kWindowPositionSlop;
+        if (*aY < (kWindowPositionSlop - mBounds.height))
+            *aY = kWindowPositionSlop - mBounds.height;
+        if (*aY > (screenHeight - kWindowPositionSlop))
+            *aY = screenHeight - kWindowPositionSlop;
+    } else {
+        if (*aX < 0)
+            *aX = 0;
+        if (*aX > (screenWidth - mBounds.width))
+            *aX = screenWidth - mBounds.width;
+        if (*aY < 0)
+            *aY = 0;
+        if (*aY > (screenHeight - mBounds.height))
+            *aY = screenHeight - mBounds.height;
+    }
+
+    return NS_OK;
+}
+
+NS_IMETHODIMP
+nsWindow::Move(double aX, double aY)
+{
+    LOG(("nsWindow::Move [%p] %f %f\n", (void *)this,
+         aX, aY));
+
+    int32_t x = NSToIntRound(aX);
+    int32_t y = NSToIntRound(aY);
+
+    if (mIsTopLevel) {
+        SetSizeMode(nsSizeMode_Normal);
+    }
+
+    if (x == mBounds.x && y == mBounds.y) {
+        return NS_OK;
+    }
+
+    mNeedsMove = false;
+
+    // update the bounds
+    QPoint pos(x, y);
+    if (mIsTopLevel) {
+        mWidget->setPosition(x, y);
+    }
+    else if (mWidget) {
+        // the position of the widget is set relative to the parent
+        // so we map the coordinates accordingly
+        pos = mWidget->mapToGlobal(pos);
+        mWidget->setPosition(pos);
+    }
+
+    mBounds.x = pos.x();
+    mBounds.y = pos.y();
+
+    NotifyRollupGeometryChange();
+    return NS_OK;
+}
+
+NS_IMETHODIMP
+nsWindow::Resize(double aWidth, double aHeight, bool aRepaint)
+{
+    mBounds.width = NSToIntRound(aWidth);
+    mBounds.height = NSToIntRound(aHeight);
+
+    if (!mWidget)
+        return NS_OK;
+
+    if (mIsShown) {
+        if (AreBoundsSane()) {
+            if (mIsTopLevel || mNeedsShow)
+                NativeResize(mBounds.x, mBounds.y,
+                             mBounds.width, mBounds.height, aRepaint);
+            else
+                NativeResize(mBounds.width, mBounds.height, aRepaint);
+
+            // Does it need to be shown because it was previously insane?
+            if (mNeedsShow) {
+                NativeShow(true);
+            }
+        }
+        else {
+            // If someone has set this so that the needs show flag is false
+            // and it needs to be hidden, update the flag and hide the
+            // window.  This flag will be cleared the next time someone
+            // hides the window or shows it.  It also prevents us from
+            // calling NativeShow(false) excessively on the window which
+            // causes unneeded X traffic.
+            if (!mNeedsShow) {
+                mNeedsShow = true;
+                NativeShow(false);
+            }
+        }
+    }
+    else if (AreBoundsSane() && mListenForResizes) {
+        // For widgets that we listen for resizes for (widgets created
+        // with native parents) we apparently _always_ have to resize.  I
+        // dunno why, but apparently we're lame like that.
+        NativeResize(mBounds.width, mBounds.height, aRepaint);
+    }
+    else {
+        mNeedsResize = true;
+    }
+
+    // synthesize a resize event if this isn't a toplevel
+    if (mIsTopLevel || mListenForResizes) {
+        nsEventStatus status;
+        DispatchResizeEvent(mBounds, status);
+    }
+
+    NotifyRollupGeometryChange();
+    return NS_OK;
+}
+
+NS_IMETHODIMP
+nsWindow::Resize(double aX, double aY, double aWidth, double aHeight,
+                 bool aRepaint)
+{
+    mBounds.x = NSToIntRound(aX);
+    mBounds.y = NSToIntRound(aY);
+    mBounds.width = NSToIntRound(aWidth);
+    mBounds.height = NSToIntRound(aHeight);
+
+    mPlaced = true;
+
+    if (!mWidget) {
+        return NS_OK;
+    }
+
+    // Has this widget been set to visible?
+    if (mIsShown) {
+        // Are the bounds sane?
+        if (AreBoundsSane()) {
+            // Yep?  Resize the window
+            NativeResize(mBounds.x, mBounds.y, mBounds.width, mBounds.height,
+                         aRepaint);
+            // Does it need to be shown because it was previously insane?
+            if (mNeedsShow)
+                NativeShow(true);
+        }
+        else {
+            // If someone has set this so that the needs show flag is false
+            // and it needs to be hidden, update the flag and hide the
+            // window.  This flag will be cleared the next time someone
+            // hides the window or shows it.  It also prevents us from
+            // calling NativeShow(false) excessively on the window which
+            // causes unneeded X traffic.
+            if (!mNeedsShow) {
+                mNeedsShow = true;
+                NativeShow(false);
+            }
+        }
+    }
+    // If the widget hasn't been shown, mark the widget as needing to be
+    // resized before it is shown
+    else if (AreBoundsSane() && mListenForResizes) {
+        // For widgets that we listen for resizes for (widgets created
+        // with native parents) we apparently _always_ have to resize.  I
+        // dunno why, but apparently we're lame like that.
+        NativeResize(mBounds.x, mBounds.y, mBounds.width, mBounds.height,
+                     aRepaint);
+    }
+    else {
+        mNeedsResize = true;
+        mNeedsMove = true;
+    }
+
+    if (mIsTopLevel || mListenForResizes) {
+        // synthesize a resize event
+        nsEventStatus status;
+        DispatchResizeEvent(mBounds, status);
+    }
+
+    if (aRepaint) {
+        mWidget->renderLater();
+    }
+
+    NotifyRollupGeometryChange();
+    return NS_OK;
+}
+
+NS_IMETHODIMP
+nsWindow::Enable(bool aState)
+{
+    mEnabled = aState;
+
+    return NS_OK;
+}
+
+bool
+nsWindow::IsEnabled() const
+{
+    return mEnabled;
+}
+
+NS_IMETHODIMP
+nsWindow::SetFocus(bool aRaise)
+{
+    // Make sure that our owning widget has focus.  If it doesn't try to
+    // grab it.  Note that we don't set our focus flag in this case.
+    LOGFOCUS(("  SetFocus [%p]\n", (void *)this));
+
+    if (!mWidget) {
+        return NS_ERROR_FAILURE;
+    }
+
+    if (mWidget->focusObject()) {
+        return NS_OK;
+    }
+
+    // Because QGraphicsItem cannot get the focus if they are
+    // invisible, we look up the chain, for the lowest visible
+    // parent and focus that one
+    QWindow* realFocusItem = nullptr;
+    find_first_visible_parent(mWidget, realFocusItem);
+
+    if (!realFocusItem || realFocusItem->focusObject()) {
+        return NS_OK;
+    }
+
+    if (aRaise && mWidget) {
+        // the raising has to happen on the view widget
+        mWidget->raise();
+    }
+
+    // XXXndeakin why is this here? It should dispatch only when the OS
+    // notifies us.
+    DispatchActivateEvent();
+
+    return NS_OK;
+}
 
 NS_IMETHODIMP
 nsWindow::ConfigureChildren(const nsTArray<nsIWidget::Configuration>& aConfigurations)
 {
     for (uint32_t i = 0; i < aConfigurations.Length(); ++i) {
         const Configuration& configuration = aConfigurations[i];
 
         nsWindow* w = static_cast<nsWindow*>(configuration.mChild);
@@ -337,837 +608,261 @@ nsWindow::ConfigureChildren(const nsTArr
         } else if (w->mBounds.TopLeft() != configuration.mBounds.TopLeft()) {
             w->Move(configuration.mBounds.x, configuration.mBounds.y);
         }
     }
     return NS_OK;
 }
 
 NS_IMETHODIMP
-nsWindow::Destroy(void)
+nsWindow::Invalidate(const nsIntRect &aRect)
 {
-    if (mIsDestroyed || !mWidget)
-        return NS_OK;
-
-    LOG(("nsWindow::Destroy [%p]\n", (void *)this));
-    mIsDestroyed = true;
-
-    if (gBufferPixmapUsageCount &&
-        --gBufferPixmapUsageCount == 0) {
+    LOGDRAW(("Invalidate (rect) [%p,%p]: %d %d %d %d\n", (void *)this,
+             (void*)mWidget,aRect.x, aRect.y, aRect.width, aRect.height));
 
-        gBufferSurface = nullptr;
-#ifdef MOZ_HAVE_SHMIMAGE
-        gShmImage = nullptr;
-#endif
-#ifdef MOZ_ENABLE_QTMOBILITY
-        if (gOrientation) {
-            gOrientation->removeFilter(&gOrientationFilter);
-            gOrientation->stop();
-            delete gOrientation;
-            gOrientation = nullptr;
-        }
-#endif
+    if (!mWidget) {
+        return NS_OK;
     }
 
-    /** Need to clean our LayerManager up while still alive */
-    if (mLayerManager) {
-        mLayerManager->Destroy();
-    }
-    mLayerManager = nullptr;
-
-    // It is safe to call DestroyeCompositor several times (here and 
-    // in the parent class) since it will take effect only once.
-    // The reason we call it here is because on gtk platforms we need 
-    // to destroy the compositor before we destroy the gdk window (which
-    // destroys the the gl context attached to it).
-    DestroyCompositor();
-
-    ClearCachedResources();
-
-    nsIRollupListener* rollupListener = nsBaseWidget::GetActiveRollupListener();
-    if (rollupListener) {
-        nsCOMPtr<nsIWidget> rollupWidget = rollupListener->GetRollupWidget();
-        if (static_cast<nsIWidget *>(this) == rollupWidget) {
-            rollupListener->Rollup(0, nullptr);
-        }
-    }
-
-    Show(false);
-
-    // walk the list of children and call destroy on them.  Have to be
-    // careful, though -- calling destroy on a kid may actually remove
-    // it from our child list, losing its sibling links.
-    for (nsIWidget* kid = mFirstChild; kid; ) {
-        nsIWidget* next = kid->GetNextSibling();
-        kid->Destroy();
-        kid = next;
-    }
-
-    // Destroy thebes surface now. Badness can happen if we destroy
-    // the surface after its X Window.
-    mThebesSurface = nullptr;
-
-    QWidget *view = nullptr;
-    QGraphicsScene *scene = nullptr;
-    if (mWidget) {
-        if (mIsTopLevel) {
-            view = GetViewWidget();
-            scene = mWidget->scene();
-        }
-
-        mWidget->dropReceiver();
-
-        // Call deleteLater instead of delete; Qt still needs the object
-        // to be valid even after sending it a Close event.  We could
-        // also set WA_DeleteOnClose, but this gives us more control.
-        mWidget->deleteLater();
-    }
-    mWidget = nullptr;
-
-    OnDestroy();
-
-    // tear down some infrastructure after all event handling is finished
-    delete scene;
-    delete view;
+    mWidget->renderLater();
 
     return NS_OK;
 }
 
-void
-nsWindow::ClearCachedResources()
+nsIntPoint
+nsWindow::WidgetToScreenOffset()
+{
+    NS_ENSURE_TRUE(mWidget, nsIntPoint(0,0));
+
+    QPoint origin(0, 0);
+    origin = mWidget->mapToGlobal(origin);
+
+    return nsIntPoint(origin.x(), origin.y());
+}
+
+void*
+nsWindow::GetNativeData(uint32_t aDataType)
 {
-    if (mLayerManager &&
-        mLayerManager->GetBackendType() == mozilla::layers::LayersBackend::LAYERS_BASIC) {
-        statimLayerManager->ClearCachedResources();
+    switch (aDataType) {
+    case NS_NATIVE_WINDOW:
+    case NS_NATIVE_WIDGET: {
+        return mWidget;
+    }
+    case NS_NATIVE_SHAREABLE_WINDOW: {
+        return mWidget ? (void*)mWidget->winId() : nullptr;
+    }
+    case NS_NATIVE_DISPLAY: {
+#ifdef MOZ_X11
+        return gfxQtPlatform::GetXDisplay(mWidget);
+#endif
+        break;
+    }
+    case NS_NATIVE_PLUGIN_PORT:
+    case NS_NATIVE_GRAPHIC:
+    case NS_NATIVE_SHELLWIDGET: {
+        break;
+    }
+    default:
+        NS_WARNING("nsWindow::GetNativeData called with bad value");
+        return nullptr;
     }
-    for (nsIWidget* kid = mFirstChild; kid; ) {
-        nsIWidget* next = kid->GetNextSibling();
-        static_cast<nsWindow*>(kid)->ClearCachedResources();
-        kid = next;
+    LOG(("nsWindow::%s [%p] aDataType:%i\n", __FUNCTION__, (void *)this, aDataType));
+    return nullptr;
+}
+
+NS_IMETHODIMP
+nsWindow::DispatchEvent(WidgetGUIEvent* aEvent, nsEventStatus& aStatus)
+{
+#ifdef DEBUG
+    debug_DumpEvent(stdout, aEvent->widget, aEvent,
+                    nsAutoCString("something"), 0);
+#endif
+
+    aStatus = nsEventStatus_eIgnore;
+
+    // send it to the standard callback
+    if (mWidgetListener) {
+        aStatus = mWidgetListener->HandleEvent(aEvent, mUseAttachedEvents);
+    }
+
+    return NS_OK;
+}
+
+NS_IMETHODIMP_(void)
+nsWindow::SetInputContext(const InputContext& aContext,
+                          const InputContextAction& aAction)
+{
+    NS_ENSURE_TRUE_VOID(mWidget);
+
+    // SetSoftwareKeyboardState uses mInputContext,
+    // so, before calling that, record aContext in mInputContext.
+    mInputContext = aContext;
+
+    switch (mInputContext.mIMEState.mEnabled) {
+        case IMEState::ENABLED:
+        case IMEState::PASSWORD:
+        case IMEState::PLUGIN:
+            SetSoftwareKeyboardState(true, aAction);
+            break;
+        default:
+            SetSoftwareKeyboardState(false, aAction);
+            break;
     }
 }
 
-NS_IMETHODIMP
-nsWindow::SetParent(nsIWidget *aNewParent)
+NS_IMETHODIMP_(InputContext)
+nsWindow::GetInputContext()
 {
-    NS_ENSURE_ARG_POINTER(aNewParent);
-    nsCOMPtr<nsIWidget> kungFuDeathGrip(this);
-    nsIWidget* parent = GetParent();
-    if (parent) {
-        parent->RemoveChild(this);
-    }
-    ReparentNativeWidget(aNewParent);
-    aNewParent->AddChild(this);
-    return NS_OK;
+    mInputContext.mIMEState.mOpen = IMEState::OPEN_STATE_NOT_SUPPORTED;
+    // Our qt widget looks like using only one context per process.
+    // However, it's better to set the context's pointer.
+    mInputContext.mNativeIMEContext = qApp->inputMethod();
+
+    return mInputContext;
 }
 
 NS_IMETHODIMP
 nsWindow::ReparentNativeWidget(nsIWidget *aNewParent)
 {
     NS_PRECONDITION(aNewParent, "");
 
     MozQWidget* newParent = static_cast<MozQWidget*>(aNewParent->GetNativeData(NS_NATIVE_WINDOW));
     NS_ASSERTION(newParent, "Parent widget has a null native window handle");
     if (mWidget) {
-        mWidget->setParentItem(newParent);
+        mWidget->setParent(newParent);
     }
     return NS_OK;
 }
 
 NS_IMETHODIMP
-nsWindow::SetModal(bool aModal)
-{
-    LOG(("nsWindow::SetModal [%p] %d, widget[%p]\n", (void *)this, aModal, mWidget));
-    if (mWidget)
-        mWidget->setModal(aModal);
-
-    return NS_OK;
-}
-
-bool
-nsWindow::IsVisible() const
-{
-    return mIsShown;
-}
-
-NS_IMETHODIMP
-nsWindow::ConstrainPosition(bool aAllowSlop, int32_t *aX, int32_t *aY)
+nsWindow::MakeFullScreen(bool aFullScreen)
 {
-    if (mWidget) {
-        int32_t screenWidth  = QApplication::desktop()->width();
-        int32_t screenHeight = QApplication::desktop()->height();
+    NS_ENSURE_TRUE(mWidget, NS_ERROR_FAILURE);
+
+    if (aFullScreen) {
+        if (mSizeMode != nsSizeMode_Fullscreen) {
+            mLastSizeMode = mSizeMode;
+        }
+
+        mSizeMode = nsSizeMode_Fullscreen;
+        mWidget->showFullScreen();
+    }
+    else {
+        mSizeMode = mLastSizeMode;
 
-        if (aAllowSlop) {
-            if (*aX < (kWindowPositionSlop - mBounds.width))
-                *aX = kWindowPositionSlop - mBounds.width;
-            if (*aX > (screenWidth - kWindowPositionSlop))
-                *aX = screenWidth - kWindowPositionSlop;
-            if (*aY < (kWindowPositionSlop - mBounds.height))
-                *aY = kWindowPositionSlop - mBounds.height;
-            if (*aY > (screenHeight - kWindowPositionSlop))
-                *aY = screenHeight - kWindowPositionSlop;
-        } else {
-            if (*aX < 0)
-                *aX = 0;
-            if (*aX > (screenWidth - mBounds.width))
-                *aX = screenWidth - mBounds.width;
-            if (*aY < 0)
-                *aY = 0;
-            if (*aY > (screenHeight - mBounds.height))
-                *aY = screenHeight - mBounds.height;
+        switch (mSizeMode) {
+        case nsSizeMode_Maximized:
+            mWidget->showMaximized();
+            break;
+        case nsSizeMode_Minimized:
+            mWidget->showMinimized();
+            break;
+        case nsSizeMode_Normal:
+            mWidget->showNormal();
+            break;
+        default:
+            mWidget->showNormal();
+            break;
         }
     }
 
-    return NS_OK;
-}
-
-NS_IMETHODIMP
-nsWindow::Move(double aX, double aY)
-{
-    LOG(("nsWindow::Move [%p] %f %f\n", (void *)this,
-         aX, aY));
-
-    int32_t x = NSToIntRound(aX);
-    int32_t y = NSToIntRound(aY);
-
-    if (mIsTopLevel) {
-        SetSizeMode(nsSizeMode_Normal);
-    }
-
-    if (x == mBounds.x && y == mBounds.y)
-        return NS_OK;
-
-    mNeedsMove = false;
-
-    // update the bounds
-    QPointF pos( x, y );
-    if (mIsTopLevel) {
-        QWidget *widget = GetViewWidget();
-        NS_ENSURE_TRUE(widget, NS_OK);
-        widget->move(x, y);
-    }
-    else if (mWidget) {
-        // the position of the widget is set relative to the parent
-        // so we map the coordinates accordingly
-        pos = mWidget->mapFromScene(pos);
-        pos = mWidget->mapToParent(pos);
-        mWidget->setPos(pos);
-    }
-
-    mBounds.x = pos.x();
-    mBounds.y = pos.y();
-
-    NotifyRollupGeometryChange();
-    return NS_OK;
-}
-
-NS_IMETHODIMP
-nsWindow::PlaceBehind(nsTopLevelWidgetZPlacement  aPlacement,
-                      nsIWidget                  *aWidget,
-                      bool                        aActivate)
-{
-    return NS_ERROR_NOT_IMPLEMENTED;
+    NS_ASSERTION(mLastSizeMode != nsSizeMode_Fullscreen,
+                 "mLastSizeMode should never be fullscreen");
+    return nsBaseWidget::MakeFullScreen(aFullScreen);
 }
 
-NS_IMETHODIMP
-nsWindow::SetSizeMode(int32_t aMode)
+LayerManager*
+nsWindow::GetLayerManager(PLayerTransactionChild* aShadowManager,
+                          LayersBackend aBackendHint,
+                          LayerManagerPersistence aPersistence,
+                          bool* aAllowRetaining)
 {
-    nsresult rv;
-
-    LOG(("nsWindow::SetSizeMode [%p] %d\n", (void *)this, aMode));
-    if (aMode != nsSizeMode_Minimized) {
-        GetViewWidget()->activateWindow();
-    }
-
-    // Save the requested state.
-    rv = nsBaseWidget::SetSizeMode(aMode);
-
-    // return if there's no shell or our current state is the same as
-    // the mode we were just set to.
-    if (!mWidget || mSizeState == mSizeMode) {
-        return rv;
+    if (!mLayerManager && eTransparencyTransparent == GetTransparencyMode()) {
+        mLayerManager = CreateBasicLayerManager();
     }
 
-    QWidget *widget = GetViewWidget();
-    NS_ENSURE_TRUE(widget, NS_ERROR_FAILURE);
+    return nsBaseWidget::GetLayerManager(aShadowManager, aBackendHint,
+                                         aPersistence, aAllowRetaining);
+}
 
-    switch (aMode) {
-    case nsSizeMode_Maximized:
-        widget->showMaximized();
-        break;
-    case nsSizeMode_Minimized:
-        widget->showMinimized();
-        break;
-    case nsSizeMode_Fullscreen:
-        widget->showFullScreen();
-        break;
-
-    default:
-        // nsSizeMode_Normal, really.
-        widget->showNormal();
-        break;
+void
+nsWindow::UserActivity()
+{
+    if (!mIdleService) {
+        mIdleService = do_GetService("@mozilla.org/widget/idleservice;1");
     }
 
-    mSizeState = mSizeMode;
-
-    return rv;
-}
-
-// Helper function to recursively find the first parent item that
-// is still visible (QGraphicsItem can be hidden even if they are
-// set to visible if one of their ancestors is invisible)
-static void find_first_visible_parent(QGraphicsItem* aItem, QGraphicsItem*& aVisibleItem)
-{
-    NS_ENSURE_TRUE_VOID(aItem);
-
-    aVisibleItem = nullptr;
-    QGraphicsItem* parItem = nullptr;
-    while (!aVisibleItem) {
-        if (aItem->isVisible())
-            aVisibleItem = aItem;
-        else {
-            parItem = aItem->parentItem();
-            if (parItem)
-                aItem = parItem;
-            else {
-                aItem->setVisible(true);
-                aVisibleItem = aItem;
-            }
-        }
+    if (mIdleService) {
+        mIdleService->ResetIdleTimeOut(0);
     }
 }
 
-NS_IMETHODIMP
-nsWindow::SetFocus(bool aRaise)
+uint32_t
+nsWindow::GetGLFrameBufferFormat()
 {
-    // Make sure that our owning widget has focus.  If it doesn't try to
-    // grab it.  Note that we don't set our focus flag in this case.
-    LOGFOCUS(("  SetFocus [%p]\n", (void *)this));
-
-    if (!mWidget)
-        return NS_ERROR_FAILURE;
-
-    if (mWidget->hasFocus())
-        return NS_OK;
-
-    // Because QGraphicsItem cannot get the focus if they are
-    // invisible, we look up the chain, for the lowest visible
-    // parent and focus that one
-    QGraphicsItem* realFocusItem = nullptr;
-    find_first_visible_parent(mWidget, realFocusItem);
-
-    if (!realFocusItem || realFocusItem->hasFocus())
-        return NS_OK;
-
-    if (aRaise) {
-        // the raising has to happen on the view widget
-        QWidget *widget = GetViewWidget();
-        if (widget)
-            widget->raise();
-        realFocusItem->setFocus(Qt::ActiveWindowFocusReason);
+    if (mLayerManager &&
+        mLayerManager->GetBackendType() == mozilla::layers::LayersBackend::LAYERS_OPENGL) {
+        return LOCAL_GL_RGB;
     }
-    else
-        realFocusItem->setFocus(Qt::OtherFocusReason);
-
-    // XXXndeakin why is this here? It should dispatch only when the OS
-    // notifies us.
-    DispatchActivateEvent();
-
-    return NS_OK;
-}
-
-NS_IMETHODIMP
-nsWindow::GetScreenBounds(nsIntRect &aRect)
-{
-    aRect = nsIntRect(nsIntPoint(0, 0), mBounds.Size());
-    if (mIsTopLevel) {
-        QWidget *widget = GetViewWidget();
-        NS_ENSURE_TRUE(widget, NS_OK);
-        QPoint pos = widget->pos();
-        aRect.MoveTo(pos.x(), pos.y());
-    }
-    else {
-        aRect.MoveTo(WidgetToScreenOffset());
-    }
-    LOG(("GetScreenBounds %d %d | %d %d | %d %d\n",
-         aRect.x, aRect.y,
-         mBounds.width, mBounds.height,
-         aRect.width, aRect.height));
-    return NS_OK;
-}
-
-NS_IMETHODIMP
-nsWindow::SetForegroundColor(const nscolor &aColor)
-{
-    return NS_ERROR_NOT_IMPLEMENTED;
-}
-
-NS_IMETHODIMP
-nsWindow::SetBackgroundColor(const nscolor &aColor)
-{
-    return NS_ERROR_NOT_IMPLEMENTED;
+    return LOCAL_GL_NONE;
 }
 
 NS_IMETHODIMP
 nsWindow::SetCursor(nsCursor aCursor)
 {
-    if (mCursor == aCursor)
+    if (mCursor == aCursor) {
         return NS_OK;
+    }
 
     mCursor = aCursor;
-    if (mWidget)
+    if (mWidget) {
         mWidget->SetCursor(mCursor);
-    return NS_OK;
-}
-
-NS_IMETHODIMP
-nsWindow::SetCursor(imgIContainer* aCursor,
-                    uint32_t aHotspotX, uint32_t aHotspotY)
-{
-    return NS_ERROR_NOT_AVAILABLE;
-}
-
-NS_IMETHODIMP
-nsWindow::Invalidate(const nsIntRect &aRect)
-{
-    LOGDRAW(("Invalidate (rect) [%p,%p]: %d %d %d %d\n", (void *)this,
-             (void*)mWidget,aRect.x, aRect.y, aRect.width, aRect.height));
-
-    if (!mWidget)
-        return NS_OK;
-
-    mDirtyScrollArea = mDirtyScrollArea.united(QRect(aRect.x, aRect.y, aRect.width, aRect.height));
-
-    mWidget->update(aRect.x, aRect.y, aRect.width, aRect.height);
-
+    }
     return NS_OK;
 }
 
-// Returns the graphics view widget for this nsWindow by iterating
-// the chain of parents until a toplevel window with a view/scene is found.
-// (This function always returns something or asserts if the precondition
-// is not met)
-QWidget* nsWindow::GetViewWidget()
-{
-    NS_ASSERTION(mWidget, "Calling GetViewWidget without mWidget created");
-    if (!mWidget || !mWidget->scene() || !mWidget->scene()->views().size())
-        return nullptr;
-
-    NS_ASSERTION(mWidget->scene()->views().size() == 1, "Not exactly one view for our scene!");
-    return mWidget->scene()->views()[0];
-}
-
-void*
-nsWindow::GetNativeData(uint32_t aDataType)
-{
-    switch (aDataType) {
-    case NS_NATIVE_WINDOW:
-    case NS_NATIVE_WIDGET: {
-        if (!mWidget)
-            return nullptr;
-
-        return mWidget;
-        break;
-    }
-
-    case NS_NATIVE_PLUGIN_PORT:
-        return SetupPluginPort();
-        break;
-
-    case NS_NATIVE_DISPLAY:
-        {
-#ifdef MOZ_X11
-            return gfxQtPlatform::GetXDisplay(GetViewWidget());
-#else
-            return nullptr;
-#endif
-        }
-        break;
-
-    case NS_NATIVE_GRAPHIC: {
-        return nullptr;
-        break;
-    }
-
-    case NS_NATIVE_SHELLWIDGET: {
-        QWidget* widget = nullptr;
-        if (mWidget && mWidget->scene())
-            widget = mWidget->scene()->views()[0]->viewport();
-        return (void *) widget;
-    }
-
-    case NS_NATIVE_SHAREABLE_WINDOW: {
-        QWidget *widget = GetViewWidget();
-        return widget ? (void*)widget->winId() : nullptr;
-    }
-
-    default:
-        NS_WARNING("nsWindow::GetNativeData called with bad value");
-        return nullptr;
-    }
-}
-
 NS_IMETHODIMP
 nsWindow::SetTitle(const nsAString& aTitle)
 {
-    QString qStr(QString::fromUtf16(aTitle.BeginReading(), aTitle.Length()));
-    if (mIsTopLevel) {
-        QWidget *widget = GetViewWidget();
-        if (widget)
-            widget->setWindowTitle(qStr);
-    }
-    else if (mWidget)
-        mWidget->setWindowTitle(qStr);
-
-    return NS_OK;
-}
-
-NS_IMETHODIMP
-nsWindow::SetIcon(const nsAString& aIconSpec)
-{
-    if (!mWidget)
-        return NS_OK;
-
-    nsCOMPtr<nsIFile> iconFile;
-    nsAutoCString path;
-    nsTArray<nsCString> iconList;
-
-    // Look for icons with the following suffixes appended to the base name.
-    // The last two entries (for the old XPM format) will be ignored unless
-    // no icons are found using the other suffixes. XPM icons are depricated.
-
-    const char extensions[6][7] = { ".png", "16.png", "32.png", "48.png",
-                                    ".xpm", "16.xpm" };
-
-    for (uint32_t i = 0; i < ArrayLength(extensions); i++) {
-        // Don't bother looking for XPM versions if we found a PNG.
-        if (i == ArrayLength(extensions) - 2 && iconList.Length())
-            break;
-
-        nsAutoString extension;
-        extension.AppendASCII(extensions[i]);
+    QString qStr(QString::fromUtf16((const ushort*)aTitle.BeginReading(), aTitle.Length()));
 
-        ResolveIconName(aIconSpec, extension, getter_AddRefs(iconFile));
-        if (iconFile) {
-            iconFile->GetNativePath(path);
-            iconList.AppendElement(path);
-        }
-    }
-
-    // leave the default icon intact if no matching icons were found
-    if (iconList.Length() == 0)
-        return NS_OK;
-
-    return SetWindowIconList(iconList);
-}
-
-nsIntPoint
-nsWindow::WidgetToScreenOffset()
-{
-    NS_ENSURE_TRUE(mWidget, nsIntPoint(0,0));
-
-    QPointF origin(0, 0);
-    origin = mWidget->mapToScene(origin);
-
-    return nsIntPoint(origin.x(), origin.y());
-}
-
-NS_IMETHODIMP
-nsWindow::EnableDragDrop(bool aEnable)
-{
-    mWidget->setAcceptDrops(aEnable);
-    return NS_OK;
-}
-
-NS_IMETHODIMP
-nsWindow::CaptureMouse(bool aCapture)
-{
-    LOG(("CaptureMouse %p\n", (void *)this));
-
-    if (!mWidget)
-        return NS_OK;
-
-    QWidget *widget = GetViewWidget();
-    NS_ENSURE_TRUE(widget, NS_ERROR_FAILURE);
-
-    if (aCapture)
-        widget->grabMouse();
-    else
-        widget->releaseMouse();
+    mWidget->setTitle(qStr);
 
     return NS_OK;
 }
 
-NS_IMETHODIMP
-nsWindow::CaptureRollupEvents(nsIRollupListener *aListener,
-                              bool               aDoCapture)
-{
-    if (!mWidget)
-        return NS_OK;
-
-    LOG(("CaptureRollupEvents %p\n", (void *)this));
-
-    gRollupListener = aDoCapture ? aListener : nullptr;
-    return NS_OK;
-}
-
-bool
-nsWindow::CheckForRollup(double aMouseX, double aMouseY,
-                         bool aIsWheel)
-{
-    nsIRollupListener* rollupListener = GetActiveRollupListener();
-    nsCOMPtr<nsIWidget> rollupWidget;
-    if (rollupListener) {
-        rollupWidget = rollupListener->GetRollupWidget();
-    }
-    if (!rollupWidget) {
-        nsBaseWidget::gRollupListener = nullptr;
-        return false;
-    }
+// EVENTS
 
-    bool retVal = false;
-    MozQWidget *currentPopup =
-        (MozQWidget *)rollupWidget->GetNativeData(NS_NATIVE_WINDOW);
-    if (!is_mouse_in_window(currentPopup, aMouseX, aMouseY)) {
-        bool rollup = true;
-        if (aIsWheel) {
-            rollup = rollupListener->ShouldRollupOnMouseWheelEvent();
-            retVal = true;
-        }
-        // if we're dealing with menus, we probably have submenus and
-        // we don't want to rollup if the clickis in a parent menu of
-        // the current submenu
-        uint32_t popupsToRollup = UINT32_MAX;
-        if (rollupListener) {
-            nsAutoTArray<nsIWidget*, 5> widgetChain;
-            uint32_t sameTypeCount = rollupListener->GetSubmenuWidgetChain(&widgetChain);
-            for (uint32_t i=0; i<widgetChain.Length(); ++i) {
-                nsIWidget* widget =  widgetChain[i];
-                MozQWidget* currWindow =
-                    (MozQWidget*) widget->GetNativeData(NS_NATIVE_WINDOW);
-                if (is_mouse_in_window(currWindow, aMouseX, aMouseY)) {
-                  if (i < sameTypeCount) {
-                    rollup = false;
-                  }
-                  else {
-                    popupsToRollup = sameTypeCount;
-                  }
-                  break;
-                }
-            } // foreach parent menu widget
-        } // if rollup listener knows about menus
-
-        // if we've determined that we should still rollup, do it.
-        if (rollup) {
-            retVal = rollupListener->Rollup(popupsToRollup, nullptr);
-        }
-    }
-
-    return retVal;
-}
-
-/* static */
-bool
-is_mouse_in_window (MozQWidget* aWindow, double aMouseX, double aMouseY)
+void
+nsWindow::OnPaint()
 {
-    return aWindow->geometry().contains( aMouseX, aMouseY );
-}
-
-NS_IMETHODIMP
-nsWindow::GetAttention(int32_t aCycleCount)
-{
-    LOG(("nsWindow::GetAttention [%p]\n", (void *)this));
-    return NS_ERROR_NOT_IMPLEMENTED;
-}
-
-#ifdef MOZ_X11
-static already_AddRefed<gfxASurface>
-GetSurfaceForQWidget(QWidget* aDrawable)
-{
-    nsRefPtr<gfxASurface> result =
-        new gfxXlibSurface(gfxQtPlatform::GetXDisplay(aDrawable),
-                           aDrawable->winId(),
-                           DefaultVisualOfScreen(gfxQtPlatform::GetXScreen(aDrawable)),
-                           gfxIntSize(aDrawable->size().width(),
-                           aDrawable->size().height()));
-    return result.forget();
-}
-#endif
-
-bool
-nsWindow::DoPaint(QPainter* aPainter, const QStyleOptionGraphicsItem* aOption, QWidget* aWidget)
-{
-    if (mIsDestroyed) {
-        LOG(("Expose event on destroyed window [%p] window %p\n",
-             (void *)this, mWidget));
-        return false;
-    }
-
-    // Call WillPaintWindow to allow scripts etc. to run before we paint
-    {
-        if (mWidgetListener)
-            mWidgetListener->WillPaintWindow(this);
+    LOGDRAW(("nsWindow::%s [%p]\n", __FUNCTION__, (void *)this));
+    nsIWidgetListener* listener =
+        mAttachedWidgetListener ? mAttachedWidgetListener : mWidgetListener;
+    if (!listener) {
+        return;
     }
 
-    if (!mWidget)
-        return false;
-
-    QRectF r;
-    if (aOption)
-        r = aOption->exposedRect;
-    else
-        r = mWidget->boundingRect();
-
-    if (r.isEmpty())
-        return nsEventStatus_eIgnore;
-
-    if (!mDirtyScrollArea.isEmpty())
-        mDirtyScrollArea = QRegion();
-
-    bool painted = false;
-    nsIntRect rect(r.x(), r.y(), r.width(), r.height());
-
-    nsFastStartup* startup = nsFastStartup::GetSingleton();
-    if (startup) {
-        startup->RemoveFakeLayout();
-    }
-
-    gfxQtPlatform::RenderMode renderMode = gfxQtPlatform::GetPlatform()->GetRenderMode();
-    int depth = aPainter->device()->depth();
-
-    nsRefPtr<gfxASurface> targetSurface = nullptr;
-    if (renderMode == gfxQtPlatform::RENDER_BUFFERED) {
-        // Prepare offscreen buffers iamge or xlib, depends from paintEngineType
-        if (!UpdateOffScreenBuffers(depth, QSize(r.width(), r.height())))
-            return false;
-
-        targetSurface = gBufferSurface;
+    listener->WillPaintWindow(this);
 
-#ifdef CAIRO_HAS_QT_SURFACE
-    } else if (renderMode == gfxQtPlatform::RENDER_QPAINTER) {
-        targetSurface = new gfxQPainterSurface(aPainter);
-#endif
-    } else if (renderMode == gfxQtPlatform::RENDER_DIRECT) {
-        if (!UpdateOffScreenBuffers(depth, aWidget->size(), aWidget)) {
-            return false;
+    switch (GetLayerManager()->GetBackendType()) {
+        case mozilla::layers::LayersBackend::LAYERS_CLIENT: {
+            nsIntRegion region(nsIntRect(0, 0, mWidget->width(), mWidget->height()));
+            listener->PaintWindow(this, region);
+            break;
         }
-        targetSurface = gBufferSurface;
-    }
-
-    if (MOZ_UNLIKELY(!targetSurface))
-        return false;
-
-    nsRefPtr<gfxContext> ctx = new gfxContext(targetSurface);
-
-    // We will paint to 0, 0 position in offscrenn buffer
-    if (renderMode == gfxQtPlatform::RENDER_BUFFERED) {
-        ctx->Translate(gfxPoint(-r.x(), -r.y()));
-    }
-    else if (renderMode == gfxQtPlatform::RENDER_DIRECT) {
-      gfxMatrix matr;
-      matr.Translate(gfxPoint(aPainter->transform().dx(), aPainter->transform().dy()));
-#ifdef MOZ_ENABLE_QTMOBILITY
-         // This is needed for rotate transformation on MeeGo
-         // This will work very slow if pixman does not handle rotation very well
-         matr.Rotate((M_PI/180) * gOrientationFilter.GetWindowRotationAngle());
-         NS_ASSERTION(PIXMAN_VERSION > PIXMAN_VERSION_ENCODE(0, 21, 2) ||
-                      !gOrientationFilter.GetWindowRotationAngle(),
-                      "Old pixman and rotate transform, it is going to be slow");
-#endif //MOZ_ENABLE_QTMOBILITY
-
-      ctx->SetMatrix(matr);
+        default:
+            NS_ERROR("Invalid layer manager");
     }
 
-    {
-        AutoLayerManagerSetup
-            setupLayerManager(this, ctx, mozilla::layers::BufferMode::BUFFER_NONE);
-        if (mWidgetListener) {
-          nsIntRegion region(rect);
-          painted = mWidgetListener->PaintWindow(this, region);
-        }
-    }
-
-    // DispatchEvent can Destroy us (bug 378273), avoid doing any paint
-    // operations below if that happened - it will lead to XError and exit().
-    if (MOZ_UNLIKELY(mIsDestroyed))
-        return painted;
-
-    if (!painted)
-        return false;
-
-    LOGDRAW(("[%p] draw done\n", this));
-
-    // Handle buffered painting mode
-    if (renderMode == gfxQtPlatform::RENDER_BUFFERED) {
-#if defined(MOZ_X11) && defined(Q_WS_X11)
-        if (gBufferSurface->GetType() == gfxSurfaceType::Xlib) {
-            // Paint offscreen pixmap to QPainter
-            static QPixmap gBufferPixmap;
-            Drawable draw = static_cast<gfxXlibSurface*>(gBufferSurface.get())->XDrawable();
-            if (gBufferPixmap.handle() != draw)
-                gBufferPixmap = QPixmap::fromX11Pixmap(draw, QPixmap::ExplicitlyShared);
-            XSync(static_cast<gfxXlibSurface*>(gBufferSurface.get())->XDisplay(), False);
-            aPainter->drawPixmap(QPoint(rect.x, rect.y), gBufferPixmap,
-                                 QRect(0, 0, rect.width, rect.height));
-
-        } else
-#endif
-        if (gBufferSurface->GetType() == gfxSurfaceType::Image) {
-            // in raster mode we can just wrap gBufferImage as QImage and paint directly
-            gfxImageSurface *imgs = static_cast<gfxImageSurface*>(gBufferSurface.get());
-            QImage img(imgs->Data(),
-                       imgs->Width(),
-                       imgs->Height(),
-                       imgs->Stride(),
-                       _gfximage_to_qformat(imgs->Format()));
-            aPainter->drawImage(QPoint(rect.x, rect.y), img,
-                                QRect(0, 0, rect.width, rect.height));
-        }
-    } else if (renderMode == gfxQtPlatform::RENDER_DIRECT) {
-        QRect trans = aPainter->transform().mapRect(r).toRect();
-#ifdef MOZ_X11
-        if (gBufferSurface->GetType() == gfxSurfaceType::Xlib) {
-            nsRefPtr<gfxASurface> widgetSurface = GetSurfaceForQWidget(aWidget);
-            nsRefPtr<gfxContext> ctx = new gfxContext(widgetSurface);
-            ctx->SetSource(gBufferSurface);
-            ctx->Rectangle(gfxRect(trans.x(), trans.y(), trans.width(), trans.height()), true);
-            ctx->Clip();
-            ctx->Fill();
-        } else
-#endif
-        if (gBufferSurface->GetType() == gfxSurfaceType::Image) {
-#ifdef MOZ_HAVE_SHMIMAGE
-            if (gShmImage) {
-                gShmImage->Put(aWidget, trans);
-            } else
-#endif
-            {
-                // Qt should take care about optimized rendering on QImage into painter device (gl/fb/image et.c.)
-                gfxImageSurface *imgs = static_cast<gfxImageSurface*>(gBufferSurface.get());
-                QImage img(imgs->Data(),
-                           imgs->Width(),
-                           imgs->Height(),
-                           imgs->Stride(),
-                          _gfximage_to_qformat(imgs->Format()));
-                aPainter->drawImage(trans, img, trans);
-            }
-        }
-    }
-
-    ctx = nullptr;
-    targetSurface = nullptr;
-    if (mWidgetListener)
-      mWidgetListener->DidPaintWindow();
-
-    // check the return value!
-    return painted;
+    listener->DidPaintWindow();
 }
 
 nsEventStatus
-nsWindow::OnMoveEvent(QGraphicsSceneHoverEvent *aEvent)
+nsWindow::moveEvent(QMoveEvent* aEvent)
 {
     LOG(("configure event [%p] %d %d\n", (void *)this,
         aEvent->pos().x(),  aEvent->pos().y()));
 
     // can we shortcut?
     if (!mWidget || !mWidgetListener)
         return nsEventStatus_eIgnore;
 
@@ -1177,128 +872,59 @@ nsWindow::OnMoveEvent(QGraphicsSceneHove
         return nsEventStatus_eIgnore;
     }
 
     bool moved = mWidgetListener->WindowMoved(this, aEvent->pos().x(), aEvent->pos().y());
     return moved ? nsEventStatus_eConsumeNoDefault : nsEventStatus_eIgnore;
 }
 
 nsEventStatus
-nsWindow::OnResizeEvent(QGraphicsSceneResizeEvent *aEvent)
+nsWindow::resizeEvent(QResizeEvent* aEvent)
 {
     nsIntRect rect;
 
     // Generate XPFE resize event
     GetBounds(rect);
 
-    rect.width = aEvent->newSize().width();
-    rect.height = aEvent->newSize().height();
+    rect.width = aEvent->size().width();
+    rect.height = aEvent->size().height();
 
     mBounds.width = rect.width;
     mBounds.height = rect.height;
 
     nsEventStatus status;
     DispatchResizeEvent(rect, status);
     return status;
 }
 
 nsEventStatus
-nsWindow::OnCloseEvent(QCloseEvent *aEvent)
-{
-    if (!mWidgetListener)
-        return nsEventStatus_eIgnore;
-    mWidgetListener->RequestWindowClose(this);
-    return nsEventStatus_eConsumeNoDefault;
-}
-
-nsEventStatus
-nsWindow::OnEnterNotifyEvent(QGraphicsSceneHoverEvent *aEvent)
-{
-    WidgetMouseEvent event(true, NS_MOUSE_ENTER, this, WidgetMouseEvent::eReal);
-
-    event.refPoint.x = nscoord(aEvent->pos().x());
-    event.refPoint.y = nscoord(aEvent->pos().y());
-
-    LOG(("OnEnterNotify: %p\n", (void *)this));
-
-    return DispatchEvent(&event);
-}
-
-nsEventStatus
-nsWindow::OnLeaveNotifyEvent(QGraphicsSceneHoverEvent *aEvent)
-{
-    WidgetMouseEvent event(true, NS_MOUSE_EXIT, this, WidgetMouseEvent::eReal);
-
-    event.refPoint.x = nscoord(aEvent->pos().x());
-    event.refPoint.y = nscoord(aEvent->pos().y());
-
-    LOG(("OnLeaveNotify: %p\n", (void *)this));
-
-    return DispatchEvent(&event);
-}
-
-// Block the mouse events if user was recently executing gestures;
-// otherwise there will be also some panning during/after gesture
-#if (QT_VERSION >= QT_VERSION_CHECK(4, 6, 0))
-#define CHECK_MOUSE_BLOCKED { \
-if (mLastMultiTouchTime.isValid()) { \
-    if (mLastMultiTouchTime.elapsed() < GESTURES_BLOCK_MOUSE_FOR) \
-        return nsEventStatus_eIgnore; \
-    else \
-        mLastMultiTouchTime = QTime(); \
-   } \
-}
-#else
-define CHECK_MOUSE_BLOCKED {}
-#endif
-
-nsEventStatus
-nsWindow::OnMotionNotifyEvent(QPointF aPos,  Qt::KeyboardModifiers aModifiers)
+nsWindow::mouseMoveEvent(QMouseEvent* aEvent)
 {
     UserActivity();
 
-    CHECK_MOUSE_BLOCKED
-
-    mMoveEvent.pos = aPos;
-    mMoveEvent.modifiers = aModifiers;
+    mMoveEvent.pos = aEvent->pos();
+    mMoveEvent.modifiers = aEvent->modifiers();
     mMoveEvent.needDispatch = true;
     DispatchMotionToMainThread();
 
     return nsEventStatus_eIgnore;
 }
 
-void
-nsWindow::InitButtonEvent(WidgetMouseEvent& aMoveEvent,
-                          QGraphicsSceneMouseEvent* aEvent,
-                          int aClickCount)
-{
-    aMoveEvent.refPoint.x = nscoord(aEvent->pos().x());
-    aMoveEvent.refPoint.y = nscoord(aEvent->pos().y());
-
-    aMoveEvent.InitBasicModifiers(aEvent->modifiers() & Qt::ControlModifier,
-                                  aEvent->modifiers() & Qt::AltModifier,
-                                  aEvent->modifiers() & Qt::ShiftModifier,
-                                  aEvent->modifiers() & Qt::MetaModifier);
-    aMoveEvent.clickCount      = aClickCount;
-}
-
 nsEventStatus
-nsWindow::OnButtonPressEvent(QGraphicsSceneMouseEvent *aEvent)
+nsWindow::mousePressEvent(QMouseEvent* aEvent)
 {
     // The user has done something.
     UserActivity();
 
-    CHECK_MOUSE_BLOCKED
-
-    QPointF pos = aEvent->pos();
+    QPoint pos = aEvent->pos();
 
     // we check against the widgets geometry, so use parent coordinates
     // for the check
     if (mWidget)
-        pos = mWidget->mapToParent(pos);
+        pos = mWidget->mapToGlobal(pos);
 
     if (CheckForRollup( pos.x(), pos.y(), false))
         return nsEventStatus_eIgnore;
 
     uint16_t      domButton;
     switch (aEvent->button()) {
     case Qt::MidButton:
         domButton = WidgetMouseEvent::eMiddleButton;
@@ -1328,21 +954,18 @@ nsWindow::OnButtonPressEvent(QGraphicsSc
         InitButtonEvent(contextMenuEvent, aEvent, 1);
         DispatchEvent(&contextMenuEvent, status);
     }
 
     return status;
 }
 
 nsEventStatus
-nsWindow::OnButtonReleaseEvent(QGraphicsSceneMouseEvent *aEvent)
+nsWindow::mouseReleaseEvent(QMouseEvent* aEvent)
 {
-    UserActivity();
-    CHECK_MOUSE_BLOCKED
-
     // The user has done something.
     UserActivity();
 
     uint16_t domButton;
 
     switch (aEvent->button()) {
     case Qt::MidButton:
         domButton = WidgetMouseEvent::eMiddleButton;
@@ -1363,17 +986,17 @@ nsWindow::OnButtonReleaseEvent(QGraphics
     InitButtonEvent(event, aEvent, 1);
 
     nsEventStatus status = DispatchEvent(&event);
 
     return status;
 }
 
 nsEventStatus
-nsWindow::OnMouseDoubleClickEvent(QGraphicsSceneMouseEvent *aEvent)
+nsWindow::mouseDoubleClickEvent(QMouseEvent* aEvent)
 {
     uint32_t eventType;
 
     switch (aEvent->button()) {
     case Qt::MidButton:
         eventType = WidgetMouseEvent::eMiddleButton;
         break;
     case Qt::RightButton:
@@ -1389,74 +1012,47 @@ nsWindow::OnMouseDoubleClickEvent(QGraph
     event.button = eventType;
 
     InitButtonEvent(event, aEvent, 2);
     //pressed
     return DispatchEvent(&event);
 }
 
 nsEventStatus
-nsWindow::OnFocusInEvent(QEvent *aEvent)
+nsWindow::focusInEvent(QFocusEvent* aEvent)
 {
     LOGFOCUS(("OnFocusInEvent [%p]\n", (void *)this));
 
-    if (!mWidget)
+    if (!mWidget) {
         return nsEventStatus_eIgnore;
+    }
 
     DispatchActivateEventOnTopLevelWindow();
 
     LOGFOCUS(("Events sent from focus in event [%p]\n", (void *)this));
     return nsEventStatus_eIgnore;
 }
 
 nsEventStatus
-nsWindow::OnFocusOutEvent(QEvent *aEvent)
+nsWindow::focusOutEvent(QFocusEvent* aEvent)
 {
     LOGFOCUS(("OnFocusOutEvent [%p]\n", (void *)this));
 
-    if (!mWidget)
+    if (!mWidget) {
         return nsEventStatus_eIgnore;
+    }
 
     DispatchDeactivateEventOnTopLevelWindow();
 
     LOGFOCUS(("Done with container focus out [%p]\n", (void *)this));
     return nsEventStatus_eIgnore;
 }
 
-inline bool
-is_latin_shortcut_key(quint32 aKeyval)
-{
-    return ((Qt::Key_0 <= aKeyval && aKeyval <= Qt::Key_9) ||
-            (Qt::Key_A <= aKeyval && aKeyval <= Qt::Key_Z));
-}
-
 nsEventStatus
-nsWindow::DispatchCommandEvent(nsIAtom* aCommand)
-{
-    WidgetCommandEvent event(true, nsGkAtoms::onAppCommand, aCommand, this);
-
-    nsEventStatus status;
-    DispatchEvent(&event, status);
-
-    return status;
-}
-
-nsEventStatus
-nsWindow::DispatchContentCommandEvent(int32_t aMsg)
-{
-    WidgetContentCommandEvent event(true, aMsg, this);
-
-    nsEventStatus status;
-    DispatchEvent(&event, status);
-
-    return status;
-}
-
-nsEventStatus
-nsWindow::OnKeyPressEvent(QKeyEvent *aEvent)
+nsWindow::keyPressEvent(QKeyEvent* aEvent)
 {
     LOGFOCUS(("OnKeyPressEvent [%p]\n", (void *)this));
 
     // The user has done something.
     UserActivity();
 
     if (aEvent->key() == Qt::Key_AltGr) {
         sAltGrModifier = true;
@@ -1472,17 +1068,17 @@ nsWindow::OnKeyPressEvent(QKeyEvent *aEv
         //keyEventToContextMenuEvent(&event, &contextMenuEvent);
         return DispatchEvent(&contextMenuEvent);
     }
 
     uint32_t domCharCode = 0;
     uint32_t domKeyCode = QtKeyCodeToDOMKeyCode(aEvent->key());
 
     // get keymap and modifier map from the Xserver
-    Display *display = mozilla::DefaultXDisplay();
+    Display *display = gfxQtPlatform::GetXDisplay(mWidget);
     int x_min_keycode = 0, x_max_keycode = 0, xkeysyms_per_keycode;
     XDisplayKeycodes(display, &x_min_keycode, &x_max_keycode);
     XModifierKeymap *xmodmap = XGetModifierMapping(display);
     if (!xmodmap)
         return nsEventStatus_eIgnore;
 
     KeySym *xkeymap = XGetKeyboardMapping(display, x_min_keycode, x_max_keycode - x_min_keycode,
                                           &xkeysyms_per_keycode);
@@ -1627,30 +1223,30 @@ nsWindow::OnKeyPressEvent(QKeyEvent *aEv
     WidgetKeyboardEvent event(true, NS_KEY_PRESS, this);
     InitKeyEvent(event, aEvent);
 
     // If there is no charcode attainable from the text, try to
     // generate it from the keycode. Check shift state for case
     // Also replace the charcode if ControlModifier is the only
     // pressed Modifier
     if ((!domCharCode) &&
-        (QApplication::keyboardModifiers() &
+        (QGuiApplication::keyboardModifiers() &
         (Qt::ControlModifier | Qt::AltModifier | Qt::MetaModifier))) {
 
         // get a character from X11 key map
         KeySym keysym = aEvent->nativeVirtualKey();
         if (keysym) {
             domCharCode = (uint32_t) keysym2ucs(keysym);
             if (domCharCode == -1 || !QChar((quint32)domCharCode).isPrint()) {
                 domCharCode = 0;
             }
         }
 
         // if Ctrl is pressed and domCharCode is not a ASCII character
-        if (domCharCode > 0xFF && (QApplication::keyboardModifiers() & Qt::ControlModifier)) {
+        if (domCharCode > 0xFF && (QGuiApplication::keyboardModifiers() & Qt::ControlModifier)) {
             // replace Unicode character
             int index = (aEvent->nativeScanCode() - x_min_keycode) * xkeysyms_per_keycode;
             for (int i = 0; i < xkeysyms_per_keycode; ++i) {
                 if (xkeymap[index + i] <= 0xFF && !shift_state) {
                     domCharCode = (uint32_t) QChar::toLower((uint) xkeymap[index + i]);
                     break;
                 }
             }
@@ -1685,17 +1281,17 @@ nsWindow::OnKeyPressEvent(QKeyEvent *aEv
     long ucs = keysym2ucs(keysym);
     ucs = ucs == -1 ? 0 : ucs;
     QChar shiftedChar((uint)ucs);
 
     // append alternativeCharCodes if modifier is pressed
     // append an additional alternativeCharCodes if domCharCode is not a Latin character
     // and if one of these modifiers is pressed (i.e. Ctrl, Alt, Meta)
     if (domCharCode &&
-        (QApplication::keyboardModifiers() &
+        (QGuiApplication::keyboardModifiers() &
         (Qt::ControlModifier | Qt::AltModifier | Qt::MetaModifier))) {
 
         event.charCode = domCharCode;
         event.keyCode = 0;
         AlternativeCharCode altCharCode(0, 0);
         // if character has a lower and upper representation
         if ((unshiftedChar.isUpper() || unshiftedChar.isLower()) &&
             unshiftedChar.toLower() == shiftedChar.toLower()) {
@@ -1776,18 +1372,19 @@ nsWindow::OnKeyPressEvent(QKeyEvent *aEv
                                           WidgetMouseEvent::eContextMenuKey);
         //keyEventToContextMenuEvent(&event, &contextMenuEvent);
         return DispatchEvent(&contextMenuEvent);
     }
 
     uint32_t domCharCode = 0;
     uint32_t domKeyCode = QtKeyCodeToDOMKeyCode(aEvent->key());
 
-    if (aEvent->text().length() && aEvent->text()[0].isPrint())
+    if (aEvent->text().length() && aEvent->text()[0].isPrint()) {
         domCharCode = (int32_t) aEvent->text()[0].unicode();
+    }
 
     KeyNameIndex keyNameIndex =
         domCharCode ? KEY_NAME_INDEX_PrintableKey :
                       QtKeyCodeToDOMKeyNameIndex(aEvent->key());
 
     // If the key isn't autorepeat, we need to send the initial down event
     if (!aEvent->isAutoRepeat() && !IsKeyDown(domKeyCode)) {
         // send the key down event
@@ -1817,34 +1414,34 @@ nsWindow::OnKeyPressEvent(QKeyEvent *aEv
     event.mKeyNameIndex = keyNameIndex;
 
     // send the key press event
     return DispatchEvent(&event);
 #endif
 }
 
 nsEventStatus
-nsWindow::OnKeyReleaseEvent(QKeyEvent *aEvent)
+nsWindow::keyReleaseEvent(QKeyEvent* aEvent)
 {
     LOGFOCUS(("OnKeyReleaseEvent [%p]\n", (void *)this));
 
     // The user has done something.
     UserActivity();
 
     if (isContextMenuKeyEvent(aEvent)) {
         // er, what do we do here? DoDefault or NoDefault?
         return nsEventStatus_eConsumeDoDefault;
     }
 
     uint32_t domKeyCode = QtKeyCodeToDOMKeyCode(aEvent->key());
 
 #ifdef MOZ_X11
     if (!domKeyCode) {
         // get keymap from the Xserver
-        Display *display = mozilla::DefaultXDisplay();
+        Display *display = gfxQtPlatform::GetXDisplay(mWidget);
         int x_min_keycode = 0, x_max_keycode = 0, xkeysyms_per_keycode;
         XDisplayKeycodes(display, &x_min_keycode, &x_max_keycode);
         KeySym *xkeymap = XGetKeyboardMapping(display, x_min_keycode, x_max_keycode - x_min_keycode,
                                               &xkeysyms_per_keycode);
 
         if (aEvent->nativeScanCode() >= (quint32)x_min_keycode &&
             aEvent->nativeScanCode() <= (quint32)x_max_keycode) {
             int index = (aEvent->nativeScanCode() - x_min_keycode) * xkeysyms_per_keycode;
@@ -1875,17 +1472,17 @@ nsWindow::OnKeyReleaseEvent(QKeyEvent *a
 
     // unset the key down flag
     ClearKeyDownFlag(event.keyCode);
 
     return DispatchEvent(&event);
 }
 
 nsEventStatus
-nsWindow::OnScrollEvent(QGraphicsSceneWheelEvent *aEvent)
+nsWindow::wheelEvent(QWheelEvent* aEvent)
 {
     // check to see if we should rollup
     WidgetWheelEvent wheelEvent(true, NS_WHEEL_WHEEL, this);
     wheelEvent.deltaMode = nsIDOMWheelEvent::DOM_DELTA_LINE;
 
     // negative values for aEvent->delta indicate downward scrolling;
     // this is opposite Gecko usage.
     // TODO: Store the unused delta values due to fraction round and add it
@@ -1900,392 +1497,552 @@ nsWindow::OnScrollEvent(QGraphicsSceneWh
     case Qt::Horizontal:
         wheelEvent.deltaX = wheelEvent.lineOrPageDeltaX = delta;
         break;
     default:
         Q_ASSERT(0);
         break;
     }
 
-    wheelEvent.refPoint.x = nscoord(aEvent->scenePos().x());
-    wheelEvent.refPoint.y = nscoord(aEvent->scenePos().y());
+    wheelEvent.refPoint.x = nscoord(aEvent->pos().x());
+    wheelEvent.refPoint.y = nscoord(aEvent->pos().y());
 
     wheelEvent.InitBasicModifiers(aEvent->modifiers() & Qt::ControlModifier,
                                   aEvent->modifiers() & Qt::AltModifier,
                                   aEvent->modifiers() & Qt::ShiftModifier,
                                   aEvent->modifiers() & Qt::MetaModifier);
     wheelEvent.time = 0;
 
     return DispatchEvent(&wheelEvent);
 }
 
-
 nsEventStatus
 nsWindow::showEvent(QShowEvent *)
 {
     LOG(("%s [%p]\n", __PRETTY_FUNCTION__,(void *)this));
-    mIsVisible = true;
+    mVisible = true;
     return nsEventStatus_eConsumeDoDefault;
 }
 
 nsEventStatus
 nsWindow::hideEvent(QHideEvent *)
 {
     LOG(("%s [%p]\n", __PRETTY_FUNCTION__,(void *)this));
-    mIsVisible = false;
+    mVisible = false;
     return nsEventStatus_eConsumeDoDefault;
 }
 
-//Gestures are only supported in 4.6.0 >
-#if (QT_VERSION >= QT_VERSION_CHECK(4, 6, 0))
-nsEventStatus nsWindow::OnTouchEvent(QTouchEvent *event, bool &handled)
+nsEventStatus nsWindow::touchEvent(QTouchEvent* aEvent)
 {
-    handled = false;
-    const QList<QTouchEvent::TouchPoint> &touchPoints = event->touchPoints();
-
-    if (event->type() == QEvent::TouchBegin) {
-        handled = true;
-        for (int i = touchPoints.count() -1; i >= 0; i--) {
-            QPointF fpos = touchPoints[i].pos();
-            WidgetGestureNotifyEvent gestureNotifyEvent(true,
-                                         NS_GESTURENOTIFY_EVENT_START, this);
-            gestureNotifyEvent.refPoint = LayoutDeviceIntPoint(fpos.x(), fpos.y());
-            DispatchEvent(&gestureNotifyEvent);
-        }
-    }
-    else if (event->type() == QEvent::TouchEnd) {
-        mGesturesCancelled = false;
-        mPinchEvent.needDispatch = false;
-    }
-
-    if (touchPoints.count() > 0) {
-        // Remember start touch point in order to use it for
-        // distance calculation in NS_SIMPLE_GESTURE_MAGNIFY_UPDATE
-        mPinchEvent.touchPoint = touchPoints.at(0).pos();
-    }
-
     return nsEventStatus_eIgnore;
 }
 
 nsEventStatus
-nsWindow::OnGestureEvent(QGestureEvent* event, bool &handled) {
-
-    handled = false;
-    if (mGesturesCancelled) {
-        return nsEventStatus_eIgnore;
-    }
-
-    nsEventStatus result = nsEventStatus_eIgnore;
+nsWindow::tabletEvent(QTabletEvent* aEvent)
+{
+    LOGFOCUS(("nsWindow::%s [%p]\n", __FUNCTION__, (void *)this));
+    return nsEventStatus_eIgnore;
+}
 
-    QGesture* gesture = event->gesture(Qt::PinchGesture);
-
-    if (gesture) {
-        QPinchGesture* pinch = static_cast<QPinchGesture*>(gesture);
-        handled = true;
-
-        mPinchEvent.centerPoint =
-            mWidget->mapFromScene(event->mapToGraphicsScene(pinch->centerPoint()));
-        nsIntPoint centerPoint(mPinchEvent.centerPoint.x(),
-                               mPinchEvent.centerPoint.y());
+//  Helpers
 
-        if (pinch->state() == Qt::GestureStarted) {
-            event->accept();
-            mPinchEvent.startDistance = DistanceBetweenPoints(mPinchEvent.centerPoint, mPinchEvent.touchPoint) * 2;
-            mPinchEvent.prevDistance = mPinchEvent.startDistance;
-            result = DispatchGestureEvent(NS_SIMPLE_GESTURE_MAGNIFY_START,
-                                          0, 0, centerPoint);
-        }
-        else if (pinch->state() == Qt::GestureUpdated) {
-            mPinchEvent.needDispatch = true;
-            mPinchEvent.delta = 0;
-            DispatchMotionToMainThread();
-        }
-        else if (pinch->state() == Qt::GestureFinished) {
-            double distance = DistanceBetweenPoints(mPinchEvent.centerPoint, mPinchEvent.touchPoint) * 2;
-            double delta = distance - mPinchEvent.startDistance;
-            result = DispatchGestureEvent(NS_SIMPLE_GESTURE_MAGNIFY,
-                                          0, delta, centerPoint);
-            mPinchEvent.needDispatch = false;
-        }
-        else {
-            handled = false;
-        }
-
-        //Disable mouse events when gestures are used, because they cause problems with
-        //Fennec
-        mLastMultiTouchTime.start();
-    }
+void
+nsWindow::InitButtonEvent(WidgetMouseEvent& aMoveEvent,
+                          QMouseEvent* aEvent,
+                          int aClickCount)
+{
+    aMoveEvent.refPoint.x = nscoord(aEvent->pos().x());
+    aMoveEvent.refPoint.y = nscoord(aEvent->pos().y());
 
-    gesture = event->gesture(gSwipeGestureId);
-    if (gesture) {
-        if (gesture->state() == Qt::GestureStarted) {
-            event->accept();
-        }
-        if (gesture->state() == Qt::GestureFinished) {
-            event->accept();
-            handled = true;
-
-            MozSwipeGesture* swipe = static_cast<MozSwipeGesture*>(gesture);
-            nsIntPoint hotspot;
-            hotspot.x = swipe->hotSpot().x();
-            hotspot.y = swipe->hotSpot().y();
-
-            // Cancel pinch gesture
-            mGesturesCancelled = true;
-            mPinchEvent.needDispatch = false;
-
-            double distance = DistanceBetweenPoints(swipe->hotSpot(), mPinchEvent.touchPoint) * 2;
-            double delta = distance - mPinchEvent.startDistance;
-
-            DispatchGestureEvent(NS_SIMPLE_GESTURE_MAGNIFY, 0, delta / 2, hotspot);
-
-            result = DispatchGestureEvent(NS_SIMPLE_GESTURE_SWIPE,
-                                          swipe->Direction(), 0, hotspot);
-        }
-        mLastMultiTouchTime.start();
-    }
-
-    return result;
+    aMoveEvent.InitBasicModifiers(aEvent->modifiers() & Qt::ControlModifier,
+                                  aEvent->modifiers() & Qt::AltModifier,
+                                  aEvent->modifiers() & Qt::ShiftModifier,
+                                  aEvent->modifiers() & Qt::MetaModifier);
+    aMoveEvent.clickCount      = aClickCount;
 }
 
 nsEventStatus
-nsWindow::DispatchGestureEvent(uint32_t aMsg, uint32_t aDirection,
-                               double aDelta, const nsIntPoint& aRefPoint)
+nsWindow::DispatchEvent(WidgetGUIEvent* aEvent)
+{
+    nsEventStatus status;
+    DispatchEvent(aEvent, status);
+    return status;
+}
+
+void
+nsWindow::DispatchActivateEvent(void)
+{
+    if (mWidgetListener) {
+        mWidgetListener->WindowActivated();
+    }
+}
+
+void
+nsWindow::DispatchDeactivateEvent(void)
+{
+    if (mWidgetListener) {
+        mWidgetListener->WindowDeactivated();
+    }
+}
+
+void
+nsWindow::DispatchActivateEventOnTopLevelWindow(void)
 {
-    WidgetSimpleGestureEvent mozGesture(true, aMsg, this, 0, 0.0);
-    mozGesture.direction = aDirection;
-    mozGesture.delta = aDelta;
-    mozGesture.refPoint = LayoutDeviceIntPoint::FromUntyped(aRefPoint);
+    nsWindow* topLevelWindow = static_cast<nsWindow*>(GetTopLevelWidget());
+    if (topLevelWindow != nullptr) {
+        topLevelWindow->DispatchActivateEvent();
+    }
+}
+
+void
+nsWindow::DispatchDeactivateEventOnTopLevelWindow(void)
+{
+    nsWindow* topLevelWindow = static_cast<nsWindow*>(GetTopLevelWidget());
+    if (topLevelWindow != nullptr) {
+        topLevelWindow->DispatchDeactivateEvent();
+    }
+}
+
+void
+nsWindow::DispatchResizeEvent(nsIntRect &aRect, nsEventStatus &aStatus)
+{
+    aStatus = nsEventStatus_eIgnore;
+    if (mWidgetListener &&
+        mWidgetListener->WindowResized(this, aRect.width, aRect.height)) {
+        aStatus = nsEventStatus_eConsumeNoDefault;
+    }
+}
+
+///////////////////////////////////// OLD GECKO ECENTS need to Sort ///////////////////
+
+/* static */ bool
+isContextMenuKeyEvent(const QKeyEvent *qe)
+{
+    uint32_t kc = QtKeyCodeToDOMKeyCode(qe->key());
+    if (qe->modifiers() & (Qt::ControlModifier | Qt::AltModifier | Qt::MetaModifier)) {
+        return false;
+    }
+
+    bool isShift = qe->modifiers() & Qt::ShiftModifier;
+    return (kc == NS_VK_F10 && isShift) ||
+        (kc == NS_VK_CONTEXT_MENU && !isShift);
+}
 
-    Qt::KeyboardModifiers modifiers = QApplication::keyboardModifiers();
+/* static */void
+InitKeyEvent(WidgetKeyboardEvent &aEvent, QKeyEvent *aQEvent)
+{
+    aEvent.InitBasicModifiers(aQEvent->modifiers() & Qt::ControlModifier,
+                              aQEvent->modifiers() & Qt::AltModifier,
+                              aQEvent->modifiers() & Qt::ShiftModifier,
+                              aQEvent->modifiers() & Qt::MetaModifier);
+    aEvent.mIsRepeat =
+        (aEvent.message == NS_KEY_DOWN || aEvent.message == NS_KEY_PRESS) &&
+        aQEvent->isAutoRepeat();
+    aEvent.time = 0;
+
+    if (sAltGrModifier) {
+        aEvent.modifiers |= (MODIFIER_CONTROL | MODIFIER_ALT);
+    }
+
+    // The transformations above and in qt for the keyval are not invertible
+    // so link to the QKeyEvent (which will vanish soon after return from the
+    // event callback) to give plugins access to hardware_keycode and state.
+    // (An XEvent would be nice but the QKeyEvent is good enough.)
+    aEvent.pluginEvent = (void *)aQEvent;
+}
+
+NS_IMPL_ISUPPORTS_INHERITED1(nsWindow, nsBaseWidget, nsISupportsWeakReference)
+
+
 
-    mozGesture.InitBasicModifiers(modifiers & Qt::ControlModifier,
-                                  modifiers & Qt::AltModifier,
-                                  modifiers & Qt::ShiftModifier,
-                                  false);
-    mozGesture.button    = 0;
-    mozGesture.time      = 0;
+void
+nsWindow::ClearCachedResources()
+{
+    if (mLayerManager &&
+        mLayerManager->GetBackendType() == mozilla::layers::LayersBackend::LAYERS_BASIC) {
+        mLayerManager->ClearCachedResources();
+    }
+    for (nsIWidget* kid = mFirstChild; kid; ) {
+        nsIWidget* next = kid->GetNextSibling();
+        static_cast<nsWindow*>(kid)->ClearCachedResources();
+        kid = next;
+    }
+}
+
+NS_IMETHODIMP
+nsWindow::SetParent(nsIWidget *aNewParent)
+{
+    NS_ENSURE_ARG_POINTER(aNewParent);
 
-    return DispatchEvent(&mozGesture);
+    nsCOMPtr<nsIWidget> kungFuDeathGrip(this);
+    nsIWidget* parent = GetParent();
+    if (parent) {
+        parent->RemoveChild(this);
+    }
+    ReparentNativeWidget(aNewParent);
+    aNewParent->AddChild(this);
+    return NS_OK;
+}
+
+NS_IMETHODIMP
+nsWindow::SetModal(bool aModal)
+{
+    LOG(("nsWindow::SetModal [%p] %d, widget[%p]\n", (void *)this, aModal, mWidget));
+    if (mWidget) {
+        mWidget->setModality(aModal ? Qt::WindowModal : Qt::NonModal);
+    }
+
+    return NS_OK;
 }
 
 
-double
-nsWindow::DistanceBetweenPoints(const QPointF &aFirstPoint, const QPointF &aSecondPoint)
+NS_IMETHODIMP
+nsWindow::PlaceBehind(nsTopLevelWidgetZPlacement  aPlacement,
+                      nsIWidget                  *aWidget,
+                      bool                        aActivate)
+{
+    return NS_ERROR_NOT_IMPLEMENTED;
+}
+
+NS_IMETHODIMP
+nsWindow::SetSizeMode(int32_t aMode)
 {
-    double result = 0;
-    double deltaX = abs(aFirstPoint.x() - aSecondPoint.x());
-    double deltaY = abs(aFirstPoint.y() - aSecondPoint.y());
-    result = sqrt(deltaX*deltaX + deltaY*deltaY);
-    return result;
+    nsresult rv;
+
+    LOG(("nsWindow::SetSizeMode [%p] %d\n", (void *)this, aMode));
+    if (aMode != nsSizeMode_Minimized) {
+        mWidget->requestActivate();
+    }
+
+    // Save the requested state.
+    rv = nsBaseWidget::SetSizeMode(aMode);
+
+    // return if there's no shell or our current state is the same as
+    // the mode we were just set to.
+    if (!mWidget || mSizeState == mSizeMode) {
+        return rv;
+    }
+