Merge mozilla-central to fx-team
authorCarsten "Tomcat" Book <cbook@mozilla.com>
Fri, 24 Jan 2014 09:27:22 +0100
changeset 181106 f9a4e354878bc5503def366a4c6275f4967798fd
parent 181030 0e17908f897fb4bdc7a566186d8de510a06188db (current diff)
parent 180988 9d650c07b5476aec4e12f100e62d7f742548b9e3 (diff)
child 181107 2552d554372d96baf3e26ddaf66468886b51cbb9
push id3343
push userffxbld
push dateMon, 17 Mar 2014 21:55:32 +0000
treeherdermozilla-beta@2f7d3415f79f [default view] [failures only]
perfherder[talos] [build metrics] [platform microbench] (compared to previous push)
milestone29.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
Merge mozilla-central to fx-team
media/libvorbis/bug944977-r19028.patch
--- a/accessible/src/jsat/AccessFu.jsm
+++ b/accessible/src/jsat/AccessFu.jsm
@@ -501,71 +501,109 @@ var Output = {
               'clicked.ogg'],
 
     earconBuffers: {},
 
     inited: false,
 
     webspeechEnabled: false,
 
+    deferredOutputs: [],
+
     init: function init() {
       let window = Utils.win;
       this.webspeechEnabled = !!window.speechSynthesis;
 
+      let settingsToGet = 2;
+      let settingsCallback = (aName, aSetting) => {
+        if (--settingsToGet > 0) {
+          return;
+        }
+
+        this.inited = true;
+
+        for (let actions of this.deferredOutputs) {
+          this.output(actions);
+        }
+      };
+
+      this._volumeSetting = new SettingCache(
+        'accessibility.screenreader-volume', settingsCallback,
+        { defaultValue: 1, callbackNow: true, callbackOnce: true });
+      this._rateSetting = new SettingCache(
+        'accessibility.screenreader-rate', settingsCallback,
+        { defaultValue: 0, callbackNow: true, callbackOnce: true });
+
       for (let earcon of this.EARCONS) {
         let earconName = /(^.*)\..*$/.exec(earcon)[1];
         this.earconBuffers[earconName] = new WeakMap();
         this.earconBuffers[earconName].set(
           window, new window.Audio('chrome://global/content/accessibility/' + earcon));
       }
+    },
 
-      this.inited = true;
+    uninit: function uninit() {
+      if (this.inited) {
+        delete this._volumeSetting;
+        delete this._rateSetting;
+      }
+      this.inited = false;
     },
 
     output: function output(aActions) {
       if (!this.inited) {
-        this.init();
+        this.deferredOutputs.push(aActions);
+        return;
       }
 
       for (let action of aActions) {
         let window = Utils.win;
         Logger.debug('tts.' + action.method, '"' + action.data + '"',
                      JSON.stringify(action.options));
 
         if (!action.options.enqueue && this.webspeechEnabled) {
           window.speechSynthesis.cancel();
         }
 
         if (action.method === 'speak' && this.webspeechEnabled) {
-          window.speechSynthesis.speak(
-            new window.SpeechSynthesisUtterance(action.data));
+          let utterance = new window.SpeechSynthesisUtterance(action.data);
+          let requestedRate = this._rateSetting.value;
+          utterance.volume = this._volumeSetting.value;
+          utterance.rate = requestedRate >= 0 ?
+            requestedRate + 1 : 1 / (Math.abs(requestedRate) + 1);
+          window.speechSynthesis.speak(utterance);
         } else if (action.method === 'playEarcon') {
           let audioBufferWeakMap = this.earconBuffers[action.data];
           if (audioBufferWeakMap) {
-            audioBufferWeakMap.get(window).cloneNode(false).play();
+            let node = audioBufferWeakMap.get(window).cloneNode(false);
+            node.volume = this._volumeSetting.value;
+            node.play();
           }
         }
       }
     }
   },
 
   start: function start() {
     Cu.import('resource://gre/modules/Geometry.jsm');
+    this.speechHelper.init();
   },
 
   stop: function stop() {
     if (this.highlightBox) {
       Utils.win.document.documentElement.removeChild(this.highlightBox.get());
       delete this.highlightBox;
     }
 
     if (this.announceBox) {
       Utils.win.document.documentElement.removeChild(this.announceBox.get());
       delete this.announceBox;
     }
+
+    this.speechHelper.uninit();
   },
 
   Speech: function Speech(aDetails, aBrowser) {
     this.speechHelper.output(aDetails.actions);
   },
 
   Visual: function Visual(aDetails, aBrowser) {
     switch (aDetails.method) {
--- a/accessible/src/jsat/Utils.jsm
+++ b/accessible/src/jsat/Utils.jsm
@@ -15,17 +15,17 @@ XPCOMUtils.defineLazyModuleGetter(this, 
   'resource://gre/modules/Geometry.jsm');
 XPCOMUtils.defineLazyModuleGetter(this, 'Roles',
   'resource://gre/modules/accessibility/Constants.jsm');
 XPCOMUtils.defineLazyModuleGetter(this, 'Events',
   'resource://gre/modules/accessibility/Constants.jsm');
 XPCOMUtils.defineLazyModuleGetter(this, 'Relations',
   'resource://gre/modules/accessibility/Constants.jsm');
 
-this.EXPORTED_SYMBOLS = ['Utils', 'Logger', 'PivotContext', 'PrefCache'];
+this.EXPORTED_SYMBOLS = ['Utils', 'Logger', 'PivotContext', 'PrefCache', 'SettingCache'];
 
 this.Utils = {
   _buildAppMap: {
     '{3c2e2abc-06d4-11e1-ac3b-374f68613e61}': 'b2g',
     '{ec8030f7-c20a-464f-9b0e-13a3a9e97384}': 'browser',
     '{aa3c5121-dab2-40e2-81ca-7ea25febc110}': 'mobile/android',
     '{a23983c0-fd0e-11dc-95ff-0800200c9a66}': 'mobile/xul'
   },
@@ -769,8 +769,41 @@ PrefCache.prototype = {
         Logger.logException(x);
       }
     }
   },
 
   QueryInterface : XPCOMUtils.generateQI([Ci.nsIObserver,
                                           Ci.nsISupportsWeakReference])
 };
+
+this.SettingCache = function SettingCache(aName, aCallback, aOptions = {}) {
+  this.value = aOptions.defaultValue;
+  let runCallback = () => {
+    if (aCallback && aOptions.callbackNow) {
+      aCallback(aName, this.value);
+      if (aOptions.callbackOnce) {
+        runCallback = () => {};
+      }
+    }
+  };
+
+  let settings = Utils.win.navigator.mozSettings;
+  if (!settings) {
+    runCallback();
+    return;
+  }
+
+
+  let lock = settings.createLock();
+  let req = lock.get(aName);
+
+  req.addEventListener('success', () => {
+    this.value = req.result[aName] == undefined ? aOptions.defaultValue : req.result[aName];
+    runCallback();
+  });
+
+  settings.addObserver(aName,
+                       (evt) => {
+                         this.value = evt.settingValue;
+                         runCallback();
+                       });
+};
--- a/accessible/src/jsat/content-script.js
+++ b/accessible/src/jsat/content-script.js
@@ -338,23 +338,24 @@ function scroll(aMessage) {
   let position = Utils.getVirtualCursor(content.document).position;
   if (!forwardToChild(aMessage, scroll, position)) {
     sendScrollCoordinates(position);
   }
 }
 
 function adjustRange(aMessage) {
   function sendUpDownKey(aAccessible) {
-    let evt = content.document.createEvent('KeyboardEvent');
-    let keycode = aMessage.json.direction == 'forward' ?
-      content.KeyEvent.DOM_VK_DOWN : content.KeyEvent.DOM_VK_UP;
-    evt.initKeyEvent(
-      "keypress", false, true, null, false, false, false, false, keycode, 0);
-    if (aAccessible.DOMNode) {
-      aAccessible.DOMNode.dispatchEvent(evt);
+    let acc = Utils.getEmbeddedControl(aAccessible) || aAccessible;
+    if (acc.DOMNode) {
+      let evt = content.document.createEvent('KeyboardEvent');
+      let keycode = aMessage.json.direction == 'forward' ?
+        content.KeyEvent.DOM_VK_DOWN : content.KeyEvent.DOM_VK_UP;
+      evt.initKeyEvent(
+        "keypress", false, true, null, false, false, false, false, keycode, 0);
+      acc.DOMNode.dispatchEvent(evt);
     }
   }
 
   let position = Utils.getVirtualCursor(content.document).position;
   if (!forwardToChild(aMessage, adjustRange, position)) {
     sendUpDownKey(position);
   }
 }
--- a/content/base/src/Element.cpp
+++ b/content/base/src/Element.cpp
@@ -1621,17 +1621,18 @@ Element::SetEventHandler(nsIAtom* aEvent
                                                                    &defer);
   if (!manager) {
     return NS_OK;
   }
 
   defer = defer && aDefer; // only defer if everyone agrees...
   manager->SetEventHandler(aEventName, aValue,
                            nsIProgrammingLanguage::JAVASCRIPT,
-                           defer, !nsContentUtils::IsChromeDoc(ownerDoc));
+                           defer, !nsContentUtils::IsChromeDoc(ownerDoc),
+                           this);
   return NS_OK;
 }
 
 
 //----------------------------------------------------------------------
 
 const nsAttrName*
 Element::InternalGetExistingAttrNameFromQName(const nsAString& aStr) const
--- a/content/base/src/nsScriptLoader.cpp
+++ b/content/base/src/nsScriptLoader.cpp
@@ -994,32 +994,47 @@ nsScriptLoader::GetScriptGlobalObject()
     return nullptr;
   }
 
   return globalObject.forget();
 }
 
 void
 nsScriptLoader::FillCompileOptionsForRequest(nsScriptLoadRequest *aRequest,
-                                             JS::Handle<JSObject *> scopeChain,
+                                             JS::Handle<JSObject *> aScopeChain,
                                              JS::CompileOptions *aOptions)
 {
   // It's very important to use aRequest->mURI, not the final URI of the channel
   // aRequest ended up getting script data from, as the script filename.
   nsContentUtils::GetWrapperSafeScriptFilename(mDocument, aRequest->mURI, aRequest->mURL);
 
   aOptions->setFileAndLine(aRequest->mURL.get(), aRequest->mLineNo);
   aOptions->setVersion(JSVersion(aRequest->mJSVersion));
-  aOptions->setCompileAndGo(JS_IsGlobalObject(scopeChain));
+  aOptions->setCompileAndGo(JS_IsGlobalObject(aScopeChain));
   if (aRequest->mHasSourceMapURL) {
     aOptions->setSourceMapURL(aRequest->mSourceMapURL.get());
   }
   if (aRequest->mOriginPrincipal) {
     aOptions->setOriginPrincipals(nsJSPrincipals::get(aRequest->mOriginPrincipal));
   }
+
+  AutoJSContext cx;
+  JS::Rooted<JS::Value> elementVal(cx);
+  MOZ_ASSERT(aRequest->mElement);
+  // XXXbz this is super-fragile, because the code that _uses_ the
+  // JS::CompileOptions is nowhere near us, but we have to coordinate
+  // compartments with it... and in particular, it will compile in the
+  // compartment of aScopeChain, so we want to wrap into that compartment as
+  // well.
+  if (NS_SUCCEEDED(nsContentUtils::WrapNative(cx, aScopeChain,
+                                              aRequest->mElement, &elementVal,
+                                              /* aAllowWrapping = */ true))) {
+    MOZ_ASSERT(elementVal.isObject());
+    aOptions->setElement(&elementVal.toObject());
+  }
 }
 
 nsresult
 nsScriptLoader::EvaluateScript(nsScriptLoadRequest* aRequest,
                                const nsAFlatString& aScript,
                                void** aOffThreadToken)
 {
   nsresult rv = NS_OK;
--- a/content/base/src/nsScriptLoader.h
+++ b/content/base/src/nsScriptLoader.h
@@ -277,17 +277,17 @@ private:
   void FireScriptEvaluated(nsresult aResult,
                            nsScriptLoadRequest* aRequest);
   nsresult EvaluateScript(nsScriptLoadRequest* aRequest,
                           const nsAFlatString& aScript,
                           void **aOffThreadToken);
 
   already_AddRefed<nsIScriptGlobalObject> GetScriptGlobalObject();
   void FillCompileOptionsForRequest(nsScriptLoadRequest *aRequest,
-                                    JS::Handle<JSObject *> scopeChain,
+                                    JS::Handle<JSObject *> aScopeChain,
                                     JS::CompileOptions *aOptions);
 
   nsresult PrepareLoadedRequest(nsScriptLoadRequest* aRequest,
                                 nsIStreamLoader* aLoader,
                                 nsresult aStatus,
                                 uint32_t aStringLen,
                                 const uint8_t* aString);
 
--- a/content/canvas/src/CanvasRenderingContext2D.cpp
+++ b/content/canvas/src/CanvasRenderingContext2D.cpp
@@ -3459,17 +3459,17 @@ CanvasRenderingContext2D::DrawWindow(nsG
       return;
     }
 
     thebes = new gfxContext(drawDT);
     thebes->Scale(matrix._11, matrix._22);
   } else {
     drawSurf =
       gfxPlatform::GetPlatform()->CreateOffscreenSurface(gfxIntSize(ceil(sw), ceil(sh)),
-                                                         GFX_CONTENT_COLOR_ALPHA);
+                                                         gfxContentType::COLOR_ALPHA);
     if (!drawSurf) {
       error.Throw(NS_ERROR_FAILURE);
       return;
     }
 
     thebes = new gfxContext(drawSurf);
     thebes->Scale(matrix._11, matrix._22);
   }
@@ -3896,17 +3896,17 @@ CanvasRenderingContext2D::PutImageData_e
   }
 
   uint32_t len = w * h * 4;
   if (aDataLen != len) {
     return NS_ERROR_DOM_SYNTAX_ERR;
   }
 
   nsRefPtr<gfxImageSurface> imgsurf = new gfxImageSurface(gfxIntSize(w, h),
-                                                          gfxImageFormatARGB32,
+                                                          gfxImageFormat::ARGB32,
                                                           false);
   if (!imgsurf || imgsurf->CairoStatus()) {
     return NS_ERROR_FAILURE;
   }
 
   uint8_t *src = aData;
   uint8_t *dst = imgsurf->Data();
 
--- a/content/canvas/src/DocumentRendererChild.cpp
+++ b/content/canvas/src/DocumentRendererChild.cpp
@@ -71,17 +71,17 @@ DocumentRendererChild::RenderDocument(ns
 
     // Draw directly into the output array.
     data.SetLength(renderSize.width * renderSize.height * 4);
 
     nsRefPtr<gfxImageSurface> surf =
         new gfxImageSurface(reinterpret_cast<uint8_t*>(data.BeginWriting()),
                             gfxIntSize(renderSize.width, renderSize.height),
                             4 * renderSize.width,
-                            gfxImageFormatARGB32);
+                            gfxImageFormat::ARGB32);
     nsRefPtr<gfxContext> ctx = new gfxContext(surf);
     ctx->SetMatrix(mozilla::gfx::ThebesMatrix(transform));
 
     nsCOMPtr<nsIPresShell> shell = presContext->PresShell();
     shell->RenderDocument(documentRect, renderFlags, bgColor, ctx);
 
     return true;
 }
--- a/content/canvas/src/DocumentRendererParent.cpp
+++ b/content/canvas/src/DocumentRendererParent.cpp
@@ -27,17 +27,17 @@ void DocumentRendererParent::DrawToCanva
 {
     if (!mCanvas || !mCanvasContext)
         return;
 
     nsRefPtr<gfxImageSurface> surf =
         new gfxImageSurface(reinterpret_cast<uint8_t*>(const_cast<nsCString&>(aData).BeginWriting()),
                             gfxIntSize(aSize.width, aSize.height),
                             aSize.width * 4,
-                            gfxImageFormatARGB32);
+                            gfxImageFormat::ARGB32);
     nsRefPtr<gfxPattern> pat = new gfxPattern(surf);
 
     gfxRect rect(gfxPoint(0, 0), gfxSize(aSize.width, aSize.height));
     mCanvasContext->NewPath();
     mCanvasContext->PixelSnappedRectangleAndSetPattern(rect, pat);
     mCanvasContext->Fill();
 
     // get rid of the pattern surface ref, because aData is very
--- a/content/canvas/src/ImageEncoder.cpp
+++ b/content/canvas/src/ImageEncoder.cpp
@@ -279,17 +279,17 @@ ImageEncoder::ExtractDataInternal(const 
                                   getter_AddRefs(imgStream));
   } else {
     // no context, so we have to encode an empty image
     // note that if we didn't have a current context, the spec says we're
     // supposed to just return transparent black pixels of the canvas
     // dimensions.
     nsRefPtr<gfxImageSurface> emptyCanvas =
       new gfxImageSurface(gfxIntSize(aSize.width, aSize.height),
-                          gfxImageFormatARGB32);
+                          gfxImageFormat::ARGB32);
     if (emptyCanvas->CairoStatus()) {
       return NS_ERROR_INVALID_ARG;
     }
     rv = aEncoder->InitFromData(emptyCanvas->Data(),
                                 aSize.width * aSize.height * 4,
                                 aSize.width,
                                 aSize.height,
                                 aSize.width * 4,
--- a/content/canvas/src/WebGLContext.cpp
+++ b/content/canvas/src/WebGLContext.cpp
@@ -616,17 +616,17 @@ WebGLContext::SetDimensions(int32_t widt
 
 NS_IMETHODIMP
 WebGLContext::Render(gfxContext *ctx, GraphicsFilter f, uint32_t aFlags)
 {
     if (!gl)
         return NS_OK;
 
     nsRefPtr<gfxImageSurface> surf = new gfxImageSurface(gfxIntSize(mWidth, mHeight),
-                                                         gfxImageFormatARGB32);
+                                                         gfxImageFormat::ARGB32);
     if (surf->CairoStatus() != 0)
         return NS_ERROR_FAILURE;
 
     gl->MakeCurrent();
     ReadScreenIntoImageSurface(gl, surf);
 
     bool srcPremultAlpha = mOptions.premultipliedAlpha;
     bool dstPremultAlpha = aFlags & RenderFlagPremultAlpha;
@@ -744,17 +744,17 @@ void WebGLContext::LoseOldestWebGLContex
 void
 WebGLContext::GetImageBuffer(uint8_t** aImageBuffer, int32_t* aFormat)
 {
     *aImageBuffer = nullptr;
     *aFormat = 0;
 
     nsRefPtr<gfxImageSurface> imgsurf =
         new gfxImageSurface(gfxIntSize(mWidth, mHeight),
-                            gfxImageFormatARGB32);
+                            gfxImageFormat::ARGB32);
 
     if (!imgsurf || imgsurf->CairoStatus()) {
         return;
     }
 
     nsRefPtr<gfxContext> ctx = new gfxContext(imgsurf);
     if (!ctx || ctx->HasError()) {
         return;
--- a/content/media/fmp4/MP4Reader.cpp
+++ b/content/media/fmp4/MP4Reader.cpp
@@ -76,17 +76,17 @@ public:
   }
 
 private:
   RefPtr<MediaResource> mResource;
 };
 
 MP4Reader::MP4Reader(AbstractMediaDecoder* aDecoder)
   : MediaDecoderReader(aDecoder),
-    mLayersBackendType(layers::LAYERS_NONE),
+    mLayersBackendType(layers::LayersBackend::LAYERS_NONE),
     mHasAudio(false),
     mHasVideo(false)
 {
   MOZ_COUNT_CTOR(MP4Reader);
 }
 
 MP4Reader::~MP4Reader()
 {
--- a/content/media/plugins/MediaPluginReader.cpp
+++ b/content/media/plugins/MediaPluginReader.cpp
@@ -348,17 +348,17 @@ MediaPluginReader::ImageBufferCallback::
     return nullptr;
   }
 
   nsRefPtr<Image> image;
   switch(aColorFormat) {
     case MPAPI::RGB565:
       image = mozilla::layers::CreateSharedRGBImage(mImageContainer,
                                                     nsIntSize(aWidth, aHeight),
-                                                    gfxImageFormatRGB16_565);
+                                                    gfxImageFormat::RGB16_565);
       if (!image) {
         NS_WARNING("Could not create rgb image");
         return nullptr;
       }
 
       mImage = image;
       return image->AsSharedImage()->GetBuffer();
     case MPAPI::I420:
--- a/content/media/webrtc/MediaEngineTabVideoSource.cpp
+++ b/content/media/webrtc/MediaEngineTabVideoSource.cpp
@@ -233,17 +233,17 @@ MediaEngineTabVideoSource::Draw() {
   nsCOMPtr<nsIPresShell> presShell = presContext->PresShell();
   uint32_t renderDocFlags = (nsIPresShell::RENDER_IGNORE_VIEWPORT_SCROLLING |
                              nsIPresShell::RENDER_DOCUMENT_RELATIVE);
   nsRect r(nsPresContext::CSSPixelsToAppUnits(srcX / scale),
            nsPresContext::CSSPixelsToAppUnits(srcY / scale),
            nsPresContext::CSSPixelsToAppUnits(srcW / scale),
            nsPresContext::CSSPixelsToAppUnits(srcH / scale));
 
-  gfxImageFormat format = gfxImageFormatRGB24;
+  gfxImageFormat format = gfxImageFormat::RGB24;
   uint32_t stride = gfxASurface::FormatStrideForWidth(format, size.width);
 
   nsRefPtr<layers::ImageContainer> container = layers::LayerManager::CreateImageContainer();
   nsRefPtr<gfxASurface> surf;
   surf = new gfxImageSurface(static_cast<unsigned char*>(mData),
                              ThebesIntSize(size), stride, format);
   if (surf->CairoStatus() != 0) {
     return;
--- a/dom/bindings/BindingUtils.h
+++ b/dom/bindings/BindingUtils.h
@@ -1311,16 +1311,35 @@ WrapCallThisObject(JSContext* cx, JS::Ha
   // But all that won't necessarily put things in the compartment of cx.
   if (!JS_WrapObject(cx, &obj)) {
     return nullptr;
   }
 
   return obj;
 }
 
+/*
+ * This specialized function simply wraps a JS::Rooted<> since
+ * WrapNativeParent() is not applicable for JS objects.
+ */
+template<>
+inline JSObject*
+WrapCallThisObject<JS::Rooted<JSObject*>>(JSContext* cx,
+                                          JS::Handle<JSObject*> scope,
+                                          const JS::Rooted<JSObject*>& p)
+{
+  JS::Rooted<JSObject*> obj(cx, p);
+
+  if (!JS_WrapObject(cx, &obj)) {
+    return nullptr;
+  }
+
+  return obj;
+}
+
 // Helper for calling WrapNewBindingObject with smart pointers
 // (nsAutoPtr/nsRefPtr/nsCOMPtr) or references.
 template <class T, bool isSmartPtr=HasgetMember<T>::Value>
 struct WrapNewBindingObjectHelper
 {
   static inline bool Wrap(JSContext* cx, JS::Handle<JSObject*> scope,
                           const T& value, JS::MutableHandle<JS::Value> rval)
   {
--- a/dom/datastore/DataStore.jsm
+++ b/dom/datastore/DataStore.jsm
@@ -31,17 +31,17 @@ Cu.import('resource://gre/modules/XPCOMU
 Cu.importGlobalProperties(["indexedDB"]);
 
 XPCOMUtils.defineLazyServiceGetter(this, "cpmm",
                                    "@mozilla.org/childprocessmessagemanager;1",
                                    "nsIMessageSender");
 
 /* Helper functions */
 function createDOMError(aWindow, aEvent) {
-  return new aWindow.DOMError(aEvent.target.error.name);
+  return new aWindow.DOMError(aEvent);
 }
 
 function throwInvalidArg(aWindow) {
   return aWindow.Promise.reject(
     new aWindow.DOMError("SyntaxError", "Non-numeric or invalid id"));
 }
 
 function throwReadOnly(aWindow) {
new file mode 100644
--- /dev/null
+++ b/dom/datastore/tests/file_duplicate.html
@@ -0,0 +1,75 @@
+<!DOCTYPE HTML>
+<html>
+<head>
+  <meta charset="utf-8">
+  <title>Test for DataStore - duplicate keys</title>
+</head>
+<body>
+<div id="container"></div>
+  <script type="application/javascript;version=1.7">
+
+  var gStore;
+  var gEvent;
+  var gChangeId;
+
+  function ok(a, msg) {
+    alert((a ? 'OK' : 'KO')+ ' ' + msg)
+  }
+
+  function is(a, b, msg) {
+    ok(a === b, msg);
+  }
+
+  function cbError() {
+    alert('KO error');
+  }
+
+  function finish() {
+    alert('DONE');
+  }
+
+  function testGetDataStores() {
+    navigator.getDataStores('foo').then(function(stores) {
+      gStore = stores[0];
+      runTest();
+    }, cbError);
+  }
+
+  function testAdd(success) {
+    gStore.add({ a: 42 }, 'test').then(function() {
+      is(success, true, "Record added");
+      runTest();
+    }, function(e) {
+      is(success, false, "Record failed");
+      ok(e instanceof DOMError, "DOMError received");
+      is(e.name, 'ConstraintError', 'e.name: ConstraintError');
+      is(e.message, '', 'e.message');
+      runTest();
+    });
+  }
+
+  var tests = [
+    // Test for GetDataStore
+    testGetDataStores,
+
+    // add
+    function() { testAdd(true); },
+
+    // add duplicate
+    function() { testAdd(false); }
+  ];
+
+  function runTest() {
+    if (!tests.length) {
+      finish();
+      return;
+    }
+
+    var test = tests.shift();
+    test();
+  }
+
+  runTest();
+  </script>
+</body>
+</html>
--- a/dom/datastore/tests/mochitest.ini
+++ b/dom/datastore/tests/mochitest.ini
@@ -8,19 +8,21 @@ support-files =
   file_app.sjs
   file_app.template.webapp
   file_app2.template.webapp
   file_arrays.html
   file_sync.html
   file_bug924104.html
   file_certifiedApp.html
   file_keys.html
+  file_duplicate.html
 
 [test_app_install.html]
 [test_readonly.html]
 [test_basic.html]
 [test_changes.html]
 [test_arrays.html]
 [test_oop.html]
 [test_sync.html]
 [test_bug924104.html]
 [test_certifiedApp.html]
 [test_keys.html]
+[test_duplicate.html]
new file mode 100644
--- /dev/null
+++ b/dom/datastore/tests/test_duplicate.html
@@ -0,0 +1,128 @@
+<!DOCTYPE HTML>
+<html>
+<head>
+  <meta charset="utf-8">
+  <title>Test for DataStore - duplicate keys</title>
+  <script type="application/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
+  <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/>
+</head>
+<body>
+<div id="container"></div>
+  <script type="application/javascript;version=1.7">
+
+  var gHostedManifestURL = 'http://test/tests/dom/datastore/tests/file_app.sjs?testToken=file_duplicate.html';
+  var gApp;
+
+  function cbError() {
+    ok(false, "Error callback invoked");
+    finish();
+  }
+
+  function installApp() {
+    var request = navigator.mozApps.install(gHostedManifestURL);
+    request.onerror = cbError;
+    request.onsuccess = function() {
+      gApp = request.result;
+      runTest();
+    }
+  }
+
+  function uninstallApp() {
+    // Uninstall the app.
+    var request = navigator.mozApps.mgmt.uninstall(gApp);
+    request.onerror = cbError;
+    request.onsuccess = function() {
+      // All done.
+      info("All done");
+      runTest();
+    }
+  }
+
+  function testApp() {
+    var ifr = document.createElement('iframe');
+    ifr.setAttribute('mozbrowser', 'true');
+    ifr.setAttribute('mozapp', gApp.manifestURL);
+    ifr.setAttribute('src', gApp.manifest.launch_path);
+    var domParent = document.getElementById('container');
+
+    // Set us up to listen for messages from the app.
+    var listener = function(e) {
+      var message = e.detail.message;
+      if (/^OK/.exec(message)) {
+        ok(true, "Message from app: " + message);
+      } else if (/KO/.exec(message)) {
+        ok(false, "Message from app: " + message);
+      } else if (/DONE/.exec(message)) {
+        ok(true, "Messaging from app complete");
+        ifr.removeEventListener('mozbrowsershowmodalprompt', listener);
+        domParent.removeChild(ifr);
+        runTest();
+      }
+    }
+
+    // This event is triggered when the app calls "alert".
+    ifr.addEventListener('mozbrowsershowmodalprompt', listener, false);
+    domParent.appendChild(ifr);
+  }
+
+  var tests = [
+    // Permissions
+    function() {
+      SpecialPowers.pushPermissions(
+        [{ "type": "browser", "allow": 1, "context": document },
+         { "type": "embed-apps", "allow": 1, "context": document },
+         { "type": "webapps-manage", "allow": 1, "context": document }], runTest);
+    },
+
+    // Preferences
+    function() {
+      SpecialPowers.pushPrefEnv({"set": [["dom.promise.enabled", true],
+                                         ["dom.datastore.enabled", true],
+                                         ["dom.testing.ignore_ipc_principal", true],
+                                         ["dom.testing.datastore_enabled_for_hosted_apps", true]]}, runTest);
+    },
+
+    function() {
+      SpecialPowers.setAllAppsLaunchable(true);
+      SpecialPowers.setBoolPref("dom.mozBrowserFramesEnabled", true);
+      runTest();
+    },
+
+    // No confirmation needed when an app is installed
+    function() {
+      SpecialPowers.autoConfirmAppInstall(runTest);
+    },
+
+    // Installing the app
+    installApp,
+
+    // Run tests in app
+    testApp,
+
+    // Uninstall the app
+    uninstallApp
+  ];
+
+  function runTest() {
+    if (!tests.length) {
+      finish();
+      return;
+    }
+
+    var test = tests.shift();
+    test();
+  }
+
+  function finish() {
+    SimpleTest.finish();
+  }
+
+  if (SpecialPowers.isMainProcess()) {
+    SpecialPowers.Cu.import("resource://gre/modules/DataStoreChangeNotifier.jsm");
+  }
+
+  SimpleTest.waitForExplicitFinish();
+  runTest();
+  </script>
+</body>
+</html>
--- a/dom/events/nsEventListenerManager.cpp
+++ b/dom/events/nsEventListenerManager.cpp
@@ -32,16 +32,18 @@
 #include "nsContentUtils.h"
 #include "nsJSUtils.h"
 #include "nsEventDispatcher.h"
 #include "nsCOMArray.h"
 #include "nsEventListenerService.h"
 #include "nsIContentSecurityPolicy.h"
 #include "xpcpublic.h"
 #include "nsSandboxFlags.h"
+#include "mozilla/dom/Element.h"
+#include "mozilla/dom/BindingUtils.h"
 
 using namespace mozilla;
 using namespace mozilla::dom;
 using namespace mozilla::hal;
 
 #define EVENT_TYPE_EQUALS(ls, type, userType, typeString, allEvents) \
   ((ls->mEventType == type &&                                        \
     (ls->mEventType != NS_USER_DEFINED_EVENT ||                      \
@@ -622,17 +624,18 @@ nsEventListenerManager::SetEventHandlerI
   return ls;
 }
 
 nsresult
 nsEventListenerManager::SetEventHandler(nsIAtom *aName,
                                         const nsAString& aBody,
                                         uint32_t aLanguage,
                                         bool aDeferCompilation,
-                                        bool aPermitUntrustedEvents)
+                                        bool aPermitUntrustedEvents,
+                                        Element* aElement)
 {
   NS_PRECONDITION(aLanguage != nsIProgrammingLanguage::UNKNOWN,
                   "Must know the language for the script event listener");
 
   // |aPermitUntrustedEvents| is set to False for chrome - events
   // *generated* from an unknown source are not allowed.
   // However, for script languages with no 'sandbox', we want to reject
   // such scripts based on the source of their code, not just the source
@@ -728,17 +731,17 @@ nsEventListenerManager::SetEventHandler(
                               global->GetGlobalJSObject());
 
   nsListenerStruct* ls = SetEventHandlerInternal(scope, aName,
                                                  EmptyString(),
                                                  nsEventHandler(),
                                                  aPermitUntrustedEvents);
 
   if (!aDeferCompilation) {
-    return CompileEventHandlerInternal(ls, &aBody);
+    return CompileEventHandlerInternal(ls, &aBody, aElement);
   }
 
   return NS_OK;
 }
 
 void
 nsEventListenerManager::RemoveEventHandler(nsIAtom* aName,
                                            const nsAString& aTypeString)
@@ -757,17 +760,18 @@ nsEventListenerManager::RemoveEventHandl
     if (mTarget && aName) {
       mTarget->EventListenerRemoved(aName);
     }
   }
 }
 
 nsresult
 nsEventListenerManager::CompileEventHandlerInternal(nsListenerStruct *aListenerStruct,
-                                                    const nsAString* aBody)
+                                                    const nsAString* aBody,
+                                                    Element* aElement)
 {
   NS_PRECONDITION(aListenerStruct->GetJSListener(),
                   "Why do we not have a JS listener?");
   NS_PRECONDITION(aListenerStruct->mHandlerIsString,
                   "Why are we compiling a non-string JS listener?");
 
   nsresult result = NS_OK;
 
@@ -782,34 +786,38 @@ nsEventListenerManager::CompileEventHand
 
   nsIScriptContext* context = global->GetScriptContext();
   NS_ENSURE_STATE(context);
 
   // Push a context to make sure exceptions are reported in the right place.
   AutoPushJSContext cx(context->GetNativeContext());
   JS::Rooted<JSObject*> handler(cx);
 
+  JS::Rooted<JSObject*> scope(cx, listener->GetEventScope());
+
+  nsIAtom* attrName = aListenerStruct->mTypeAtom;
+
   if (aListenerStruct->mHandlerIsString) {
     // OK, we didn't find an existing compiled event handler.  Flag us
     // as not a string so we don't keep trying to compile strings
     // which can't be compiled
     aListenerStruct->mHandlerIsString = false;
 
-    // mTarget may not be an nsIContent if it's a window and we're
+    // mTarget may not be an Element if it's a window and we're
     // getting an inline event listener forwarded from <html:body> or
     // <html:frameset> or <xul:window> or the like.
     // XXX I don't like that we have to reference content from
     // here. The alternative is to store the event handler string on
     // the nsIJSEventListener itself, and that still doesn't address
     // the arg names issue.
-    nsCOMPtr<nsIContent> content = do_QueryInterface(mTarget);
+    nsCOMPtr<Element> element = do_QueryInterface(mTarget);
+    MOZ_ASSERT(element || aBody, "Where will we get our body?");
     nsAutoString handlerBody;
     const nsAString* body = aBody;
-    if (content && !aBody) {
-      nsIAtom* attrName = aListenerStruct->mTypeAtom;
+    if (!aBody) {
       if (aListenerStruct->mTypeAtom == nsGkAtoms::onSVGLoad)
         attrName = nsGkAtoms::onload;
       else if (aListenerStruct->mTypeAtom == nsGkAtoms::onSVGUnload)
         attrName = nsGkAtoms::onunload;
       else if (aListenerStruct->mTypeAtom == nsGkAtoms::onSVGAbort)
         attrName = nsGkAtoms::onabort;
       else if (aListenerStruct->mTypeAtom == nsGkAtoms::onSVGError)
         attrName = nsGkAtoms::onerror;
@@ -821,61 +829,74 @@ nsEventListenerManager::CompileEventHand
         attrName = nsGkAtoms::onzoom;
       else if (aListenerStruct->mTypeAtom == nsGkAtoms::onbeginEvent)
         attrName = nsGkAtoms::onbegin;
       else if (aListenerStruct->mTypeAtom == nsGkAtoms::onrepeatEvent)
         attrName = nsGkAtoms::onrepeat;
       else if (aListenerStruct->mTypeAtom == nsGkAtoms::onendEvent)
         attrName = nsGkAtoms::onend;
 
-      content->GetAttr(kNameSpaceID_None, attrName, handlerBody);
+      element->GetAttr(kNameSpaceID_None, attrName, handlerBody);
       body = &handlerBody;
+      aElement = element;
     }
 
     uint32_t lineNo = 0;
     nsAutoCString url (NS_LITERAL_CSTRING("-moz-evil:lying-event-listener"));
-    if (doc) {
-      nsIURI *uri = doc->GetDocumentURI();
-      if (uri) {
-        uri->GetSpec(url);
-        lineNo = 1;
-      }
+    MOZ_ASSERT(body);
+    MOZ_ASSERT(aElement);
+    nsIURI *uri = aElement->OwnerDoc()->GetDocumentURI();
+    if (uri) {
+      uri->GetSpec(url);
+      lineNo = 1;
     }
 
     uint32_t argCount;
     const char **argNames;
-    // If no content, then just use kNameSpaceID_None for the
-    // namespace ID.  In practice, it doesn't matter since SVG is
-    // the only thing with weird arg names and SVG doesn't map event
-    // listeners to the window.
-    nsContentUtils::GetEventArgNames(content ?
-                                       content->GetNameSpaceID() :
-                                       kNameSpaceID_None,
+    nsContentUtils::GetEventArgNames(aElement->GetNameSpaceID(),
                                      aListenerStruct->mTypeAtom,
                                      &argCount, &argNames);
 
     JSAutoCompartment ac(cx, context->GetWindowProxy());
     JS::CompileOptions options(cx);
     options.setFileAndLine(url.get(), lineNo)
            .setVersion(SCRIPTVERSION_DEFAULT);
 
+    JS::Rooted<JS::Value> targetVal(cx);
+    // Go ahead and wrap into the current compartment of cx directly.
+    JS::Rooted<JSObject*> wrapScope(cx, JS::CurrentGlobalOrNull(cx));
+    if (WrapNewBindingObject(cx, wrapScope, aElement, &targetVal)) {
+      MOZ_ASSERT(targetVal.isObject());
+
+      nsDependentAtomString str(attrName);
+      // Most of our names are short enough that we don't even have to malloc
+      // the JS string stuff, so don't worry about playing games with
+      // refcounting XPCOM stringbuffers.
+      JS::Rooted<JSString*> jsStr(cx, JS_NewUCStringCopyN(cx,
+                                                          str.BeginReading(),
+                                                          str.Length()));
+      NS_ENSURE_TRUE(jsStr, NS_ERROR_OUT_OF_MEMORY);
+
+      options.setElement(&targetVal.toObject())
+             .setElementAttributeName(jsStr);
+    }
+
     JS::Rooted<JSObject*> handlerFun(cx);
     result = nsJSUtils::CompileFunction(cx, JS::NullPtr(), options,
                                         nsAtomCString(aListenerStruct->mTypeAtom),
                                         argCount, argNames, *body, handlerFun.address());
     NS_ENSURE_SUCCESS(result, result);
     handler = handlerFun;
     NS_ENSURE_TRUE(handler, NS_ERROR_FAILURE);
   }
 
   if (handler) {
     nsCOMPtr<nsPIDOMWindow> win = do_QueryInterface(mTarget);
     // Bind it
     JS::Rooted<JSObject*> boundHandler(cx);
-    JS::Rooted<JSObject*> scope(cx, listener->GetEventScope());
     context->BindCompiledEventHandler(mTarget, scope, handler, &boundHandler);
     aListenerStruct = nullptr;
     // Note - We pass null for aIncumbentGlobal below. We could also pass the
     // compilation global, but since the handler is guaranteed to be scripted,
     // there's no need to use an override, since the JS engine will always give
     // us the right answer.
     if (!boundHandler) {
       listener->ForgetHandler();
@@ -904,17 +925,17 @@ nsEventListenerManager::HandleEventSubTy
 {
   nsresult result = NS_OK;
   EventListenerHolder listener(aListenerStruct->mListener);  // strong ref
 
   // If this is a script handler and we haven't yet
   // compiled the event handler itself
   if ((aListenerStruct->mListenerType == eJSEventListener) &&
       aListenerStruct->mHandlerIsString) {
-    result = CompileEventHandlerInternal(aListenerStruct, nullptr);
+    result = CompileEventHandlerInternal(aListenerStruct, nullptr, nullptr);
     aListenerStruct = nullptr;
   }
 
   if (NS_SUCCEEDED(result)) {
     if (mIsMainThreadELM) {
       nsContentUtils::EnterMicroTask();
     }
     // nsIDOMEvent::currentTarget is set in nsEventDispatcher.
@@ -1137,17 +1158,18 @@ nsEventListenerManager::GetListenerInfo(
   NS_ENSURE_STATE(target);
   aList->Clear();
   uint32_t count = mListeners.Length();
   for (uint32_t i = 0; i < count; ++i) {
     const nsListenerStruct& ls = mListeners.ElementAt(i);
     // If this is a script handler and we haven't yet
     // compiled the event handler itself go ahead and compile it
     if ((ls.mListenerType == eJSEventListener) && ls.mHandlerIsString) {
-      CompileEventHandlerInternal(const_cast<nsListenerStruct*>(&ls), nullptr);
+      CompileEventHandlerInternal(const_cast<nsListenerStruct*>(&ls), nullptr,
+                                  nullptr);
     }
     nsAutoString eventType;
     if (ls.mAllEvents) {
       eventType.SetIsVoid(true);
     } else {
       eventType.Assign(Substring(nsDependentAtomString(ls.mTypeAtom), 2));
     }
     // EventListenerInfo is defined in XPCOM, so we have to go ahead
@@ -1246,17 +1268,17 @@ nsEventListenerManager::GetEventHandlerI
 
   if (!ls) {
     return nullptr;
   }
 
   nsIJSEventListener *listener = ls->GetJSListener();
     
   if (ls->mHandlerIsString) {
-    CompileEventHandlerInternal(ls, nullptr);
+    CompileEventHandlerInternal(ls, nullptr, nullptr);
   }
 
   const nsEventHandler& handler = listener->GetHandler();
   if (handler.HasEventHandler()) {
     return &handler;
   }
 
   return nullptr;
--- a/dom/events/nsEventListenerManager.h
+++ b/dom/events/nsEventListenerManager.h
@@ -27,16 +27,17 @@ struct nsListenerStruct;
 class nsEventListenerManager;
 
 template<class T> class nsCOMArray;
 
 namespace mozilla {
 namespace dom {
 
 class EventTarget;
+class Element;
 
 typedef CallbackObjectHolder<EventListener, nsIDOMEventListener>
   EventListenerHolder;
 
 struct EventListenerFlags
 {
   friend struct ::nsListenerStruct;
   friend class  ::nsEventListenerManager;
@@ -278,24 +279,27 @@ public:
                                  const nsAString& type,
                                  const mozilla::dom::EventListenerFlags& aFlags);
 
   /**
    * Sets the current "inline" event listener for aName to be a
    * function compiled from aFunc if !aDeferCompilation.  If
    * aDeferCompilation, then we assume that we can get the string from
    * mTarget later and compile lazily.
+   *
+   * aElement, if not null, is the element the string is associated with.
    */
   // XXXbz does that play correctly with nodes being adopted across
   // documents?  Need to double-check the spec here.
   nsresult SetEventHandler(nsIAtom *aName,
                            const nsAString& aFunc,
                            uint32_t aLanguage,
                            bool aDeferCompilation,
-                           bool aPermitUntrustedEvents);
+                           bool aPermitUntrustedEvents,
+                           mozilla::dom::Element* aElement);
   /**
    * Remove the current "inline" event listener for aName.
    */
   void RemoveEventHandler(nsIAtom *aName, const nsAString& aTypeString);
 
   void HandleEvent(nsPresContext* aPresContext,
                    mozilla::WidgetEvent* aEvent, 
                    nsIDOMEvent** aDOMEvent,
@@ -415,20 +419,22 @@ protected:
 
   nsresult HandleEventSubType(nsListenerStruct* aListenerStruct,
                               nsIDOMEvent* aDOMEvent,
                               mozilla::dom::EventTarget* aCurrentTarget);
 
   /**
    * Compile the "inline" event listener for aListenerStruct.  The
    * body of the listener can be provided in aBody; if this is null we
-   * will look for it on mTarget.
+   * will look for it on mTarget.  If aBody is provided, aElement should be
+   * as well; otherwise it will also be inferred from mTarget.
    */
   nsresult CompileEventHandlerInternal(nsListenerStruct *aListenerStruct,
-                                       const nsAString* aBody);
+                                       const nsAString* aBody,
+                                       mozilla::dom::Element* aElement);
 
   /**
    * Find the nsListenerStruct for the "inline" event listener for aTypeAtom.
    */
   nsListenerStruct* FindEventHandler(uint32_t aEventType, nsIAtom* aTypeAtom,
                                      const nsAString& aTypeString);
 
   /**
--- a/dom/events/nsEventListenerService.cpp
+++ b/dom/events/nsEventListenerService.cpp
@@ -64,61 +64,60 @@ nsEventListenerInfo::GetInSystemEventGro
   return NS_OK;
 }
 
 NS_IMETHODIMP
 nsEventListenerInfo::GetListenerObject(JSContext* aCx,
                                        JS::MutableHandle<JS::Value> aObject)
 {
   mozilla::Maybe<JSAutoCompartment> ac;
-  GetJSVal(aCx, ac, aObject.address());
+  GetJSVal(aCx, ac, aObject);
   return NS_OK;
 }
 
 NS_IMPL_ISUPPORTS1(nsEventListenerService, nsIEventListenerService)
 
-// Caller must root *aJSVal!
 bool
 nsEventListenerInfo::GetJSVal(JSContext* aCx,
                               mozilla::Maybe<JSAutoCompartment>& aAc,
-                              JS::Value* aJSVal)
+                              JS::MutableHandle<JS::Value> aJSVal)
 {
-  *aJSVal = JSVAL_NULL;
+  aJSVal.setNull();
   nsCOMPtr<nsIXPConnectWrappedJS> wrappedJS = do_QueryInterface(mListener);
   if (wrappedJS) {
     JS::Rooted<JSObject*> object(aCx, wrappedJS->GetJSObject());
     if (!object) {
       return false;
     }
     aAc.construct(aCx, object);
-    *aJSVal = OBJECT_TO_JSVAL(object);
+    aJSVal.setObject(*object);
     return true;
   }
 
   nsCOMPtr<nsIJSEventListener> jsl = do_QueryInterface(mListener);
   if (jsl && jsl->GetHandler().HasEventHandler()) {
     JS::Handle<JSObject*> handler(jsl->GetHandler().Ptr()->Callable());
     if (handler) {
       aAc.construct(aCx, handler);
-      *aJSVal = OBJECT_TO_JSVAL(handler);
+      aJSVal.setObject(*handler);
       return true;
     }
   }
   return false;
 }
 
 NS_IMETHODIMP
 nsEventListenerInfo::ToSource(nsAString& aResult)
 {
   aResult.SetIsVoid(true);
 
   AutoSafeJSContext cx;
   mozilla::Maybe<JSAutoCompartment> ac;
-  JS::Rooted<JS::Value> v(cx, JSVAL_NULL);
-  if (GetJSVal(cx, ac, v.address())) {
+  JS::Rooted<JS::Value> v(cx);
+  if (GetJSVal(cx, ac, &v)) {
     JSString* str = JS_ValueToSource(cx, v);
     if (str) {
       nsDependentJSString depStr;
       if (depStr.init(cx, str)) {
         aResult.Assign(depStr);
       }
     }
   }
@@ -137,18 +136,18 @@ nsEventListenerInfo::GetDebugObject(nsIS
   NS_ENSURE_SUCCESS(rv, NS_OK);
 
   bool isOn = false;
   jsd->GetIsOn(&isOn);
   NS_ENSURE_TRUE(isOn, NS_OK);
 
   AutoSafeJSContext cx;
   mozilla::Maybe<JSAutoCompartment> ac;
-  JS::Rooted<JS::Value> v(cx, JSVAL_NULL);
-  if (GetJSVal(cx, ac, v.address())) {
+  JS::Rooted<JS::Value> v(cx);
+  if (GetJSVal(cx, ac, &v)) {
     nsCOMPtr<jsdIValue> jsdValue;
     rv = jsd->WrapValue(v, getter_AddRefs(jsdValue));
     NS_ENSURE_SUCCESS(rv, rv);
     jsdValue.forget(aRetVal);
   }
 #endif
 
   return NS_OK;
--- a/dom/events/nsEventListenerService.h
+++ b/dom/events/nsEventListenerService.h
@@ -29,17 +29,17 @@ public:
     mAllowsUntrusted(aAllowsUntrusted),
     mInSystemEventGroup(aInSystemEventGroup) {}
   virtual ~nsEventListenerInfo() {}
   NS_DECL_CYCLE_COLLECTING_ISUPPORTS
   NS_DECL_CYCLE_COLLECTION_CLASS(nsEventListenerInfo)
   NS_DECL_NSIEVENTLISTENERINFO
 protected:
   bool GetJSVal(JSContext* aCx, mozilla::Maybe<JSAutoCompartment>& aAc,
-                JS::Value* aJSVal);
+                JS::MutableHandle<JS::Value> aJSVal);
 
   nsString                      mType;
   // nsReftPtr because that is what nsListenerStruct uses too.
   nsRefPtr<nsIDOMEventListener> mListener;
   bool                          mCapturing;
   bool                          mAllowsUntrusted;
   bool                          mInSystemEventGroup;
 };
--- a/dom/events/nsEventStateManager.cpp
+++ b/dom/events/nsEventStateManager.cpp
@@ -1696,20 +1696,18 @@ nsEventStateManager::HandleCrossProcessE
   // event to.
   //
   // NB: the elements of |targets| must be unique, for correctness.
   nsAutoTArray<nsCOMPtr<nsIContent>, 1> targets;
   if (aEvent->eventStructType != NS_TOUCH_EVENT ||
       aEvent->message == NS_TOUCH_START) {
     // If this event only has one target, and it's remote, add it to
     // the array.
-    nsIContent* target = mCurrentTargetContent;
-    if (!target && aTargetFrame) {
-      target = aTargetFrame->GetContent();
-    }
+    nsIFrame* frame = GetEventTarget();
+    nsIContent* target = frame ? frame->GetContent() : nullptr;
     if (IsRemoteTarget(target)) {
       targets.AppendElement(target);
     }
   } else {
     // This is a touch event with possibly multiple touch points.
     // Each touch point may have its own target.  So iterate through
     // all of them and collect the unique set of targets for event
     // forwarding.
--- a/dom/file/FileHandle.cpp
+++ b/dom/file/FileHandle.cpp
@@ -31,17 +31,18 @@ public:
                 FileRequest* aFileRequest,
                 MetadataParameters* aParams,
                 FileHandle* aFileHandle)
   : MetadataHelper(aLockedFile, aFileRequest, aParams),
     mFileHandle(aFileHandle)
   { }
 
   nsresult
-  GetSuccessResult(JSContext* aCx, JS::Value* aVal);
+  GetSuccessResult(JSContext* aCx,
+                   JS::MutableHandle<JS::Value> aVal) MOZ_OVERRIDE;
 
   void
   ReleaseObjects()
   {
     mFileHandle = nullptr;
 
     MetadataHelper::ReleaseObjects();
   }
@@ -173,29 +174,27 @@ FileHandle::GetFileId()
 
 NS_IMETHODIMP_(mozilla::dom::indexedDB::FileInfo*)
 FileHandle::GetFileInfo()
 {
   return nullptr;
 }
 
 nsresult
-GetFileHelper::GetSuccessResult(JSContext* aCx, JS::Value* aVal)
+GetFileHelper::GetSuccessResult(JSContext* aCx,
+                                JS::MutableHandle<JS::Value> aVal)
 {
   nsCOMPtr<nsIDOMFile> domFile =
     mFileHandle->CreateFileObject(mLockedFile, mParams->Size());
 
   JS::Rooted<JSObject*> global(aCx, JS::CurrentGlobalOrNull(aCx));
-  JS::Rooted<JS::Value> rval(aCx);
   nsresult rv =
     nsContentUtils::WrapNative(aCx, global, domFile,
-                               &NS_GET_IID(nsIDOMFile), &rval);
+                               &NS_GET_IID(nsIDOMFile), aVal);
   NS_ENSURE_SUCCESS(rv, NS_ERROR_DOM_FILEHANDLE_UNKNOWN_ERR);
-  *aVal = rval;
-
   return NS_OK;
 }
 
 /* virtual */
 JSObject*
 FileHandle::WrapObject(JSContext* aCx, JS::Handle<JSObject*> aScope)
 {
   return FileHandleBinding::Wrap(aCx, aScope, this);
--- a/dom/file/FileHelper.cpp
+++ b/dom/file/FileHelper.cpp
@@ -145,21 +145,21 @@ FileHelper::GetCurrentLockedFile()
 {
   NS_ASSERTION(NS_IsMainThread(), "Wrong thread!");
 
   return gCurrentLockedFile;
 }
 
 nsresult
 FileHelper::GetSuccessResult(JSContext* aCx,
-                             JS::Value* aVal)
+                             JS::MutableHandle<JS::Value> aVal)
 {
   NS_ASSERTION(NS_IsMainThread(), "Wrong thread!");
 
-  *aVal = JSVAL_VOID;
+  aVal.setUndefined();
   return NS_OK;
 }
 
 void
 FileHelper::ReleaseObjects()
 {
   NS_ASSERTION(NS_IsMainThread(), "Wrong thread!");
 
--- a/dom/file/FileHelper.h
+++ b/dom/file/FileHelper.h
@@ -69,17 +69,17 @@ protected:
   FileHelper(LockedFile* aLockedFile, FileRequest* aRequest);
 
   virtual ~FileHelper();
 
   virtual nsresult
   DoAsyncRun(nsISupports* aStream) = 0;
 
   virtual nsresult
-  GetSuccessResult(JSContext* aCx, JS::Value* aVal);
+  GetSuccessResult(JSContext* aCx, JS::MutableHandle<JS::Value> aVal);
 
   virtual void
   ReleaseObjects();
 
   void
   Finish();
 
   nsCOMPtr<nsIFileStorage> mFileStorage;
--- a/dom/file/FileRequest.cpp
+++ b/dom/file/FileRequest.cpp
@@ -79,17 +79,17 @@ FileRequest::NotifyHelperCompleted(FileH
 
   JS::Rooted<JS::Value> result(cx);
 
   JS::Rooted<JSObject*> global(cx, sc->GetWindowProxy());
   NS_ASSERTION(global, "Failed to get global object!");
 
   JSAutoCompartment ac(cx, global);
 
-  rv = aFileHelper->GetSuccessResult(cx, result.address());
+  rv = aFileHelper->GetSuccessResult(cx, &result);
   if (NS_FAILED(rv)) {
     NS_WARNING("GetSuccessResult failed!");
   }
 
   if (NS_SUCCEEDED(rv)) {
     FireSuccess(result);
   }
   else {
--- a/dom/file/LockedFile.cpp
+++ b/dom/file/LockedFile.cpp
@@ -57,20 +57,21 @@ public:
   {
     NS_ASSERTION(mSize, "Passed zero size!");
   }
 
   nsresult
   Init();
 
   nsresult
-  DoAsyncRun(nsISupports* aStream);
+  DoAsyncRun(nsISupports* aStream) MOZ_OVERRIDE;
 
   nsresult
-  GetSuccessResult(JSContext* aCx, JS::Value* aVal);
+  GetSuccessResult(JSContext* aCx,
+                   JS::MutableHandle<JS::Value> aVal) MOZ_OVERRIDE;
 
 protected:
   uint64_t mLocation;
   uint64_t mSize;
 
   nsRefPtr<MemoryOutputStream> mStream;
 };
 
@@ -82,17 +83,18 @@ public:
                  uint64_t aLocation,
                  uint64_t aSize,
                  const nsAString& aEncoding)
   : ReadHelper(aLockedFile, aFileRequest, aLocation, aSize),
     mEncoding(aEncoding)
   { }
 
   nsresult
-  GetSuccessResult(JSContext* aCx, JS::Value* aVal);
+  GetSuccessResult(JSContext* aCx,
+                   JS::MutableHandle<JS::Value> aVal) MOZ_OVERRIDE;
 
 private:
   nsString mEncoding;
 };
 
 class WriteHelper : public FileHelper
 {
 public:
@@ -822,23 +824,23 @@ LockedFile::OpenInputStream(bool aWholeF
   nsRefPtr<OpenStreamHelper> helper =
     new OpenStreamHelper(this, aWholeFile, aStart, aLength);
 
   nsresult rv = helper->Enqueue();
   NS_ENSURE_SUCCESS(rv, NS_ERROR_DOM_FILEHANDLE_UNKNOWN_ERR);
 
   nsCOMPtr<nsIInputStream>& result = helper->Result();
   NS_ENSURE_TRUE(result, NS_ERROR_DOM_FILEHANDLE_UNKNOWN_ERR);
-  
+
   result.forget(aResult);
   return NS_OK;
 }
 
 nsresult
-LockedFile::WriteOrAppend(const JS::Value& aValue,
+LockedFile::WriteOrAppend(JS::Handle<JS::Value> aValue,
                           JSContext* aCx,
                           nsISupports** _retval,
                           bool aAppend)
 {
   if (!IsOpen()) {
     return NS_ERROR_DOM_FILEHANDLE_LOCKEDFILE_INACTIVE_ERR;
   }
 
@@ -850,21 +852,20 @@ LockedFile::WriteOrAppend(const JS::Valu
     return NS_ERROR_DOM_FILEHANDLE_NOT_ALLOWED_ERR;
   }
 
   // Do nothing if the window is closed
   if (!GetOwner()) {
     return NS_OK;
   }
 
-  JS::Rooted<JS::Value> val(aCx, aValue);
   nsCOMPtr<nsIInputStream> inputStream;
   uint64_t inputLength;
   nsresult rv =
-    GetInputStreamForJSVal(val, aCx, getter_AddRefs(inputStream),
+    GetInputStreamForJSVal(aValue, aCx, getter_AddRefs(inputStream),
                            &inputLength);
   NS_ENSURE_SUCCESS(rv, rv);
 
   if (!inputLength) {
     return NS_OK;
   }
 
   nsRefPtr<FileRequest> fileRequest = GenerateFileRequest();
@@ -1014,34 +1015,31 @@ ReadHelper::DoAsyncRun(nsISupports* aStr
 
   mRequest = do_QueryInterface(copier);
 
   return NS_OK;
 }
 
 nsresult
 ReadHelper::GetSuccessResult(JSContext* aCx,
-                             JS::Value* aVal)
+                             JS::MutableHandle<JS::Value> aVal)
 {
   JS::Rooted<JSObject*> arrayBuffer(aCx);
   nsresult rv =
     nsContentUtils::CreateArrayBuffer(aCx, mStream->Data(), arrayBuffer.address());
   NS_ENSURE_SUCCESS(rv, rv);
 
-  *aVal = OBJECT_TO_JSVAL(arrayBuffer);
-
+  aVal.setObject(*arrayBuffer);
   return NS_OK;
 }
 
 nsresult
 ReadTextHelper::GetSuccessResult(JSContext* aCx,
-                                 JS::Value* aVal)
+                                 JS::MutableHandle<JS::Value> aVal)
 {
-  nsresult rv;
-
   nsAutoCString encoding;
   const nsCString& data = mStream->Data();
   // The BOM sniffing is baked into the "decode" part of the Encoding
   // Standard, which the File API references.
   if (!nsContentUtils::CheckForBOM(
         reinterpret_cast<const unsigned char *>(data.get()),
         data.Length(),
         encoding)) {
@@ -1050,27 +1048,24 @@ ReadTextHelper::GetSuccessResult(JSConte
       // API argument failed. Since we are dealing with a file system file,
       // we don't have a meaningful type attribute for the blob available,
       // so proceeding to the next step, which is defaulting to UTF-8.
       encoding.AssignLiteral("UTF-8");
     }
   }
 
   nsString tmpString;
-  rv = nsContentUtils::ConvertStringFromEncoding(encoding, data,
-                                                 tmpString);
+  nsresult rv = nsContentUtils::ConvertStringFromEncoding(encoding, data,
+                                                          tmpString);
   NS_ENSURE_SUCCESS(rv, rv);
 
-  JS::Rooted<JS::Value> rval(aCx);
-  if (!xpc::StringToJsval(aCx, tmpString, &rval)) {
+  if (!xpc::StringToJsval(aCx, tmpString, aVal)) {
     NS_WARNING("Failed to convert string!");
     return NS_ERROR_FAILURE;
   }
-
-  *aVal = rval;
   return NS_OK;
 }
 
 nsresult
 WriteHelper::DoAsyncRun(nsISupports* aStream)
 {
   NS_ASSERTION(aStream, "Passed a null stream!");
 
@@ -1102,17 +1097,17 @@ nsresult
 TruncateHelper::DoAsyncRun(nsISupports* aStream)
 {
   NS_ASSERTION(aStream, "Passed a null stream!");
 
   nsRefPtr<AsyncTruncator> truncator = new AsyncTruncator(aStream, mOffset);
 
   nsresult rv = truncator->AsyncWork(this, nullptr);
   NS_ENSURE_SUCCESS(rv, rv);
-  
+
   return NS_OK;
 }
 
 nsresult
 TruncateHelper::AsyncTruncator::DoStreamWork(nsISupports* aStream)
 {
   nsCOMPtr<nsISeekableStream> sstream = do_QueryInterface(aStream);
 
--- a/dom/file/LockedFile.h
+++ b/dom/file/LockedFile.h
@@ -96,17 +96,17 @@ private:
 
   void
   OnRequestFinished();
 
   inline already_AddRefed<FileRequest>
   GenerateFileRequest();
 
   nsresult
-  WriteOrAppend(const jsval& aValue, JSContext* aCx,
+  WriteOrAppend(JS::Handle<JS::Value> aValue, JSContext* aCx,
                 nsISupports** _retval, bool aAppend);
 
   nsresult
   Finish();
 
   nsRefPtr<FileHandle> mFileHandle;
   ReadyState mReadyState;
   FileMode mMode;
--- a/dom/file/MetadataHelper.cpp
+++ b/dom/file/MetadataHelper.cpp
@@ -21,17 +21,17 @@ MetadataHelper::DoAsyncRun(nsISupports* 
   nsresult rv = getter->AsyncWork(this, nullptr);
   NS_ENSURE_SUCCESS(rv, rv);
 
   return NS_OK;
 }
 
 nsresult
 MetadataHelper::GetSuccessResult(JSContext* aCx,
-                                 JS::Value* aVal)
+                                 JS::MutableHandle<JS::Value> aVal)
 {
   JS::Rooted<JSObject*> obj(aCx, JS_NewObject(aCx, nullptr, JS::NullPtr(),
                                               JS::NullPtr()));
   NS_ENSURE_TRUE(obj, NS_ERROR_OUT_OF_MEMORY);
 
   if (mParams->SizeRequested()) {
     JS::Value val = JS_NumberValue(mParams->Size());
 
@@ -47,18 +47,17 @@ MetadataHelper::GetSuccessResult(JSConte
     NS_ENSURE_TRUE(date, NS_ERROR_OUT_OF_MEMORY);
 
     if (!JS_DefineProperty(aCx, obj, "lastModified", OBJECT_TO_JSVAL(date),
                            nullptr, nullptr, JSPROP_ENUMERATE)) {
       return NS_ERROR_FAILURE;
     }
   }
 
-  *aVal = OBJECT_TO_JSVAL(obj);
-
+  aVal.setObject(*obj);
   return NS_OK;
 }
 
 nsresult
 MetadataHelper::AsyncMetadataGetter::DoStreamWork(nsISupports* aStream)
 {
   nsresult rv;
 
--- a/dom/file/MetadataHelper.h
+++ b/dom/file/MetadataHelper.h
@@ -80,17 +80,18 @@ public:
   : FileHelper(aLockedFile, aFileRequest),
     mParams(aParams)
   { }
 
   nsresult
   DoAsyncRun(nsISupports* aStream) MOZ_OVERRIDE;
 
   nsresult
-  GetSuccessResult(JSContext* aCx, JS::Value* aVal) MOZ_OVERRIDE;
+  GetSuccessResult(JSContext* aCx,
+                   JS::MutableHandle<JS::Value> aVal) MOZ_OVERRIDE;
 
 protected:
   class AsyncMetadataGetter : public AsyncHelper
   {
   public:
     AsyncMetadataGetter(nsISupports* aStream, MetadataParameters* aParams,
                         bool aReadWrite)
     : AsyncHelper(aStream),
--- a/dom/indexedDB/IDBKeyRange.cpp
+++ b/dom/indexedDB/IDBKeyRange.cpp
@@ -24,17 +24,17 @@ using namespace mozilla;
 using namespace mozilla::dom;
 USING_INDEXEDDB_NAMESPACE
 using namespace mozilla::dom::indexedDB::ipc;
 
 namespace {
 
 inline nsresult
 GetKeyFromJSVal(JSContext* aCx,
-                jsval aVal,
+                JS::Handle<JS::Value> aVal,
                 Key& aKey,
                 bool aAllowUnset = false)
 {
   nsresult rv = aKey.SetFromJSVal(aCx, aVal);
   if (NS_FAILED(rv)) {
     NS_ASSERTION(NS_ERROR_GET_MODULE(rv) == NS_ERROR_MODULE_DOM_INDEXEDDB,
                  "Bad error code!");
     return rv;
@@ -47,17 +47,17 @@ GetKeyFromJSVal(JSContext* aCx,
   return NS_OK;
 }
 
 } // anonymous namespace
 
 // static
 nsresult
 IDBKeyRange::FromJSVal(JSContext* aCx,
-                       const jsval& aVal,
+                       JS::Handle<JS::Value> aVal,
                        IDBKeyRange** aKeyRange)
 {
   nsRefPtr<IDBKeyRange> keyRange;
 
   if (aVal.isNullOrUndefined()) {
     // undefined and null returns no IDBKeyRange.
     keyRange.forget(aKeyRange);
     return NS_OK;
@@ -140,18 +140,18 @@ NS_IMPL_CYCLE_COLLECTING_ADDREF(IDBKeyRa
 NS_IMPL_CYCLE_COLLECTING_RELEASE(IDBKeyRange)
 
 void
 IDBKeyRange::DropJSObjects()
 {
   if (!mRooted) {
     return;
   }
-  mCachedLowerVal = JSVAL_VOID;
-  mCachedUpperVal = JSVAL_VOID;
+  mCachedLowerVal = JS::UndefinedValue();
+  mCachedUpperVal = JS::UndefinedValue();
   mHaveCachedLowerVal = false;
   mHaveCachedUpperVal = false;
   mRooted = false;
   mozilla::DropJSObjects(this);
 }
 
 IDBKeyRange::~IDBKeyRange()
 {
--- a/dom/indexedDB/IDBKeyRange.h
+++ b/dom/indexedDB/IDBKeyRange.h
@@ -31,17 +31,17 @@ class KeyRange;
 
 class IDBKeyRange MOZ_FINAL : public nsISupports
 {
 public:
   NS_DECL_CYCLE_COLLECTING_ISUPPORTS
   NS_DECL_CYCLE_COLLECTION_SCRIPT_HOLDER_CLASS(IDBKeyRange)
 
   static nsresult FromJSVal(JSContext* aCx,
-                            const jsval& aVal,
+                            JS::Handle<JS::Value> aVal,
                             IDBKeyRange** aKeyRange);
 
   template <class T>
   static already_AddRefed<IDBKeyRange>
   FromSerializedKeyRange(const T& aKeyRange);
 
   const Key& Lower() const
   {
--- a/dom/indexedDB/Key.cpp
+++ b/dom/indexedDB/Key.cpp
@@ -96,49 +96,44 @@ USING_INDEXEDDB_NAMESPACE
  [[]]          // 8
 */
 
 const int MaxArrayCollapse = 3;
 
 const int MaxRecursionDepth = 256;
 
 nsresult
-Key::EncodeJSValInternal(JSContext* aCx, const jsval aVal,
+Key::EncodeJSValInternal(JSContext* aCx, JS::Handle<JS::Value> aVal,
                          uint8_t aTypeOffset, uint16_t aRecursionDepth)
 {
   NS_ENSURE_TRUE(aRecursionDepth < MaxRecursionDepth, NS_ERROR_DOM_INDEXEDDB_DATA_ERR);
 
   static_assert(eMaxType * MaxArrayCollapse < 256,
                 "Unable to encode jsvals.");
 
-  if (JSVAL_IS_STRING(aVal)) {
+  if (aVal.isString()) {
     nsDependentJSString str;
     if (!str.init(aCx, aVal)) {
       return NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR;
     }
     EncodeString(str, aTypeOffset);
     return NS_OK;
   }
 
-  if (JSVAL_IS_INT(aVal)) {
-    EncodeNumber((double)JSVAL_TO_INT(aVal), eFloat + aTypeOffset);
-    return NS_OK;
-  }
-
-  if (JSVAL_IS_DOUBLE(aVal)) {
-    double d = JSVAL_TO_DOUBLE(aVal);
+  if (aVal.isNumber()) {
+    double d = aVal.toNumber();
     if (mozilla::IsNaN(d)) {
       return NS_ERROR_DOM_INDEXEDDB_DATA_ERR;
     }
     EncodeNumber(d, eFloat + aTypeOffset);
     return NS_OK;
   }
 
-  if (!JSVAL_IS_PRIMITIVE(aVal)) {
-    JS::Rooted<JSObject*> obj(aCx, JSVAL_TO_OBJECT(aVal));
+  if (aVal.isObject()) {
+    JS::Rooted<JSObject*> obj(aCx, &aVal.toObject());
     if (JS_IsArrayObject(aCx, obj)) {
       aTypeOffset += eMaxType;
 
       if (aTypeOffset == eMaxType * MaxArrayCollapse) {
         mBuffer.Append(aTypeOffset);
         aTypeOffset = 0;
       }
       NS_ASSERTION((aTypeOffset % eMaxType) == 0 &&
--- a/dom/indexedDB/Key.h
+++ b/dom/indexedDB/Key.h
@@ -156,21 +156,21 @@ public:
   void SetFromInteger(int64_t aInt)
   {
     mBuffer.Truncate();
     EncodeNumber(double(aInt), eFloat);
     TrimBuffer();
   }
 
   nsresult SetFromJSVal(JSContext* aCx,
-                        const JS::Value aVal)
+                        JS::Handle<JS::Value> aVal)
   {
     mBuffer.Truncate();
 
-    if (JSVAL_IS_NULL(aVal) || JSVAL_IS_VOID(aVal)) {
+    if (aVal.isNull() || aVal.isUndefined()) {
       Unset();
       return NS_OK;
     }
 
     nsresult rv = EncodeJSVal(aCx, aVal, 0);
     if (NS_FAILED(rv)) {
       Unset();
       return rv;
@@ -179,17 +179,17 @@ public:
 
     return NS_OK;
   }
 
   nsresult ToJSVal(JSContext* aCx,
                    JS::MutableHandle<JS::Value> aVal) const
   {
     if (IsUnset()) {
-      aVal.set(JSVAL_VOID);
+      aVal.setUndefined();
       return NS_OK;
     }
 
     const unsigned char* pos = BufferStart();
     nsresult rv = DecodeJSVal(pos, BufferEnd(), aCx, 0, aVal);
     NS_ENSURE_SUCCESS(rv, rv);
 
     NS_ASSERTION(pos >= BufferEnd(),
@@ -206,17 +206,17 @@ public:
     if (NS_SUCCEEDED(rv)) {
       aVal = value;
     }
     return rv;
   }
 
   nsresult AppendItem(JSContext* aCx,
                       bool aFirstOfArray,
-                      const JS::Value aVal)
+                      JS::Handle<JS::Value> aVal)
   {
     nsresult rv = EncodeJSVal(aCx, aVal, aFirstOfArray ? eMaxType : 0);
     if (NS_FAILED(rv)) {
       Unset();
       return rv;
     }
 
     return NS_OK;
@@ -300,17 +300,17 @@ private:
     while (!*end) {
       --end;
     }
 
     mBuffer.Truncate(end + 1 - mBuffer.BeginReading());
   }
 
   // Encoding functions. These append the encoded value to the end of mBuffer
-  inline nsresult EncodeJSVal(JSContext* aCx, const JS::Value aVal,
+  inline nsresult EncodeJSVal(JSContext* aCx, JS::Handle<JS::Value> aVal,
                               uint8_t aTypeOffset)
   {
     return EncodeJSValInternal(aCx, aVal, aTypeOffset, 0);
   }
   void EncodeString(const nsAString& aString, uint8_t aTypeOffset);
   void EncodeNumber(double aFloat, uint8_t aType);
 
   // Decoding functions. aPos points into mBuffer and is adjusted to point
@@ -326,17 +326,17 @@ private:
                            const unsigned char* aEnd,
                            nsString& aString);
   static double DecodeNumber(const unsigned char*& aPos,
                              const unsigned char* aEnd);
 
   nsCString mBuffer;
 
 private:
-  nsresult EncodeJSValInternal(JSContext* aCx, const JS::Value aVal,
+  nsresult EncodeJSValInternal(JSContext* aCx, JS::Handle<JS::Value> aVal,
                                uint8_t aTypeOffset, uint16_t aRecursionDepth);
 
   static nsresult DecodeJSValInternal(const unsigned char*& aPos,
                                       const unsigned char* aEnd,
                                       JSContext* aCx, uint8_t aTypeOffset,
                                       JS::MutableHandle<JS::Value> aVal, uint16_t aRecursionDepth);
 };
 
--- a/dom/ipc/TabChild.cpp
+++ b/dom/ipc/TabChild.cpp
@@ -2361,17 +2361,17 @@ TabChild::GetDefaultScale(double* aScale
 
 void
 TabChild::NotifyPainted()
 {
     // Normally we only need to notify the content process once, but with BasicCompositor
     // we need to notify content every change so that it can compute an invalidation
     // region and send that to the widget.
     if (UseDirectCompositor() &&
-        (!mNotified || mTextureFactoryIdentifier.mParentBackend == LAYERS_BASIC)) {
+        (!mNotified || mTextureFactoryIdentifier.mParentBackend == LayersBackend::LAYERS_BASIC)) {
         mRemoteFrame->SendNotifyCompositorTransaction();
         mNotified = true;
     }
 }
 
 bool
 TabChild::IsAsyncPanZoomEnabled()
 {
--- a/dom/plugins/base/nsNPAPIPlugin.cpp
+++ b/dom/plugins/base/nsNPAPIPlugin.cpp
@@ -1501,21 +1501,16 @@ bool NP_CALLBACK
   if (!obj) {
     return false;
   }
 
   obj = JS_ObjectToInnerObject(cx, obj);
   NS_ABORT_IF_FALSE(obj,
     "JS_ObjectToInnerObject should never return null with non-null input.");
 
-  // Root obj and the rval (below).
-  JS::Value vec[] = { OBJECT_TO_JSVAL(obj), JSVAL_NULL };
-  JS::AutoArrayRooter tvr(cx, ArrayLength(vec), vec);
-  JS::Value *rval = &vec[1];
-
   if (result) {
     // Initialize the out param to void
     VOID_TO_NPVARIANT(*result);
   }
 
   if (!script || !script->UTF8Length || !script->UTF8Characters) {
     // Nothing to evaluate.
 
@@ -1558,22 +1553,23 @@ bool NP_CALLBACK
 
   NPN_PLUGIN_LOG(PLUGIN_LOG_NOISY,
                  ("NPN_Evaluate(npp %p, npobj %p, script <<<%s>>>) called\n",
                   npp, npobj, script->UTF8Characters));
 
   JS::CompileOptions options(cx);
   options.setFileAndLine(spec, 0)
          .setVersion(JSVERSION_DEFAULT);
+  JS::Rooted<JS::Value> rval(cx);
   nsresult rv = scx->EvaluateString(utf16script, obj, options,
                                     /* aCoerceToString = */ false,
-                                    rval);
+                                    rval.address());
 
   return NS_SUCCEEDED(rv) &&
-         (!result || JSValToNPVariant(npp, cx, *rval, result));
+         (!result || JSValToNPVariant(npp, cx, rval, result));
 }
 
 bool NP_CALLBACK
 _getproperty(NPP npp, NPObject* npobj, NPIdentifier property,
              NPVariant *result)
 {
   if (!NS_IsMainThread()) {
     NPN_PLUGIN_LOG(PLUGIN_LOG_ALWAYS,("NPN_getproperty called from the wrong thread\n"));
--- a/dom/plugins/base/nsPluginInstanceOwner.cpp
+++ b/dom/plugins/base/nsPluginInstanceOwner.cpp
@@ -2502,17 +2502,17 @@ void nsPluginInstanceOwner::Paint(gfxCon
 #ifdef ANP_BITMAP_DRAWING_MODEL
   static nsRefPtr<gfxImageSurface> pluginSurface;
 
   if (pluginSurface == nullptr ||
       aFrameRect.width  != pluginSurface->Width() ||
       aFrameRect.height != pluginSurface->Height()) {
 
     pluginSurface = new gfxImageSurface(gfxIntSize(aFrameRect.width, aFrameRect.height), 
-                                        gfxImageFormatARGB32);
+                                        gfxImageFormat::ARGB32);
     if (!pluginSurface)
       return;
   }
 
   // Clears buffer.  I think this is needed.
   nsRefPtr<gfxContext> ctx = new gfxContext(pluginSurface);
   ctx->SetOperator(gfxContext::OPERATOR_CLEAR);
   ctx->Paint();
--- a/dom/plugins/ipc/PluginInstanceChild.cpp
+++ b/dom/plugins/ipc/PluginInstanceChild.cpp
@@ -132,17 +132,17 @@ PluginInstanceChild::PluginInstanceChild
 #endif
     , mLayersRendering(false)
 #ifdef XP_WIN
     , mCurrentSurfaceActor(nullptr)
     , mBackSurfaceActor(nullptr)
 #endif
     , mAccumulatedInvalidRect(0,0,0,0)
     , mIsTransparent(false)
-    , mSurfaceType(gfxSurfaceTypeMax)
+    , mSurfaceType(gfxSurfaceType::Max)
     , mCurrentInvalidateTask(nullptr)
     , mCurrentAsyncSetWindowTask(nullptr)
     , mPendingPluginCall(false)
     , mDoAlphaExtraction(false)
     , mHasPainted(false)
     , mSurfaceDifferenceRect(0,0,0,0)
 {
     memset(&mWindow, 0, sizeof(mWindow));
@@ -2768,36 +2768,36 @@ static inline gfxRect
 GfxFromNsRect(const nsIntRect& aRect)
 {
     return gfxRect(aRect.x, aRect.y, aRect.width, aRect.height);
 }
 
 bool
 PluginInstanceChild::CreateOptSurface(void)
 {
-    NS_ABORT_IF_FALSE(mSurfaceType != gfxSurfaceTypeMax,
+    NS_ABORT_IF_FALSE(mSurfaceType != gfxSurfaceType::Max,
                       "Need a valid surface type here");
     NS_ASSERTION(!mCurrentSurface, "mCurrentSurfaceActor can get out of sync.");
 
     nsRefPtr<gfxASurface> retsurf;
     // Use an opaque surface unless we're transparent and *don't* have
     // a background to source from.
     gfxImageFormat format =
-        (mIsTransparent && !mBackground) ? gfxImageFormatARGB32 :
-                                           gfxImageFormatRGB24;
+        (mIsTransparent && !mBackground) ? gfxImageFormat::ARGB32 :
+                                           gfxImageFormat::RGB24;
 
 #ifdef MOZ_X11
     Display* dpy = mWsInfo.display;
     Screen* screen = DefaultScreenOfDisplay(dpy);
-    if (format == gfxImageFormatRGB24 &&
+    if (format == gfxImageFormat::RGB24 &&
         DefaultDepth(dpy, DefaultScreen(dpy)) == 16) {
-        format = gfxImageFormatRGB16_565;
+        format = gfxImageFormat::RGB16_565;
     }
 
-    if (mSurfaceType == gfxSurfaceTypeXlib) {
+    if (mSurfaceType == gfxSurfaceType::Xlib) {
         if (!mIsTransparent  || mBackground) {
             Visual* defaultVisual = DefaultVisualOfScreen(screen);
             mCurrentSurface =
                 gfxXlibSurface::Create(screen, defaultVisual,
                                        gfxIntSize(mWindow.width,
                                                   mWindow.height));
             return mCurrentSurface != nullptr;
         }
@@ -2811,18 +2811,18 @@ PluginInstanceChild::CreateOptSurface(vo
             gfxXlibSurface::Create(screen, xfmt,
                                    gfxIntSize(mWindow.width,
                                               mWindow.height));
         return mCurrentSurface != nullptr;
     }
 #endif
 
 #ifdef XP_WIN
-    if (mSurfaceType == gfxSurfaceTypeWin32 ||
-        mSurfaceType == gfxSurfaceTypeD2D) {
+    if (mSurfaceType == gfxSurfaceType::Win32 ||
+        mSurfaceType == gfxSurfaceType::D2D) {
         bool willHaveTransparentPixels = mIsTransparent && !mBackground;
 
         SharedDIBSurface* s = new SharedDIBSurface();
         if (!s->Create(reinterpret_cast<HDC>(mWindow.window),
                        mWindow.width, mWindow.height,
                        willHaveTransparentPixels))
             return false;
 
@@ -2851,27 +2851,27 @@ PluginInstanceChild::MaybeCreatePlatform
     bool supportNonDefaultVisual = false;
     Screen* screen = DefaultScreenOfDisplay(mWsInfo.display);
     Visual* defaultVisual = DefaultVisualOfScreen(screen);
     Visual* visual = nullptr;
     Colormap colormap = 0;
     mDoAlphaExtraction = false;
     bool createHelperSurface = false;
 
-    if (mCurrentSurface->GetType() == gfxSurfaceTypeXlib) {
+    if (mCurrentSurface->GetType() == gfxSurfaceType::Xlib) {
         static_cast<gfxXlibSurface*>(mCurrentSurface.get())->
             GetColormapAndVisual(&colormap, &visual);
         // Create helper surface if layer surface visual not same as default
         // and we don't support non-default visual rendering
         if (!visual || (defaultVisual != visual && !supportNonDefaultVisual)) {
             createHelperSurface = true;
             visual = defaultVisual;
             mDoAlphaExtraction = mIsTransparent;
         }
-    } else if (mCurrentSurface->GetType() == gfxSurfaceTypeImage) {
+    } else if (mCurrentSurface->GetType() == gfxSurfaceType::Image) {
         // For image layer surface we should always create helper surface
         createHelperSurface = true;
         // Check if we can create helper surface with non-default visual
         visual = gfxXlibSurface::FindVisual(screen,
             static_cast<gfxImageSurface*>(mCurrentSurface.get())->Format());
         if (!visual || (defaultVisual != visual && !supportNonDefaultVisual)) {
             visual = defaultVisual;
             mDoAlphaExtraction = mIsTransparent;
@@ -2914,19 +2914,19 @@ PluginInstanceChild::EnsureCurrentBuffer
                                nsIntRect(0, 0, winSize.width, winSize.height));
     }
 
     if (mCurrentSurface) {
         gfxIntSize surfSize = mCurrentSurface->GetSize();
         if (winSize != surfSize ||
             (mBackground && !CanPaintOnBackground()) ||
             (mBackground &&
-             GFX_CONTENT_COLOR != mCurrentSurface->GetContentType()) ||
+             gfxContentType::COLOR != mCurrentSurface->GetContentType()) ||
             (!mBackground && mIsTransparent &&
-             GFX_CONTENT_COLOR == mCurrentSurface->GetContentType())) {
+             gfxContentType::COLOR == mCurrentSurface->GetContentType())) {
             // Don't try to use an old, invalid DC.
             mWindow.window = nullptr;
             ClearCurrentSurface();
             toInvalidate.UnionRect(toInvalidate,
                                    nsIntRect(0, 0, winSize.width, winSize.height));
         }
     }
 
@@ -3009,17 +3009,17 @@ PluginInstanceChild::EnsureCurrentBuffer
 void
 PluginInstanceChild::UpdateWindowAttributes(bool aForceSetWindow)
 {
     nsRefPtr<gfxASurface> curSurface = mHelperSurface ? mHelperSurface : mCurrentSurface;
     bool needWindowUpdate = aForceSetWindow;
 #ifdef MOZ_X11
     Visual* visual = nullptr;
     Colormap colormap = 0;
-    if (curSurface && curSurface->GetType() == gfxSurfaceTypeXlib) {
+    if (curSurface && curSurface->GetType() == gfxSurfaceType::Xlib) {
         static_cast<gfxXlibSurface*>(curSurface.get())->
             GetColormapAndVisual(&colormap, &visual);
         if (visual != mWsInfo.visual || colormap != mWsInfo.colormap) {
             mWsInfo.visual = visual;
             mWsInfo.colormap = colormap;
             needWindowUpdate = true;
         }
     }
@@ -3101,17 +3101,17 @@ PluginInstanceChild::UpdateWindowAttribu
 void
 PluginInstanceChild::PaintRectToPlatformSurface(const nsIntRect& aRect,
                                                 gfxASurface* aSurface)
 {
     UpdateWindowAttributes();
 
 #ifdef MOZ_X11
     {
-        NS_ASSERTION(aSurface->GetType() == gfxSurfaceTypeXlib,
+        NS_ASSERTION(aSurface->GetType() == gfxSurfaceType::Xlib,
                      "Non supported platform surface type");
 
         NPEvent pluginEvent;
         XGraphicsExposeEvent& exposeEvent = pluginEvent.xgraphicsexpose;
         exposeEvent.type = GraphicsExpose;
         exposeEvent.display = mWsInfo.display;
         exposeEvent.drawable = static_cast<gfxXlibSurface*>(aSurface)->XDrawable();
         exposeEvent.x = aRect.x;
@@ -3195,29 +3195,29 @@ PluginInstanceChild::PaintRectToSurface(
         ctx->Fill();
     }
 }
 
 void
 PluginInstanceChild::PaintRectWithAlphaExtraction(const nsIntRect& aRect,
                                                   gfxASurface* aSurface)
 {
-    NS_ABORT_IF_FALSE(aSurface->GetContentType() == GFX_CONTENT_COLOR_ALPHA,
+    NS_ABORT_IF_FALSE(aSurface->GetContentType() == gfxContentType::COLOR_ALPHA,
                       "Refusing to pointlessly recover alpha");
 
     nsIntRect rect(aRect);
     // If |aSurface| can be used to paint and can have alpha values
     // recovered directly to it, do that to save a tmp surface and
     // copy.
     bool useSurfaceSubimageForBlack = false;
-    if (gfxSurfaceTypeImage == aSurface->GetType()) {
+    if (gfxSurfaceType::Image == aSurface->GetType()) {
         gfxImageSurface* surfaceAsImage =
             static_cast<gfxImageSurface*>(aSurface);
         useSurfaceSubimageForBlack =
-            (surfaceAsImage->Format() == gfxImageFormatARGB32);
+            (surfaceAsImage->Format() == gfxImageFormat::ARGB32);
         // If we're going to use a subimage, nudge the rect so that we
         // can use optimal alpha recovery.  If we're not using a
         // subimage, the temporaries should automatically get
         // fast-path alpha recovery so we don't need to do anything.
         if (useSurfaceSubimageForBlack) {
             rect =
                 gfxAlphaRecovery::AlignRectForSubimageRecovery(aRect,
                                                                surfaceAsImage);
@@ -3226,17 +3226,17 @@ PluginInstanceChild::PaintRectWithAlphaE
 
     nsRefPtr<gfxImageSurface> whiteImage;
     nsRefPtr<gfxImageSurface> blackImage;
     gfxRect targetRect(rect.x, rect.y, rect.width, rect.height);
     gfxIntSize targetSize(rect.width, rect.height);
     gfxPoint deviceOffset = -targetRect.TopLeft();
 
     // We always use a temporary "white image"
-    whiteImage = new gfxImageSurface(targetSize, gfxImageFormatRGB24);
+    whiteImage = new gfxImageSurface(targetSize, gfxImageFormat::RGB24);
     if (whiteImage->CairoStatus()) {
         return;
     }
 
 #ifdef XP_WIN
     // On windows, we need an HDC and so can't paint directly to
     // vanilla image surfaces.  Bifurcate this painting code so that
     // we don't accidentally attempt that.
@@ -3269,17 +3269,17 @@ PluginInstanceChild::PaintRectWithAlphaE
     whiteImage->SetDeviceOffset(deviceOffset);
     PaintRectToSurface(rect, whiteImage, gfxRGBA(1.0, 1.0, 1.0));
 
     if (useSurfaceSubimageForBlack) {
         gfxImageSurface *surface = static_cast<gfxImageSurface*>(aSurface);
         blackImage = surface->GetSubimage(targetRect);
     } else {
         blackImage = new gfxImageSurface(targetSize,
-                                         gfxImageFormatARGB32);
+                                         gfxImageFormat::ARGB32);
     }
 
     // Paint onto black background
     blackImage->SetDeviceOffset(deviceOffset);
     PaintRectToSurface(rect, blackImage, gfxRGBA(0.0, 0.0, 0.0));
 #endif
 
     NS_ABORT_IF_FALSE(whiteImage && blackImage, "Didn't paint enough!");
@@ -3413,17 +3413,17 @@ PluginInstanceChild::ShowPluginFrame()
     if (!ReadbackDifferenceRect(rect)) {
         // We couldn't read back the pixels that differ between the
         // current surface and last, so we have to invalidate the
         // entire window.
         rect.SetRect(0, 0, mWindow.width, mWindow.height);
     }
 
     bool haveTransparentPixels =
-        GFX_CONTENT_COLOR_ALPHA == mCurrentSurface->GetContentType();
+        gfxContentType::COLOR_ALPHA == mCurrentSurface->GetContentType();
     PLUGIN_LOG_DEBUG(
         ("[InstanceChild][%p] Painting%s <x=%d,y=%d, w=%d,h=%d> on surface <w=%d,h=%d>",
          this, haveTransparentPixels ? " with alpha" : "",
          rect.x, rect.y, rect.width, rect.height,
          mCurrentSurface->GetSize().width, mCurrentSurface->GetSize().height));
 
     if (CanPaintOnBackground()) {
         PLUGIN_LOG_DEBUG(("  (on background)"));
@@ -3479,17 +3479,17 @@ PluginInstanceChild::ShowPluginFrame()
         mAccumulatedInvalidRect.SetRect(0, 0, mWindow.width, mWindow.height);
         return true;
     }
 
     NPRect r = { (uint16_t)rect.y, (uint16_t)rect.x,
                  (uint16_t)rect.YMost(), (uint16_t)rect.XMost() };
     SurfaceDescriptor currSurf;
 #ifdef MOZ_X11
-    if (mCurrentSurface->GetType() == gfxSurfaceTypeXlib) {
+    if (mCurrentSurface->GetType() == gfxSurfaceType::Xlib) {
         gfxXlibSurface *xsurf = static_cast<gfxXlibSurface*>(mCurrentSurface.get());
         currSurf = SurfaceDescriptorX11(xsurf);
         // Need to sync all pending x-paint requests
         // before giving drawable to another process
         XSync(mWsInfo.display, False);
     } else
 #endif
 #ifdef XP_WIN
@@ -3531,17 +3531,17 @@ bool
 PluginInstanceChild::ReadbackDifferenceRect(const nsIntRect& rect)
 {
     if (!mBackSurface)
         return false;
 
     // We can read safely from XSurface,SharedDIBSurface and Unsafe SharedMemory,
     // because PluginHost is not able to modify that surface
 #if defined(MOZ_X11)
-    if (mBackSurface->GetType() != gfxSurfaceTypeXlib &&
+    if (mBackSurface->GetType() != gfxSurfaceType::Xlib &&
         !gfxSharedImageSurface::IsSharedImage(mBackSurface))
         return false;
 #elif defined(XP_WIN)
     if (!SharedDIBSurface::IsSharedDIBSurface(mBackSurface))
         return false;
 #else
     return false;
 #endif
--- a/dom/plugins/ipc/PluginInstanceParent.cpp
+++ b/dom/plugins/ipc/PluginInstanceParent.cpp
@@ -606,17 +606,17 @@ PluginInstanceParent::RecvShow(const NPR
     }
 #endif
 
     if (mFrontSurface) {
         // This is the "old front buffer" we're about to hand back to
         // the plugin.  We might still have drawing operations
         // referencing it.
 #ifdef MOZ_X11
-        if (mFrontSurface->GetType() == gfxSurfaceTypeXlib) {
+        if (mFrontSurface->GetType() == gfxSurfaceType::Xlib) {
             // Finish with the surface and XSync here to ensure the server has
             // finished operations on the surface before the plugin starts
             // scribbling on it again, or worse, destroys it.
             mFrontSurface->Finish();
             FinishX(DefaultXDisplay());
         } else 
 #endif
         {
@@ -872,17 +872,17 @@ PluginInstanceParent::CreateBackground(c
 
 #elif defined(XP_WIN)
     // We have chosen to create an unsafe surface in which the plugin
     // can read from the region while we're writing to it.
     mBackground =
         gfxSharedImageSurface::CreateUnsafe(
             this,
             gfxIntSize(aSize.width, aSize.height),
-            gfxImageFormatRGB24);
+            gfxImageFormat::RGB24);
     return !!mBackground;
 #else
     return nullptr;
 #endif
 }
 
 void
 PluginInstanceParent::DestroyBackground()
--- a/dom/promise/Promise.cpp
+++ b/dom/promise/Promise.cpp
@@ -288,46 +288,143 @@ EnterCompartment(Maybe<JSAutoCompartment
   if (aValue.isObject()) {
     JS::Rooted<JSObject*> rooted(aCx, &aValue.toObject());
     aAc.construct(aCx, rooted);
   }
 }
 
 enum {
   SLOT_PROMISE = 0,
-  SLOT_TASK
+  SLOT_DATA
 };
 
 /* static */ bool
-Promise::JSCallback(JSContext *aCx, unsigned aArgc, JS::Value *aVp)
+Promise::JSCallback(JSContext* aCx, unsigned aArgc, JS::Value* aVp)
 {
   JS::CallArgs args = CallArgsFromVp(aArgc, aVp);
 
   JS::Rooted<JS::Value> v(aCx,
                           js::GetFunctionNativeReserved(&args.callee(),
                                                         SLOT_PROMISE));
   MOZ_ASSERT(v.isObject());
 
   Promise* promise;
   if (NS_FAILED(UNWRAP_OBJECT(Promise, &v.toObject(), promise))) {
     return Throw(aCx, NS_ERROR_UNEXPECTED);
   }
 
-  v = js::GetFunctionNativeReserved(&args.callee(), SLOT_TASK);
+  v = js::GetFunctionNativeReserved(&args.callee(), SLOT_DATA);
   PromiseCallback::Task task = static_cast<PromiseCallback::Task>(v.toInt32());
 
   if (task == PromiseCallback::Resolve) {
     promise->MaybeResolveInternal(aCx, args.get(0));
   } else {
     promise->MaybeRejectInternal(aCx, args.get(0));
   }
 
   return true;
 }
 
+/*
+ * Utilities for thenable callbacks.
+ *
+ * A thenable is a { then: function(resolve, reject) { } }.
+ * `then` is called with a resolve and reject callback pair.
+ * Since only one of these should be called at most once (first call wins), the
+ * two keep a reference to each other in SLOT_DATA. When either of them is
+ * called, the references are cleared. Further calls are ignored.
+ */
+namespace {
+void
+LinkThenableCallables(JSContext* aCx, JS::Handle<JSObject*> aResolveFunc,
+                      JS::Handle<JSObject*> aRejectFunc)
+{
+  js::SetFunctionNativeReserved(aResolveFunc, SLOT_DATA,
+                                JS::ObjectValue(*aRejectFunc));
+  js::SetFunctionNativeReserved(aRejectFunc, SLOT_DATA,
+                                JS::ObjectValue(*aResolveFunc));
+}
+
+/*
+ * Returns false if callback was already called before, otherwise breaks the
+ * links and returns true.
+ */
+bool
+MarkAsCalledIfNotCalledBefore(JSContext* aCx, JS::Handle<JSObject*> aFunc)
+{
+  JS::Value otherFuncVal = js::GetFunctionNativeReserved(aFunc, SLOT_DATA);
+
+  if (!otherFuncVal.isObject()) {
+    return false;
+  }
+
+  JSObject* otherFuncObj = &otherFuncVal.toObject();
+  MOZ_ASSERT(js::GetFunctionNativeReserved(otherFuncObj, SLOT_DATA).isObject());
+
+  // Break both references.
+  js::SetFunctionNativeReserved(aFunc, SLOT_DATA, JS::UndefinedValue());
+  js::SetFunctionNativeReserved(otherFuncObj, SLOT_DATA, JS::UndefinedValue());
+
+  return true;
+}
+
+Promise*
+GetPromise(JSContext* aCx, JS::Handle<JSObject*> aFunc)
+{
+  JS::Value promiseVal = js::GetFunctionNativeReserved(aFunc, SLOT_PROMISE);
+
+  MOZ_ASSERT(promiseVal.isObject());
+
+  Promise* promise;
+  UNWRAP_OBJECT(Promise, &promiseVal.toObject(), promise);
+  return promise;
+}
+};
+
+/*
+ * Common bits of (JSCallbackThenableResolver/JSCallbackThenableRejecter).
+ * Resolves/rejects the Promise if it is ok to do so, based on whether either of
+ * the callbacks have been called before or not.
+ */
+/* static */ bool
+Promise::ThenableResolverCommon(JSContext* aCx, uint32_t aTask,
+                                unsigned aArgc, JS::Value* aVp)
+{
+  JS::CallArgs args = CallArgsFromVp(aArgc, aVp);
+  JS::Rooted<JSObject*> thisFunc(aCx, &args.callee());
+  if (!MarkAsCalledIfNotCalledBefore(aCx, thisFunc)) {
+    // A function from this pair has been called before.
+    return true;
+  }
+
+  Promise* promise = GetPromise(aCx, thisFunc);
+  MOZ_ASSERT(promise);
+
+  if (aTask == PromiseCallback::Resolve) {
+    promise->ResolveInternal(aCx, args.get(0), SyncTask);
+  } else {
+    promise->RejectInternal(aCx, args.get(0), SyncTask);
+  }
+  return true;
+}
+
+/* static */ bool
+Promise::JSCallbackThenableResolver(JSContext* aCx,
+                                    unsigned aArgc, JS::Value* aVp)
+{
+  return ThenableResolverCommon(aCx, PromiseCallback::Resolve, aArgc, aVp);
+}
+
+/* static */ bool
+Promise::JSCallbackThenableRejecter(JSContext* aCx,
+                                    unsigned aArgc, JS::Value* aVp)
+{
+  return ThenableResolverCommon(aCx, PromiseCallback::Reject, aArgc, aVp);
+}
+
 /* static */ JSObject*
 Promise::CreateFunction(JSContext* aCx, JSObject* aParent, Promise* aPromise,
                         int32_t aTask)
 {
   JSFunction* func = js::NewFunctionWithReserved(aCx, JSCallback,
                                                  1 /* nargs */, 0 /* flags */,
                                                  aParent, nullptr);
   if (!func) {
@@ -337,17 +434,43 @@ Promise::CreateFunction(JSContext* aCx, 
   JS::Rooted<JSObject*> obj(aCx, JS_GetFunctionObject(func));
 
   JS::Rooted<JS::Value> promiseObj(aCx);
   if (!dom::WrapNewBindingObject(aCx, obj, aPromise, &promiseObj)) {
     return nullptr;
   }
 
   js::SetFunctionNativeReserved(obj, SLOT_PROMISE, promiseObj);
-  js::SetFunctionNativeReserved(obj, SLOT_TASK, JS::Int32Value(aTask));
+  js::SetFunctionNativeReserved(obj, SLOT_DATA, JS::Int32Value(aTask));
+
+  return obj;
+}
+
+/* static */ JSObject*
+Promise::CreateThenableFunction(JSContext* aCx, Promise* aPromise, uint32_t aTask)
+{
+  JSNative whichFunc =
+    aTask == PromiseCallback::Resolve ? JSCallbackThenableResolver :
+                                        JSCallbackThenableRejecter ;
+
+  JSFunction* func = js::NewFunctionWithReserved(aCx, whichFunc,
+                                                 1 /* nargs */, 0 /* flags */,
+                                                 nullptr, nullptr);
+  if (!func) {
+    return nullptr;
+  }
+
+  JS::Rooted<JSObject*> obj(aCx, JS_GetFunctionObject(func));
+
+  JS::Rooted<JS::Value> promiseObj(aCx);
+  if (!dom::WrapNewBindingObject(aCx, obj, aPromise, &promiseObj)) {
+    return nullptr;
+  }
+
+  js::SetFunctionNativeReserved(obj, SLOT_PROMISE, promiseObj);
 
   return obj;
 }
 
 /* static */ already_AddRefed<Promise>
 Promise::Constructor(const GlobalObject& aGlobal,
                      PromiseInit& aInit, ErrorResult& aRv)
 {
@@ -611,32 +734,87 @@ Promise::MaybeRejectInternal(JSContext* 
   if (mResolvePending) {
     return;
   }
 
   RejectInternal(aCx, aValue, aAsynchronous);
 }
 
 void
+Promise::HandleException(JSContext* aCx)
+{
+  JS::Rooted<JS::Value> exn(aCx);
+  if (JS_GetPendingException(aCx, &exn)) {
+    JS_ClearPendingException(aCx);
+    RejectInternal(aCx, exn, SyncTask);
+  }
+}
+
+void
 Promise::ResolveInternal(JSContext* aCx,
                          JS::Handle<JS::Value> aValue,
                          PromiseTaskSync aAsynchronous)
 {
   mResolvePending = true;
 
-  // TODO: Bug 879245 - Then-able objects
   if (aValue.isObject()) {
     JS::Rooted<JSObject*> valueObj(aCx, &aValue.toObject());
-    Promise* nextPromise;
-    nsresult rv = UNWRAP_OBJECT(Promise, valueObj, nextPromise);
+
+    // Thenables.
+    JS::Rooted<JS::Value> then(aCx);
+    if (!JS_GetProperty(aCx, valueObj, "then", &then)) {
+      HandleException(aCx);
+      return;
+    }
+
+    if (then.isObject() && JS_ObjectIsCallable(aCx, &then.toObject())) {
+      JS::Rooted<JSObject*> resolveFunc(aCx,
+        CreateThenableFunction(aCx, this, PromiseCallback::Resolve));
+
+      if (!resolveFunc) {
+        HandleException(aCx);
+        return;
+      }
+
+      JS::Rooted<JSObject*> rejectFunc(aCx,
+        CreateThenableFunction(aCx, this, PromiseCallback::Reject));
+      if (!rejectFunc) {
+        HandleException(aCx);
+        return;
+      }
+
+      LinkThenableCallables(aCx, resolveFunc, rejectFunc);
 
-    if (NS_SUCCEEDED(rv)) {
-      nsRefPtr<PromiseCallback> resolveCb = new ResolvePromiseCallback(this);
-      nsRefPtr<PromiseCallback> rejectCb = new RejectPromiseCallback(this);
-      nextPromise->AppendCallbacks(resolveCb, rejectCb);
+      JS::Rooted<JSObject*> thenObj(aCx, &then.toObject());
+      nsRefPtr<PromiseInit> thenCallback =
+        new PromiseInit(thenObj, mozilla::dom::GetIncumbentGlobal());
+
+      ErrorResult rv;
+      thenCallback->Call(valueObj, resolveFunc, rejectFunc,
+                         rv, CallbackObject::eRethrowExceptions);
+      rv.WouldReportJSException();
+
+      if (rv.IsJSException()) {
+        JS::Rooted<JS::Value> exn(aCx);
+        rv.StealJSException(aCx, &exn);
+
+        bool couldMarkAsCalled = MarkAsCalledIfNotCalledBefore(aCx, resolveFunc);
+
+        // If we could mark as called, neither of the callbacks had been called
+        // when the exception was thrown. So we can reject the Promise.
+        if (couldMarkAsCalled) {
+          Maybe<JSAutoCompartment> ac;
+          EnterCompartment(ac, aCx, exn);
+          RejectInternal(aCx, exn, Promise::SyncTask);
+        }
+        // At least one of resolveFunc or rejectFunc have been called, so ignore
+        // the exception. FIXME(nsm): This should be reported to the error
+        // console though, for debugging.
+      }
+
       return;
     }
   }
 
   // If the synchronous flag is set, process our resolve callbacks with
   // value. Otherwise, the synchronous flag is unset, queue a task to process
   // own resolve callbacks with value. Otherwise, the synchronous flag is
   // unset, queue a task to process our resolve callbacks with value.
--- a/dom/promise/Promise.h
+++ b/dom/promise/Promise.h
@@ -146,20 +146,34 @@ private:
 
   void RejectInternal(JSContext* aCx,
                       JS::Handle<JS::Value> aValue,
                       PromiseTaskSync aSync = AsyncTask);
 
   // Static methods for the PromiseInit functions.
   static bool
   JSCallback(JSContext *aCx, unsigned aArgc, JS::Value *aVp);
+
+  static bool
+  ThenableResolverCommon(JSContext* aCx, uint32_t /* PromiseCallback::Task */ aTask,
+                         unsigned aArgc, JS::Value* aVp);
+  static bool
+  JSCallbackThenableResolver(JSContext *aCx, unsigned aArgc, JS::Value *aVp);
+  static bool
+  JSCallbackThenableRejecter(JSContext *aCx, unsigned aArgc, JS::Value *aVp);
+
   static JSObject*
   CreateFunction(JSContext* aCx, JSObject* aParent, Promise* aPromise,
                 int32_t aTask);
 
+  static JSObject*
+  CreateThenableFunction(JSContext* aCx, Promise* aPromise, uint32_t aTask);
+
+  void HandleException(JSContext* aCx);
+
   nsRefPtr<nsPIDOMWindow> mWindow;
 
   nsTArray<nsRefPtr<PromiseCallback> > mResolveCallbacks;
   nsTArray<nsRefPtr<PromiseCallback> > mRejectCallbacks;
 
   JS::Heap<JS::Value> mResult;
   PromiseState mState;
   bool mTaskPending;
--- a/dom/promise/tests/test_promise.html
+++ b/dom/promise/tests/test_promise.html
@@ -461,16 +461,114 @@ function promiseResolveNestedPromise() {
   })).then(function(what) {
     is(what, 42, "Value == 42");
     runTest();
   }, function() {
     ok(false, "This should not be called");
   });
 }
 
+function promiseSimpleThenableResolve() {
+  var thenable = { then: function(resolve) { resolve(5); } };
+  var promise = new Promise(function(resolve, reject) {
+    resolve(thenable);
+  });
+
+  promise.then(function(v) {
+    ok(v === 5, "promiseSimpleThenableResolve");
+    runTest();
+  }, function(e) {
+    ok(false, "promiseSimpleThenableResolve: Should not reject");
+  });
+}
+
+function promiseSimpleThenableReject() {
+  var thenable = { then: function(resolve, reject) { reject(5); } };
+  var promise = new Promise(function(resolve, reject) {
+    resolve(thenable);
+  });
+
+  promise.then(function() {
+    ok(false, "promiseSimpleThenableReject: Should not resolve");
+    runTest();
+  }, function(e) {
+    ok(e === 5, "promiseSimpleThenableReject");
+    runTest();
+  });
+}
+
+function promiseThenableThrowsBeforeCallback() {
+  var thenable = { then: function(resolve) {
+    throw new TypeError("Hi there");
+    resolve(5);
+  }};
+
+  var promise = Promise.resolve(thenable);
+  promise.then(function(v) {
+    ok(false, "promiseThenableThrowsBeforeCallback: Should've rejected");
+    runTest();
+  }, function(e) {
+    ok(e instanceof TypeError, "promiseThenableThrowsBeforeCallback");
+    runTest();
+  });
+}
+
+function promiseThenableThrowsAfterCallback() {
+  var thenable = { then: function(resolve) {
+    resolve(5);
+    throw new TypeError("Hi there");
+  }};
+
+  var promise = Promise.resolve(thenable);
+  promise.then(function(v) {
+    ok(v === 5, "promiseThenableThrowsAfterCallback");
+    runTest();
+  }, function(e) {
+    ok(false, "promiseThenableThrowsAfterCallback: Should've resolved");
+    runTest();
+  });
+}
+
+function promiseThenableRejectThenResolve() {
+  var thenable = { then: function(resolve, reject) {
+    reject(new TypeError("Hi there"));
+    resolve(5);
+  }};
+
+  var promise = Promise.resolve(thenable);
+  promise.then(function(v) {
+    ok(false, "promiseThenableRejectThenResolve should have rejected");
+    runTest();
+  }, function(e) {
+    ok(e instanceof TypeError, "promiseThenableRejectThenResolve");
+    runTest();
+  });
+}
+
+function promiseWithThenReplaced() {
+  // Ensure that we call the 'then' on the promise and not the internal then.
+  var promise = new Promise(function(resolve, reject) {
+    resolve(5);
+  });
+
+  // Rogue `then` always rejects.
+  promise.then = function(onFulfill, onReject) {
+    onReject(new TypeError("Foo"));
+  }
+
+  var promise2 = Promise.resolve(promise);
+  promise2.then(function(v) {
+    ok(false, "promiseWithThenReplaced: Should've rejected");
+    runTest();
+  }, function(e) {
+    ok(e instanceof TypeError, "promiseWithThenReplaced");
+    runTest();
+  });
+}
+
 var tests = [ promiseResolve, promiseReject,
               promiseException, promiseGC, promiseAsync,
               promiseDoubleThen, promiseThenException,
               promiseThenCatchThen, promiseRejectThenCatchThen,
               promiseRejectThenCatchThen2,
               promiseRejectThenCatchExceptionThen,
               promiseThenCatchOrderingResolve,
               promiseThenCatchOrderingReject,
@@ -480,16 +578,22 @@ var tests = [ promiseResolve, promiseRej
               promiseResolveNestedPromise,
               promiseResolveNoArg,
               promiseRejectNoArg,
               promiseThenNoArg,
               promiseThenUndefinedResolveFunction,
               promiseThenNullResolveFunction,
               promiseCatchNoArg,
               promiseRejectNoHandler,
+              promiseSimpleThenableResolve,
+              promiseSimpleThenableReject,
+              promiseThenableThrowsBeforeCallback,
+              promiseThenableThrowsAfterCallback,
+              promiseThenableRejectThenResolve,
+              promiseWithThenReplaced,
             ];
 
 function runTest() {
   if (!tests.length) {
     SimpleTest.finish();
     return;
   }
 
--- a/dom/workers/WorkerPrivate.h
+++ b/dom/workers/WorkerPrivate.h
@@ -154,23 +154,37 @@ public:
     LoadInfo()
     : mEvalAllowed(false), mReportCSPViolations(false),
       mXHRParamsAllowed(false), mPrincipalIsSystem(false)
     { }
 
     void
     StealFrom(LoadInfo& aOther)
     {
-      mBaseURI = aOther.mBaseURI.forget();
-      mResolvedScriptURI = aOther.mResolvedScriptURI.forget();
-      mPrincipal = aOther.mPrincipal.forget();
-      mScriptContext = aOther.mScriptContext.forget();
-      mWindow = aOther.mWindow.forget();
-      mCSP = aOther.mCSP.forget();
-      mChannel = aOther.mChannel.forget();
+      MOZ_ASSERT(!mBaseURI);
+      aOther.mBaseURI.swap(mBaseURI);
+
+      MOZ_ASSERT(!mResolvedScriptURI);
+      aOther.mResolvedScriptURI.swap(mResolvedScriptURI);
+
+      MOZ_ASSERT(!mPrincipal);
+      aOther.mPrincipal.swap(mPrincipal);
+
+      MOZ_ASSERT(!mScriptContext);
+      aOther.mScriptContext.swap(mScriptContext);
+
+      MOZ_ASSERT(!mWindow);
+      aOther.mWindow.swap(mWindow);
+
+      MOZ_ASSERT(!mCSP);
+      aOther.mCSP.swap(mCSP);
+
+      MOZ_ASSERT(!mChannel);
+      aOther.mChannel.swap(mChannel);
+
       mDomain = aOther.mDomain;
       mEvalAllowed = aOther.mEvalAllowed;
       mReportCSPViolations = aOther.mReportCSPViolations;
       mXHRParamsAllowed = aOther.mXHRParamsAllowed;
       mPrincipalIsSystem = aOther.mPrincipalIsSystem;
     }
   };
 
--- a/gfx/2d/FilterNodeSoftware.cpp
+++ b/gfx/2d/FilterNodeSoftware.cpp
@@ -23,17 +23,17 @@ namespace gfx {
 static void
 DumpAsPNG(SourceSurface* aSurface)
 {
   RefPtr<DataSourceSurface> dataSource = aSurface->GetDataSurface();
   IntSize size = dataSource->GetSize();
   nsRefPtr<gfxImageSurface> imageSurface =
     new gfxImageSurface(dataSource->GetData(), gfxIntSize(size.width, size.height),
                         dataSource->Stride(),
-                        aSurface->GetFormat() == SurfaceFormat::A8 ? gfxImageFormatA8 : gfxImageFormatARGB32);
+                        aSurface->GetFormat() == SurfaceFormat::A8 ? gfxImageFormat::A8 : gfxImageFormat::ARGB32);
   imageSurface->PrintAsDataURL();
 }
 } // namespace gfx
 } // namespace mozilla
 #endif
 
 namespace mozilla {
 namespace gfx {
--- a/gfx/gl/GLContextProviderGLX.cpp
+++ b/gfx/gl/GLContextProviderGLX.cpp
@@ -252,17 +252,17 @@ GLXLibrary::EnsureInitialized()
 
 bool
 GLXLibrary::SupportsTextureFromPixmap(gfxASurface* aSurface)
 {
     if (!EnsureInitialized()) {
         return false;
     }
 
-    if (aSurface->GetType() != gfxSurfaceTypeXlib || !mUseTextureFromPixmap) {
+    if (aSurface->GetType() != gfxSurfaceType::Xlib || !mUseTextureFromPixmap) {
         return false;
     }
 
     return true;
 }
 
 GLXPixmap
 GLXLibrary::CreatePixmap(gfxASurface* aSurface)
--- a/gfx/gl/GLReadTexImageHelper.cpp
+++ b/gfx/gl/GLReadTexImageHelper.cpp
@@ -231,41 +231,41 @@ static void SwapRAndBComponents(DataSour
   }
 }
 
 void
 ReadPixelsIntoImageSurface(GLContext* gl, gfxImageSurface* dest) {
     gl->MakeCurrent();
     MOZ_ASSERT(dest->GetSize() != gfxIntSize(0, 0));
 
-    /* gfxImageFormatARGB32:
+    /* gfxImageFormat::ARGB32:
      * RGBA+UByte: be[RGBA], le[ABGR]
      * RGBA+UInt: le[RGBA]
      * BGRA+UInt: le[BGRA]
      * BGRA+UIntRev: le[ARGB]
      *
-     * gfxImageFormatRGB16_565:
+     * gfxImageFormat::RGB16_565:
      * RGB+UShort: le[rrrrrggg,gggbbbbb]
      */
-    bool hasAlpha = dest->Format() == gfxImageFormatARGB32;
+    bool hasAlpha = dest->Format() == gfxImageFormat::ARGB32;
 
     int destPixelSize;
     GLenum destFormat;
     GLenum destType;
 
     switch (dest->Format()) {
-        case gfxImageFormatRGB24: // XRGB
-        case gfxImageFormatARGB32:
+        case gfxImageFormat::RGB24: // XRGB
+        case gfxImageFormat::ARGB32:
             destPixelSize = 4;
             // Needs host (little) endian ARGB.
             destFormat = LOCAL_GL_BGRA;
             destType = LOCAL_GL_UNSIGNED_INT_8_8_8_8_REV;
             break;
 
-        case gfxImageFormatRGB16_565:
+        case gfxImageFormat::RGB16_565:
             destPixelSize = 2;
             destFormat = LOCAL_GL_RGB;
             destType = LOCAL_GL_UNSIGNED_SHORT_5_6_5_REV;
             break;
 
         default:
             MOZ_CRASH("Bad format.");
     }
@@ -374,17 +374,17 @@ ReadPixelsIntoImageSurface(GLContext* gl
         ctx.Paint();
     }
 
     // Check if GL is giving back 1.0 alpha for
     // RGBA reads to RGBA images from no-alpha buffers.
 #ifdef XP_MACOSX
     if (gl->WorkAroundDriverBugs() &&
         gl->Vendor() == gl::GLVendor::NVIDIA &&
-        dest->Format() == gfxImageFormatARGB32 &&
+        dest->Format() == gfxImageFormat::ARGB32 &&
         width && height)
     {
         GLint alphaBits = 0;
         gl->fGetIntegerv(LOCAL_GL_ALPHA_BITS, &alphaBits);
         if (!alphaBits) {
             const uint32_t alphaMask = gfxPackedPixelNoPreMultiply(0xff,0,0,0);
 
             dest->Flush();
@@ -498,17 +498,17 @@ GLReadTexImageHelper::ReadTexImage(GLuin
 
     MOZ_ASSERT(aTextureTarget == LOCAL_GL_TEXTURE_2D ||
                aTextureTarget == LOCAL_GL_TEXTURE_EXTERNAL ||
                aTextureTarget == LOCAL_GL_TEXTURE_RECTANGLE_ARB);
 
     mGL->MakeCurrent();
 
     /* Allocate resulting image surface */
-    nsRefPtr<gfxImageSurface> isurf = new gfxImageSurface(aSize, gfxImageFormatARGB32);
+    nsRefPtr<gfxImageSurface> isurf = new gfxImageSurface(aSize, gfxImageFormat::ARGB32);
     if (!isurf || isurf->CairoStatus()) {
         return nullptr;
     }
 
     GLint oldrb, oldfb, oldprog, oldTexUnit, oldTex;
     GLuint rb, fb;
 
     do {
--- a/gfx/gl/GLReadTexImageHelper.h
+++ b/gfx/gl/GLReadTexImageHelper.h
@@ -43,20 +43,20 @@ class GLReadTexImageHelper MOZ_FINAL
 
 public:
 
     GLReadTexImageHelper(GLContext* gl);
     ~GLReadTexImageHelper();
 
     /**
       * Read the image data contained in aTexture, and return it as an ImageSurface.
-      * If GL_RGBA is given as the format, a gfxImageFormatARGB32 surface is returned.
+      * If GL_RGBA is given as the format, a gfxImageFormat::ARGB32 surface is returned.
       * Not implemented yet:
-      * If GL_RGB is given as the format, a gfxImageFormatRGB24 surface is returned.
-      * If GL_LUMINANCE is given as the format, a gfxImageFormatA8 surface is returned.
+      * If GL_RGB is given as the format, a gfxImageFormat::RGB24 surface is returned.
+      * If GL_LUMINANCE is given as the format, a gfxImageFormat::A8 surface is returned.
       *
       * THIS IS EXPENSIVE.  It is ridiculously expensive.  Only do this
       * if you absolutely positively must, and never in any performance
       * critical path.
       *
       * NOTE: aShaderProgram is really mozilla::layers::ShaderProgramType. It is
       * passed as int to eliminate including LayerManagerOGLProgram.h here.
       */
--- a/gfx/gl/GLScreenBuffer.cpp
+++ b/gfx/gl/GLScreenBuffer.cpp
@@ -479,18 +479,18 @@ GLScreenBuffer::CreateRead(SharedSurface
 }
 
 
 void
 GLScreenBuffer::Readback(SharedSurface_GL* src, gfxImageSurface* dest)
 {
     MOZ_ASSERT(src && dest);
     MOZ_ASSERT(ToIntSize(dest->GetSize()) == src->Size());
-    MOZ_ASSERT(dest->Format() == (src->HasAlpha() ? gfxImageFormatARGB32
-                                                  : gfxImageFormatRGB24));
+    MOZ_ASSERT(dest->Format() == (src->HasAlpha() ? gfxImageFormat::ARGB32
+                                                  : gfxImageFormat::RGB24));
 
     mGL->MakeCurrent();
 
     bool needsSwap = src != SharedSurf();
     if (needsSwap) {
         SharedSurf()->UnlockProd();
         src->LockProd();
     }
--- a/gfx/gl/GLTextureImage.cpp
+++ b/gfx/gl/GLTextureImage.cpp
@@ -140,18 +140,18 @@ BasicTextureImage::BeginUpdate(nsIntRegi
 
     nsIntRect rgnSize = mUpdateRegion.GetBounds();
     if (!nsIntRect(nsIntPoint(0, 0), gfx::ThebesIntSize(mSize)).Contains(rgnSize)) {
         NS_ERROR("update outside of image");
         return nullptr;
     }
 
     ImageFormat format =
-        (GetContentType() == GFX_CONTENT_COLOR) ?
-        gfxImageFormatRGB24 : gfxImageFormatARGB32;
+        (GetContentType() == gfxContentType::COLOR) ?
+        gfxImageFormat::RGB24 : gfxImageFormat::ARGB32;
     mUpdateSurface =
         GetSurfaceForUpdate(gfxIntSize(rgnSize.width, rgnSize.height), format);
 
     if (!mUpdateSurface || mUpdateSurface->CairoStatus()) {
         mUpdateSurface = nullptr;
         return nullptr;
     }
 
@@ -283,17 +283,17 @@ TextureImage::TextureImage(const gfx::In
 {}
 
 BasicTextureImage::BasicTextureImage(GLuint aTexture,
                                      const nsIntSize& aSize,
                                      GLenum aWrapMode,
                                      ContentType aContentType,
                                      GLContext* aContext,
                                      TextureImage::Flags aFlags /* = TextureImage::NoFlags */,
-                                     TextureImage::ImageFormat aImageFormat /* = gfxImageFormatUnknown */)
+                                     TextureImage::ImageFormat aImageFormat /* = gfxImageFormat::Unknown */)
     : TextureImage(aSize, aWrapMode, aContentType, aFlags, aImageFormat)
     , mTexture(aTexture)
     , mTextureState(Created)
     , mGLContext(aContext)
     , mUpdateOffset(0, 0)
 {
 }
 
@@ -504,18 +504,18 @@ TiledTextureImage::BeginUpdate(nsIntRegi
     // Get the real updated region, taking into account the capabilities of
     // each TextureImage tile
     GetUpdateRegion(aRegion);
     mUpdateRegion = aRegion;
     bounds = aRegion.GetBounds();
 
     // update covers multiple Images - create a temp surface to paint in
     gfxImageFormat format =
-        (GetContentType() == GFX_CONTENT_COLOR) ?
-        gfxImageFormatRGB24 : gfxImageFormatARGB32;
+        (GetContentType() == gfxContentType::COLOR) ?
+        gfxImageFormat::RGB24 : gfxImageFormat::ARGB32;
     mUpdateSurface = gfxPlatform::GetPlatform()->
         CreateOffscreenSurface(gfxIntSize(bounds.width, bounds.height), gfxASurface::ContentFromFormat(format));
     mUpdateSurface->SetDeviceOffset(gfxPoint(-bounds.x, -bounds.y));
 
     return mUpdateSurface;
 }
 
 void
--- a/gfx/gl/GLTextureImage.h
+++ b/gfx/gl/GLTextureImage.h
@@ -217,17 +217,17 @@ protected:
      * After the ctor, the TextureImage is invalid.  Implementations
      * must allocate resources successfully before returning the new
      * TextureImage from GLContext::CreateTextureImage().  That is,
      * clients must not be given partially-constructed TextureImages.
      */
     TextureImage(const nsIntSize& aSize,
                  GLenum aWrapMode, ContentType aContentType,
                  Flags aFlags = NoFlags,
-                 ImageFormat aImageFormat = gfxImageFormatUnknown)
+                 ImageFormat aImageFormat = gfxImageFormat::Unknown)
         : mSize(aSize.ToIntSize())
         , mWrapMode(aWrapMode)
         , mContentType(aContentType)
         , mImageFormat(aImageFormat)
         , mFilter(GraphicsFilter::FILTER_GOOD)
         , mFlags(aFlags)
     {}
 
@@ -263,24 +263,24 @@ public:
     virtual ~BasicTextureImage();
 
     BasicTextureImage(GLuint aTexture,
                       const nsIntSize& aSize,
                       GLenum aWrapMode,
                       ContentType aContentType,
                       GLContext* aContext,
                       TextureImage::Flags aFlags = TextureImage::NoFlags,
-                      TextureImage::ImageFormat aImageFormat = gfxImageFormatUnknown);
+                      TextureImage::ImageFormat aImageFormat = gfxImageFormat::Unknown);
     BasicTextureImage(GLuint aTexture,
                       const gfx::IntSize& aSize,
                       GLenum aWrapMode,
                       ContentType aContentType,
                       GLContext* aContext,
                       TextureImage::Flags aFlags = TextureImage::NoFlags,
-                      TextureImage::ImageFormat aImageFormat = gfxImageFormatUnknown);
+                      TextureImage::ImageFormat aImageFormat = gfxImageFormat::Unknown);
 
     virtual void BindTexture(GLenum aTextureUnit);
 
     virtual gfxASurface* BeginUpdate(nsIntRegion& aRegion);
     virtual void GetUpdateRegion(nsIntRegion& aForRegion);
     virtual void EndUpdate();
     virtual bool DirectUpdate(gfxASurface* aSurf, const nsIntRegion& aRegion, const nsIntPoint& aFrom = nsIntPoint(0,0));
     virtual GLuint GetTextureID() { return mTexture; }
@@ -321,17 +321,17 @@ protected:
 class TiledTextureImage
     : public TextureImage
 {
 public:
     TiledTextureImage(GLContext* aGL,
                       gfx::IntSize aSize,
                       TextureImage::ContentType,
                       TextureImage::Flags aFlags = TextureImage::NoFlags,
-                      TextureImage::ImageFormat aImageFormat = gfxImageFormatUnknown);
+                      TextureImage::ImageFormat aImageFormat = gfxImageFormat::Unknown);
     ~TiledTextureImage();
     void DumpDiv();
     virtual gfxASurface* BeginUpdate(nsIntRegion& aRegion);
     virtual void GetUpdateRegion(nsIntRegion& aForRegion);
     virtual void EndUpdate();
     virtual void Resize(const gfx::IntSize& aSize);
     virtual uint32_t GetTileCount();
     virtual void BeginTileIteration();
@@ -372,17 +372,17 @@ protected:
  * In doubt, use GLContext::CreateTextureImage instead.
  */
 already_AddRefed<TextureImage>
 CreateBasicTextureImage(GLContext* aGL,
                         const gfx::IntSize& aSize,
                         TextureImage::ContentType aContentType,
                         GLenum aWrapMode,
                         TextureImage::Flags aFlags,
-                        TextureImage::ImageFormat aImageFormat = gfxImageFormatUnknown);
+                        TextureImage::ImageFormat aImageFormat = gfxImageFormat::Unknown);
 
 /**
   * Return a valid, allocated TextureImage of |aSize| with
   * |aContentType|.  If |aContentType| is COLOR, |aImageFormat| can be used
   * to hint at the preferred RGB format, however it is not necessarily
   * respected.  The TextureImage's texture is configured to use
   * |aWrapMode| (usually GL_CLAMP_TO_EDGE or GL_REPEAT) and by
   * default, GL_LINEAR filtering.  Specify
@@ -396,14 +396,14 @@ CreateBasicTextureImage(GLContext* aGL,
   * crashy) behavior.
   */
 already_AddRefed<TextureImage>
 CreateTextureImage(GLContext* gl,
                    const gfx::IntSize& aSize,
                    TextureImage::ContentType aContentType,
                    GLenum aWrapMode,
                    TextureImage::Flags aFlags = TextureImage::NoFlags,
-                   TextureImage::ImageFormat aImageFormat = gfxImageFormatUnknown);
+                   TextureImage::ImageFormat aImageFormat = gfxImageFormat::Unknown);
 
 } // namespace gl
 } // namespace mozilla
 
 #endif /* GLTEXTUREIMAGE_H_ */
--- a/gfx/gl/GLUploadHelpers.cpp
+++ b/gfx/gl/GLUploadHelpers.cpp
@@ -26,25 +26,25 @@ DataOffset(const nsIntPoint &aPoint, int
   return data;
 }
 
 static gfxImageFormat
 ImageFormatForSurfaceFormat(gfx::SurfaceFormat aFormat)
 {
     switch (aFormat) {
         case gfx::SurfaceFormat::B8G8R8A8:
-            return gfxImageFormatARGB32;
+            return gfxImageFormat::ARGB32;
         case gfx::SurfaceFormat::B8G8R8X8:
-            return gfxImageFormatRGB24;
+            return gfxImageFormat::RGB24;
         case gfx::SurfaceFormat::R5G6B5:
-            return gfxImageFormatRGB16_565;
+            return gfxImageFormat::RGB16_565;
         case gfx::SurfaceFormat::A8:
-            return gfxImageFormatA8;
+            return gfxImageFormat::A8;
         default:
-            return gfxImageFormatUnknown;
+            return gfxImageFormat::Unknown;
     }
 }
 
 static GLint GetAddressAlignment(ptrdiff_t aAddress)
 {
     if (!(aAddress & 0x7)) {
        return 8;
     } else if (!(aAddress & 0x3)) {
@@ -412,48 +412,48 @@ UploadImageDataToTexture(GLContext* gl,
     GLenum internalFormat;
     GLenum type;
     int32_t pixelSize = gfxASurface::BytePerPixelFromFormat(aFormat);
     SurfaceFormat surfaceFormat;
 
     MOZ_ASSERT(gl->GetPreferredARGB32Format() == LOCAL_GL_BGRA ||
                gl->GetPreferredARGB32Format() == LOCAL_GL_RGBA);
     switch (aFormat) {
-        case gfxImageFormatARGB32:
+        case gfxImageFormat::ARGB32:
             if (gl->GetPreferredARGB32Format() == LOCAL_GL_BGRA) {
               format = LOCAL_GL_BGRA;
               surfaceFormat = gfx::SurfaceFormat::R8G8B8A8;
               type = LOCAL_GL_UNSIGNED_INT_8_8_8_8_REV;
             } else {
               format = LOCAL_GL_RGBA;
               surfaceFormat = gfx::SurfaceFormat::B8G8R8A8;
               type = LOCAL_GL_UNSIGNED_BYTE;
             }
             internalFormat = LOCAL_GL_RGBA;
             break;
-        case gfxImageFormatRGB24:
+        case gfxImageFormat::RGB24:
             // Treat RGB24 surfaces as RGBA32 except for the surface
             // format used.
             if (gl->GetPreferredARGB32Format() == LOCAL_GL_BGRA) {
               format = LOCAL_GL_BGRA;
               surfaceFormat = gfx::SurfaceFormat::R8G8B8X8;
               type = LOCAL_GL_UNSIGNED_INT_8_8_8_8_REV;
             } else {
               format = LOCAL_GL_RGBA;
               surfaceFormat = gfx::SurfaceFormat::B8G8R8X8;
               type = LOCAL_GL_UNSIGNED_BYTE;
             }
             internalFormat = LOCAL_GL_RGBA;
             break;
-        case gfxImageFormatRGB16_565:
+        case gfxImageFormat::RGB16_565:
             internalFormat = format = LOCAL_GL_RGB;
             type = LOCAL_GL_UNSIGNED_SHORT_5_6_5;
             surfaceFormat = gfx::SurfaceFormat::R5G6B5;
             break;
-        case gfxImageFormatA8:
+        case gfxImageFormat::A8:
             internalFormat = format = LOCAL_GL_LUMINANCE;
             type = LOCAL_GL_UNSIGNED_BYTE;
             // We don't have a specific luminance shader
             surfaceFormat = gfx::SurfaceFormat::A8;
             break;
         default:
             NS_ASSERTION(false, "Unhandled image surface format!");
             format = 0;
@@ -521,25 +521,25 @@ UploadSurfaceToTexture(GLContext* gl,
                        GLenum aTextureUnit,
                        GLenum aTextureTarget)
 {
 
     nsRefPtr<gfxImageSurface> imageSurface = aSurface->GetAsImageSurface();
     unsigned char* data = nullptr;
 
     if (!imageSurface ||
-        (imageSurface->Format() != gfxImageFormatARGB32 &&
-         imageSurface->Format() != gfxImageFormatRGB24 &&
-         imageSurface->Format() != gfxImageFormatRGB16_565 &&
-         imageSurface->Format() != gfxImageFormatA8)) {
+        (imageSurface->Format() != gfxImageFormat::ARGB32 &&
+         imageSurface->Format() != gfxImageFormat::RGB24 &&
+         imageSurface->Format() != gfxImageFormat::RGB16_565 &&
+         imageSurface->Format() != gfxImageFormat::A8)) {
         // We can't get suitable pixel data for the surface, make a copy
         nsIntRect bounds = aDstRegion.GetBounds();
         imageSurface =
           new gfxImageSurface(gfxIntSize(bounds.width, bounds.height),
-                              gfxImageFormatARGB32);
+                              gfxImageFormat::ARGB32);
 
         nsRefPtr<gfxContext> context = new gfxContext(imageSurface);
 
         context->Translate(-gfxPoint(aSrcPoint.x, aSrcPoint.y));
         context->SetSource(aSurface);
         context->Paint();
         data = imageSurface->Data();
         NS_ASSERTION(!aPixelBuffer,
--- a/gfx/gl/SharedSurfaceGralloc.cpp
+++ b/gfx/gl/SharedSurfaceGralloc.cpp
@@ -69,18 +69,18 @@ SharedSurface_Gralloc::Create(GLContext*
     GLLibraryEGL* egl = &sEGLLibrary;
     MOZ_ASSERT(egl);
 
     DEBUG_PRINT("SharedSurface_Gralloc::Create -------\n");
 
     if (!HasExtensions(egl, prodGL))
         return nullptr;
 
-    gfxContentType type = hasAlpha ? GFX_CONTENT_COLOR_ALPHA
-                                   : GFX_CONTENT_COLOR;
+    gfxContentType type = hasAlpha ? gfxContentType::COLOR_ALPHA
+                                   : gfxContentType::COLOR;
 
     gfxImageFormat format
       = gfxPlatform::GetPlatform()->OptimalFormatForContent(type);
 
     GrallocTextureClientOGL* grallocTC =
       new GrallocTextureClientOGL(
           allocator,
           gfx::ImageFormatToSurfaceFormat(format),
--- a/gfx/gl/TextureImageCGL.h
+++ b/gfx/gl/TextureImageCGL.h
@@ -21,17 +21,17 @@ class TextureImageCGL : public BasicText
 public:
 
     TextureImageCGL(GLuint aTexture,
                     const nsIntSize& aSize,
                     GLenum aWrapMode,
                     ContentType aContentType,
                     GLContext* aContext,
                     TextureImage::Flags aFlags = TextureImage::NoFlags,
-                    TextureImage::ImageFormat aImageFormat = gfxImageFormatUnknown);
+                    TextureImage::ImageFormat aImageFormat = gfxImageFormat::Unknown);
 
     ~TextureImageCGL();
 
 protected:
     already_AddRefed<gfxASurface>
     GetSurfaceForUpdate(const gfxIntSize& aSize, ImageFormat aFmt);
 
     bool FinishedSurfaceUpdate();
--- a/gfx/gl/TextureImageEGL.cpp
+++ b/gfx/gl/TextureImageEGL.cpp
@@ -13,39 +13,39 @@
 
 namespace mozilla {
 namespace gl {
 
 static GLenum
 GLFormatForImage(gfxImageFormat aFormat)
 {
     switch (aFormat) {
-    case gfxImageFormatARGB32:
-    case gfxImageFormatRGB24:
+    case gfxImageFormat::ARGB32:
+    case gfxImageFormat::RGB24:
         // Thebes only supports RGBX, not packed RGB.
         return LOCAL_GL_RGBA;
-    case gfxImageFormatRGB16_565:
+    case gfxImageFormat::RGB16_565:
         return LOCAL_GL_RGB;
-    case gfxImageFormatA8:
+    case gfxImageFormat::A8:
         return LOCAL_GL_LUMINANCE;
     default:
         NS_WARNING("Unknown GL format for Image format");
     }
     return 0;
 }
 
 static GLenum
 GLTypeForImage(gfxImageFormat aFormat)
 {
     switch (aFormat) {
-    case gfxImageFormatARGB32:
-    case gfxImageFormatRGB24:
-    case gfxImageFormatA8:
+    case gfxImageFormat::ARGB32:
+    case gfxImageFormat::RGB24:
+    case gfxImageFormat::A8:
         return LOCAL_GL_UNSIGNED_BYTE;
-    case gfxImageFormatRGB16_565:
+    case gfxImageFormat::RGB16_565:
         return LOCAL_GL_UNSIGNED_SHORT_5_6_5;
     default:
         NS_WARNING("Unknown GL format for Image format");
     }
     return 0;
 }
 
 TextureImageEGL::TextureImageEGL(GLuint aTexture,
@@ -61,23 +61,23 @@ TextureImageEGL::TextureImageEGL(GLuint 
     , mUpdateFormat(aImageFormat)
     , mEGLImage(nullptr)
     , mTexture(aTexture)
     , mSurface(nullptr)
     , mConfig(nullptr)
     , mTextureState(aTextureState)
     , mBound(false)
 {
-    if (mUpdateFormat == gfxImageFormatUnknown) {
+    if (mUpdateFormat == gfxImageFormat::Unknown) {
         mUpdateFormat = gfxPlatform::GetPlatform()->OptimalFormatForContent(GetContentType());
     }
 
-    if (mUpdateFormat == gfxImageFormatRGB16_565) {
+    if (mUpdateFormat == gfxImageFormat::RGB16_565) {
         mTextureFormat = gfx::SurfaceFormat::R8G8B8X8;
-    } else if (mUpdateFormat == gfxImageFormatRGB24) {
+    } else if (mUpdateFormat == gfxImageFormat::RGB24) {
         // RGB24 means really RGBX for Thebes, which means we have to
         // use the right shader and ignore the uninitialized alpha
         // value.
         mTextureFormat = gfx::SurfaceFormat::B8G8R8X8;
     } else {
         mTextureFormat = gfx::SurfaceFormat::B8G8R8A8;
     }
 }
@@ -154,17 +154,17 @@ TextureImageEGL::EndUpdate()
     // Undo the device offset that BeginUpdate set; doesn't much
     // matter for us here, but important if we ever do anything
     // directly with the surface.
     mUpdateSurface->SetDeviceOffset(gfxPoint(0, 0));
 
     nsRefPtr<gfxImageSurface> uploadImage = nullptr;
     gfxIntSize updateSize(mUpdateRect.width, mUpdateRect.height);
 
-    NS_ASSERTION(mUpdateSurface->GetType() == gfxSurfaceTypeImage &&
+    NS_ASSERTION(mUpdateSurface->GetType() == gfxSurfaceType::Image &&
                   mUpdateSurface->GetSize() == updateSize,
                   "Upload image isn't an image surface when one is expected, or is wrong size!");
 
     uploadImage = static_cast<gfxImageSurface*>(mUpdateSurface.get());
 
     if (!uploadImage) {
         return;
     }
--- a/gfx/gl/TextureImageEGL.h
+++ b/gfx/gl/TextureImageEGL.h
@@ -17,17 +17,17 @@ class TextureImageEGL
 public:
     TextureImageEGL(GLuint aTexture,
                     const nsIntSize& aSize,
                     GLenum aWrapMode,
                     ContentType aContentType,
                     GLContext* aContext,
                     Flags aFlags = TextureImage::NoFlags,
                     TextureState aTextureState = Created,
-                    TextureImage::ImageFormat aImageFormat = gfxImageFormatUnknown);
+                    TextureImage::ImageFormat aImageFormat = gfxImageFormat::Unknown);
 
     virtual ~TextureImageEGL();
 
     virtual void GetUpdateRegion(nsIntRegion& aForRegion);
 
     virtual gfxASurface* BeginUpdate(nsIntRegion& aRegion);
 
     virtual void EndUpdate();
--- a/gfx/ipc/GfxMessageUtils.h
+++ b/gfx/ipc/GfxMessageUtils.h
@@ -184,56 +184,64 @@ struct ParamTraits<gfx3DMatrix>
             Rd(_31) && Rd(_32) && Rd(_33) && Rd(_34) &&
             Rd(_41) && Rd(_42) && Rd(_43) && Rd(_44));
 #undef Rd
   }
 };
 
 template <>
 struct ParamTraits<gfxContentType>
-  : public EnumSerializer<gfxContentType,
-                          GFX_CONTENT_COLOR,
-                          GFX_CONTENT_SENTINEL>
+  : public TypedEnumSerializer<gfxContentType,
+                               gfxContentType::COLOR,
+                               gfxContentType::SENTINEL>
 {};
 
 template <>
 struct ParamTraits<gfxSurfaceType>
-  : public EnumSerializer<gfxSurfaceType,
-                          gfxSurfaceTypeImage,
-                          gfxSurfaceTypeMax>
+  : public TypedEnumSerializer<gfxSurfaceType,
+                               gfxSurfaceType::Image,
+                               gfxSurfaceType::Max>
 {};
 
 template <>
 struct ParamTraits<mozilla::GraphicsFilterType>
   : public EnumSerializer<mozilla::GraphicsFilterType,
                           GraphicsFilter::FILTER_FAST,
                           GraphicsFilter::FILTER_SENTINEL>
 {};
 
 template <>
 struct ParamTraits<mozilla::layers::LayersBackend>
-  : public EnumSerializer<mozilla::layers::LayersBackend,
-                          mozilla::layers::LAYERS_NONE,
-                          mozilla::layers::LAYERS_LAST>
+  : public TypedEnumSerializer<mozilla::layers::LayersBackend,
+                               mozilla::layers::LayersBackend::LAYERS_NONE,
+                               mozilla::layers::LayersBackend::LAYERS_LAST>
 {};
 
 template <>
 struct ParamTraits<mozilla::layers::ScaleMode>
-  : public EnumSerializer<mozilla::layers::ScaleMode,
-                          mozilla::layers::SCALE_NONE,
-                          mozilla::layers::SCALE_SENTINEL>
+  : public TypedEnumSerializer<mozilla::layers::ScaleMode,
+                               mozilla::layers::ScaleMode::SCALE_NONE,
+                               mozilla::layers::ScaleMode::SENTINEL>
 {};
 
 template <>
+struct ParamTraits<gfxImageFormat>
+  : public TypedEnumSerializer<gfxImageFormat,
+                               gfxImageFormat::ARGB32,
+                               gfxImageFormat::Unknown>
+{};
+
+/*
+template <>
 struct ParamTraits<mozilla::PixelFormat>
   : public EnumSerializer<mozilla::PixelFormat,
-                          gfxImageFormatARGB32,
-                          gfxImageFormatUnknown>
+                          gfxImageFormat::ARGB32,
+                          gfxImageFormat::Unknown>
 {};
-
+*/
 
 template<>
 struct ParamTraits<gfxRGBA>
 {
   typedef gfxRGBA paramType;
 
   static void Write(Message* msg, const paramType& param)
   {
--- a/gfx/ipc/SharedDIBSurface.cpp
+++ b/gfx/ipc/SharedDIBSurface.cpp
@@ -40,26 +40,26 @@ SharedDIBSurface::Attach(Handle aHandle,
 
 void
 SharedDIBSurface::InitSurface(uint32_t aWidth, uint32_t aHeight,
                               bool aTransparent)
 {
   long stride = long(aWidth * kBytesPerPixel);
   unsigned char* data = reinterpret_cast<unsigned char*>(mSharedDIB.GetBits());
 
-  gfxImageFormat format = aTransparent ? gfxImageFormatARGB32 : gfxImageFormatRGB24;
+  gfxImageFormat format = aTransparent ? gfxImageFormat::ARGB32 : gfxImageFormat::RGB24;
 
   gfxImageSurface::InitWithData(data, gfxIntSize(aWidth, aHeight),
                                 stride, format);
 
   cairo_surface_set_user_data(mSurface, &SHAREDDIB_KEY, this, nullptr);
 }
 
 bool
 SharedDIBSurface::IsSharedDIBSurface(gfxASurface* aSurface)
 {
   return aSurface &&
-    aSurface->GetType() == gfxSurfaceTypeImage &&
+    aSurface->GetType() == gfxSurfaceType::Image &&
     aSurface->GetData(&SHAREDDIB_KEY);
 }
 
 } // namespace gfx
 } // namespace mozilla
--- a/gfx/layers/Compositor.cpp
+++ b/gfx/layers/Compositor.cpp
@@ -12,17 +12,17 @@
 
 namespace mozilla {
 namespace gfx {
 class Matrix4x4;
 }
 
 namespace layers {
 
-/* static */ LayersBackend Compositor::sBackend = LAYERS_NONE;
+/* static */ LayersBackend Compositor::sBackend = LayersBackend::LAYERS_NONE;
 /* static */ LayersBackend
 Compositor::GetBackend()
 {
   AssertOnCompositorThread();
   return sBackend;
 }
 
 /* static */ void
--- a/gfx/layers/CompositorTypes.h
+++ b/gfx/layers/CompositorTypes.h
@@ -201,17 +201,17 @@ enum DeprecatedTextureHostFlags
 struct TextureFactoryIdentifier
 {
   LayersBackend mParentBackend;
   GeckoProcessType mParentProcessId;
   int32_t mMaxTextureSize;
   bool mSupportsTextureBlitting;
   bool mSupportsPartialUploads;
 
-  TextureFactoryIdentifier(LayersBackend aLayersBackend = LAYERS_NONE,
+  TextureFactoryIdentifier(LayersBackend aLayersBackend = LayersBackend::LAYERS_NONE,
                            GeckoProcessType aParentProcessId = GeckoProcessType_Default,
                            int32_t aMaxTextureSize = 0,
                            bool aSupportsTextureBlitting = false,
                            bool aSupportsPartialUploads = false)
     : mParentBackend(aLayersBackend)
     , mParentProcessId(aParentProcessId)
     , mMaxTextureSize(aMaxTextureSize)
     , mSupportsTextureBlitting(aSupportsTextureBlitting)
--- a/gfx/layers/CopyableCanvasLayer.cpp
+++ b/gfx/layers/CopyableCanvasLayer.cpp
@@ -104,18 +104,18 @@ CopyableCanvasLayer::UpdateSurface(gfxAS
     SharedSurface* sharedSurf = mGLContext->RequestFrame();
     if (!sharedSurf) {
       NS_WARNING("Null frame received.");
       return;
     }
 
     IntSize readSize(sharedSurf->Size());
     gfxImageFormat format = (GetContentFlags() & CONTENT_OPAQUE)
-                            ? gfxImageFormatRGB24
-                            : gfxImageFormatARGB32;
+                            ? gfxImageFormat::RGB24
+                            : gfxImageFormat::ARGB32;
 
     if (aDestSurface) {
       resultSurf = aDestSurface;
     } else {
       resultSurf = GetTempSurface(readSize, format);
     }
     MOZ_ASSERT(resultSurf);
     if (resultSurf->CairoStatus() != 0) {
--- a/gfx/layers/D3D9SurfaceImage.cpp
+++ b/gfx/layers/D3D9SurfaceImage.cpp
@@ -118,17 +118,17 @@ D3D9SurfaceImage::GetSize()
 
 already_AddRefed<gfxASurface>
 D3D9SurfaceImage::DeprecatedGetAsSurface()
 {
   NS_ENSURE_TRUE(mTexture, nullptr);
 
   HRESULT hr;
   nsRefPtr<gfxImageSurface> surface =
-    new gfxImageSurface(gfx::ThebesIntSize(mSize), gfxImageFormatRGB24);
+    new gfxImageSurface(gfx::ThebesIntSize(mSize), gfxImageFormat::RGB24);
 
   if (!surface->CairoSurface() || surface->CairoStatus()) {
     NS_WARNING("Failed to created Cairo image surface for D3D9SurfaceImage.");
     return nullptr;
   }
 
   // Ensure that the texture is ready to be used.
   EnsureSynchronized();
--- a/gfx/layers/GrallocImages.cpp
+++ b/gfx/layers/GrallocImages.cpp
@@ -228,17 +228,17 @@ GrallocImage::DeprecatedGetAsSurface()
   }
 
   if (!omxFormat) {
     NS_WARNING("Unknown color format");
     return nullptr;
   }
 
   nsRefPtr<gfxImageSurface> imageSurface =
-    new gfxImageSurface(gfx::ThebesIntSize(GetSize()), gfxImageFormatRGB16_565);
+    new gfxImageSurface(gfx::ThebesIntSize(GetSize()), gfxImageFormat::RGB16_565);
 
   uint32_t width = GetSize().width;
   uint32_t height = GetSize().height;
 
   if (format == HAL_PIXEL_FORMAT_YCrCb_420_SP_ADRENO) {
     // The Adreno hardware decoder aligns image dimensions to a multiple of 32,
     // so we have to account for that here
     uint32_t alignedWidth = ALIGN(width, 32);
--- a/gfx/layers/ImageContainer.cpp
+++ b/gfx/layers/ImageContainer.cpp
@@ -317,18 +317,18 @@ ImageContainer::DeprecatedLockCurrentAsS
     } 
 
     if (mActiveImage->GetFormat() == REMOTE_IMAGE_BITMAP) {
       nsRefPtr<gfxImageSurface> newSurf =
         new gfxImageSurface(mRemoteData->mBitmap.mData,
                             ThebesIntSize(mRemoteData->mSize),
                             mRemoteData->mBitmap.mStride,
                             mRemoteData->mFormat == RemoteImageData::BGRX32 ?
-                                                   gfxImageFormatARGB32 :
-                                                   gfxImageFormatRGB24);
+                                                   gfxImageFormat::ARGB32 :
+                                                   gfxImageFormat::RGB24);
 
       *aSize = newSurf->GetSize().ToIntSize();
     
       return newSurf.forget();
     }
 
     *aSize = mActiveImage->GetSize();
     return mActiveImage->DeprecatedGetAsSurface();
@@ -364,18 +364,18 @@ ImageContainer::LockCurrentAsSourceSurfa
     }
 
     if (!mActiveImage) {
       return nullptr;
     }
 
     if (mActiveImage->GetFormat() == REMOTE_IMAGE_BITMAP) {
       gfxImageFormat fmt = mRemoteData->mFormat == RemoteImageData::BGRX32
-                           ? gfxImageFormatARGB32
-                           : gfxImageFormatRGB24;
+                           ? gfxImageFormat::ARGB32
+                           : gfxImageFormat::RGB24;
 
       RefPtr<gfx::DataSourceSurface> newSurf
         = gfx::Factory::CreateWrappingDataSourceSurface(mRemoteData->mBitmap.mData,
                                                         mRemoteData->mBitmap.mStride,
                                                         mRemoteData->mSize,
                                                         gfx::ImageFormatToSurfaceFormat(fmt));
       *aSize = newSurf->GetSize();
 
@@ -521,17 +521,17 @@ ImageContainer::EnsureActiveImage()
 #endif
   }
 }
 
 
 PlanarYCbCrImage::PlanarYCbCrImage(BufferRecycleBin *aRecycleBin)
   : Image(nullptr, PLANAR_YCBCR)
   , mBufferSize(0)
-  , mOffscreenFormat(gfxImageFormatUnknown)
+  , mOffscreenFormat(gfxImageFormat::Unknown)
   , mRecycleBin(aRecycleBin)
 {
 }
 
 PlanarYCbCrImage::~PlanarYCbCrImage()
 {
   if (mBuffer) {
     mRecycleBin->RecycleBuffer(mBuffer.forget(), mBufferSize);
@@ -603,17 +603,17 @@ void
 PlanarYCbCrImage::SetData(const Data &aData)
 {
   CopyData(aData);
 }
 
 gfxImageFormat
 PlanarYCbCrImage::GetOffscreenFormat()
 {
-  return mOffscreenFormat == gfxImageFormatUnknown ?
+  return mOffscreenFormat == gfxImageFormat::Unknown ?
     gfxPlatform::GetPlatform()->GetOffscreenFormat() :
     mOffscreenFormat;
 }
 
 void
 PlanarYCbCrImage::SetDataNoCopy(const Data &aData)
 {
   mData = aData;
@@ -684,17 +684,17 @@ PlanarYCbCrImage::GetAsSourceSurface()
   return surface.forget();
 }
 
 already_AddRefed<gfxASurface>
 RemoteBitmapImage::DeprecatedGetAsSurface()
 {
   nsRefPtr<gfxImageSurface> newSurf =
     new gfxImageSurface(ThebesIntSize(mSize),
-    mFormat == RemoteImageData::BGRX32 ? gfxImageFormatRGB24 : gfxImageFormatARGB32);
+    mFormat == RemoteImageData::BGRX32 ? gfxImageFormat::RGB24 : gfxImageFormat::ARGB32);
 
   for (int y = 0; y < mSize.height; y++) {
     memcpy(newSurf->Data() + newSurf->Stride() * y,
            mData + mStride * y,
            mSize.width * 4);
   }
 
   return newSurf.forget();
--- a/gfx/layers/ImageContainer.h
+++ b/gfx/layers/ImageContainer.h
@@ -196,36 +196,36 @@ public:
   virtual already_AddRefed<gfxASurface> DeprecatedGetAsSurface() = 0;
   virtual gfx::IntSize GetSize() = 0;
   virtual nsIntRect GetPictureRect()
   {
     return nsIntRect(0, 0, GetSize().width, GetSize().height);
   }
 
   ImageBackendData* GetBackendData(LayersBackend aBackend)
-  { return mBackendData[aBackend]; }
+  { return mBackendData[size_t(aBackend)]; }
   void SetBackendData(LayersBackend aBackend, ImageBackendData* aData)
-  { mBackendData[aBackend] = aData; }
+  { mBackendData[size_t(aBackend)] = aData; }
 
   int32_t GetSerial() { return mSerial; }
 
   void MarkSent() { mSent = true; }
   bool IsSentToCompositor() { return mSent; }
 
   virtual TemporaryRef<gfx::SourceSurface> GetAsSourceSurface();
 
 protected:
   Image(void* aImplData, ImageFormat aFormat) :
     mImplData(aImplData),
     mSerial(++sSerialCounter),
     mFormat(aFormat),
     mSent(false)
   {}
 
-  nsAutoPtr<ImageBackendData> mBackendData[mozilla::layers::LAYERS_LAST];
+  nsAutoPtr<ImageBackendData> mBackendData[size_t(mozilla::layers::LayersBackend::LAYERS_LAST)];
 
   void* mImplData;
   int32_t mSerial;
   ImageFormat mFormat;
   static mozilla::Atomic<int32_t> sSerialCounter;
   bool mSent;
 };
 
--- a/gfx/layers/ImageLayers.cpp
+++ b/gfx/layers/ImageLayers.cpp
@@ -11,17 +11,17 @@
 #include "nsISupportsImpl.h"            // for ImageContainer::Release, etc
 #include "gfx2DGlue.h"
 
 namespace mozilla {
 namespace layers {
 
 ImageLayer::ImageLayer(LayerManager* aManager, void* aImplData)
 : Layer(aManager, aImplData), mFilter(GraphicsFilter::FILTER_GOOD)
-, mScaleMode(SCALE_NONE), mDisallowBigImage(false)
+, mScaleMode(ScaleMode::SCALE_NONE), mDisallowBigImage(false)
 {}
 
 ImageLayer::~ImageLayer()
 {}
 
 void ImageLayer::SetContainer(ImageContainer* aContainer) 
 {
   mContainer = aContainer;
@@ -30,19 +30,19 @@ void ImageLayer::SetContainer(ImageConta
 void ImageLayer::ComputeEffectiveTransforms(const gfx3DMatrix& aTransformToSurface)
 {
   gfx3DMatrix local = GetLocalTransform();
 
   // Snap image edges to pixel boundaries
   gfxRect sourceRect(0, 0, 0, 0);
   if (mContainer) {
     sourceRect.SizeTo(gfx::ThebesIntSize(mContainer->GetCurrentSize()));
-    if (mScaleMode != SCALE_NONE &&
+    if (mScaleMode != ScaleMode::SCALE_NONE &&
         sourceRect.width != 0.0 && sourceRect.height != 0.0) {
-      NS_ASSERTION(mScaleMode == SCALE_STRETCH,
+      NS_ASSERTION(mScaleMode == ScaleMode::STRETCH,
                    "No other scalemodes than stretch and none supported yet.");
       local.Scale(mScaleToSize.width / sourceRect.width,
                   mScaleToSize.height / sourceRect.height, 1.0);
     }
   }
   // Snap our local transform first, and snap the inherited transform as well.
   // This makes our snapping equivalent to what would happen if our content
   // was drawn into a ThebesLayer (gfxContext would snap using the local
--- a/gfx/layers/Layers.cpp
+++ b/gfx/layers/Layers.cpp
@@ -118,17 +118,17 @@ LayerManager::CreateOptimalSurface(const
 {
   return gfxPlatform::GetPlatform()->
     CreateOffscreenSurface(gfx::ThebesIntSize(aSize), gfxASurface::ContentFromFormat(aFormat));
 }
 
 already_AddRefed<gfxASurface>
 LayerManager::CreateOptimalMaskSurface(const gfx::IntSize &aSize)
 {
-  return CreateOptimalSurface(aSize, gfxImageFormatA8);
+  return CreateOptimalSurface(aSize, gfxImageFormat::A8);
 }
 
 TemporaryRef<DrawTarget>
 LayerManager::CreateDrawTarget(const IntSize &aSize,
                                SurfaceFormat aFormat)
 {
   return gfxPlatform::GetPlatform()->
     CreateOffscreenCanvasDrawTarget(aSize, aFormat);
@@ -1528,17 +1528,17 @@ SetAntialiasingFlags(Layer* aLayer, gfxC
 {
   if (!aTarget->IsCairo()) {
     SetAntialiasingFlags(aLayer, aTarget->GetDrawTarget());
     return;
   }
 
   bool permitSubpixelAA = !(aLayer->GetContentFlags() & Layer::CONTENT_DISABLE_SUBPIXEL_AA);
   nsRefPtr<gfxASurface> surface = aTarget->CurrentSurface();
-  if (surface->GetContentType() != GFX_CONTENT_COLOR_ALPHA) {
+  if (surface->GetContentType() != gfxContentType::COLOR_ALPHA) {
     // Destination doesn't have alpha channel; no need to set any special flags
     surface->SetSubpixelAntialiasingEnabled(permitSubpixelAA);
     return;
   }
 
   const nsIntRect& bounds = aLayer->GetVisibleRegion().GetBounds();
   permitSubpixelAA &= !(aLayer->GetContentFlags() & Layer::CONTENT_COMPONENT_ALPHA) ||
       surface->GetOpaqueRect().Contains(
--- a/gfx/layers/Layers.h
+++ b/gfx/layers/Layers.h
@@ -290,17 +290,17 @@ public:
 
   virtual bool HasShadowManagerInternal() const { return false; }
   bool HasShadowManager() const { return HasShadowManagerInternal(); }
 
   bool IsSnappingEffectiveTransforms() { return mSnapEffectiveTransforms; }
 
   /**
    * Returns true if this LayerManager can properly support layers with
-   * SURFACE_COMPONENT_ALPHA. This can include disabling component
+   * SurfaceMode::SURFACE_COMPONENT_ALPHA. This can include disabling component
    * alpha if required.
    */
   virtual bool AreComponentAlphaLayersEnabled() { return true; }
 
   /**
    * CONSTRUCTION PHASE ONLY
    * Set the root layer. The root layer is initially null. If there is
    * no root layer, EndTransaction won't draw anything.
@@ -580,19 +580,19 @@ public:
 
   void BeginTabSwitch();
 
   static bool IsLogEnabled();
   static PRLogModuleInfo* GetLog() { return sLog; }
 
   bool IsCompositingCheap(LayersBackend aBackend)
   {
-    // LAYERS_NONE is an error state, but in that case we should try to
+    // LayersBackend::LAYERS_NONE is an error state, but in that case we should try to
     // avoid loading the compositor!
-    return LAYERS_BASIC != aBackend && LAYERS_NONE != aBackend;
+    return LayersBackend::LAYERS_BASIC != aBackend && LayersBackend::LAYERS_NONE != aBackend;
   }
 
   virtual bool IsCompositingCheap() { return true; }
 
   bool IsInTransaction() const { return mInTransaction; }
 
 protected:
   nsRefPtr<Layer> mRoot;
@@ -1102,20 +1102,20 @@ public:
   // If we can use a surface without an alpha channel, we should, because
   // it will often make painting of antialiased text faster and higher
   // quality.
   bool CanUseOpaqueSurface();
 
   SurfaceMode GetSurfaceMode()
   {
     if (CanUseOpaqueSurface())
-      return SURFACE_OPAQUE;
+      return SurfaceMode::SURFACE_OPAQUE;
     if (mContentFlags & CONTENT_COMPONENT_ALPHA)
-      return SURFACE_COMPONENT_ALPHA;
-    return SURFACE_SINGLE_CHANNEL_ALPHA;
+      return SurfaceMode::SURFACE_COMPONENT_ALPHA;
+    return SurfaceMode::SURFACE_SINGLE_CHANNEL_ALPHA;
   }
 
   /**
    * This setter can be used anytime. The user data for all keys is
    * initially null. Ownership pases to the layer manager.
    */
   void SetUserData(void* aKey, LayerUserData* aData)
   {
--- a/gfx/layers/LayersTypes.h
+++ b/gfx/layers/LayersTypes.h
@@ -5,16 +5,18 @@
 
 #ifndef GFX_LAYERSTYPES_H
 #define GFX_LAYERSTYPES_H
 
 #include <stdint.h>                     // for uint32_t
 #include "nsPoint.h"                    // for nsIntPoint
 #include "nsRegion.h"
 
+#include "mozilla/TypedEnum.h"
+
 #ifdef MOZ_WIDGET_GONK
 #include <ui/GraphicBuffer.h>
 #endif
 #if defined(DEBUG) || defined(PR_LOGGING)
 #  include <stdio.h>            // FILE
 #  include "prlog.h"            // for PR_LOG
 #  ifndef MOZ_LAYERS_HAVE_LOG
 #    define MOZ_LAYERS_HAVE_LOG
@@ -34,44 +36,47 @@ class GraphicBuffer;
 }
 
 namespace mozilla {
 namespace layers {
 
 
 typedef uint32_t TextureFlags;
 
-enum LayersBackend {
+#undef NONE
+#undef OPAQUE
+
+MOZ_BEGIN_ENUM_CLASS(LayersBackend, int8_t)
   LAYERS_NONE = 0,
   LAYERS_BASIC,
   LAYERS_OPENGL,
   LAYERS_D3D9,
   LAYERS_D3D10,
   LAYERS_D3D11,
   LAYERS_CLIENT,
   LAYERS_LAST
-};
+MOZ_END_ENUM_CLASS(LayersBackend)
 
-enum BufferMode {
+MOZ_BEGIN_ENUM_CLASS(BufferMode, int8_t)
   BUFFER_NONE,
-  BUFFER_BUFFERED
-};
+  BUFFERED
+MOZ_END_ENUM_CLASS(BufferMode)
 
-enum DrawRegionClip {
-  CLIP_DRAW,
-  CLIP_DRAW_SNAPPED,
-  CLIP_NONE,
-};
+MOZ_BEGIN_ENUM_CLASS(DrawRegionClip, int8_t)
+  DRAW,
+  DRAW_SNAPPED,
+  CLIP_NONE
+MOZ_END_ENUM_CLASS(DrawRegionClip)
 
-enum SurfaceMode {
+MOZ_BEGIN_ENUM_CLASS(SurfaceMode, int8_t)
   SURFACE_NONE = 0,
   SURFACE_OPAQUE,
   SURFACE_SINGLE_CHANNEL_ALPHA,
   SURFACE_COMPONENT_ALPHA
-};
+MOZ_END_ENUM_CLASS(SurfaceMode)
 
 // LayerRenderState for Composer2D
 // We currently only support Composer2D using gralloc. If we want to be backed
 // by other surfaces we will need a more generic LayerRenderState.
 enum LayerRenderStateFlags {
   LAYER_RENDER_STATE_Y_FLIPPED = 1 << 0,
   LAYER_RENDER_STATE_BUFFER_ROTATION = 1 << 1,
   // Notify Composer2D to swap the RB pixels of gralloc buffer
@@ -122,22 +127,22 @@ struct LayerRenderState {
   // see LayerRenderStateFlags
   uint32_t mFlags;
   // the location of the layer's origin on mSurface
   nsIntPoint mOffset;
   // true if mOffset is applicable
   bool mHasOwnOffset;
 };
 
-enum ScaleMode {
+MOZ_BEGIN_ENUM_CLASS(ScaleMode, int8_t)
   SCALE_NONE,
-  SCALE_STRETCH,
-  SCALE_SENTINEL
-// Unimplemented - SCALE_PRESERVE_ASPECT_RATIO_CONTAIN
-};
+  STRETCH,
+  SENTINEL
+// Unimplemented - PRESERVE_ASPECT_RATIO_CONTAIN
+MOZ_END_ENUM_CLASS(ScaleMode)
 
 struct EventRegions {
   nsIntRegion mHitRegion;
   nsIntRegion mDispatchToContentHitRegion;
 
   bool operator==(const EventRegions& aRegions) const
   {
     return mHitRegion == aRegions.mHitRegion &&
--- a/gfx/layers/MacIOSurfaceImage.h
+++ b/gfx/layers/MacIOSurfaceImage.h
@@ -32,17 +32,17 @@ public:
     mSurface->Lock();
     size_t bytesPerRow = mSurface->GetBytesPerRow();
     size_t ioWidth = mSurface->GetDevicePixelWidth();
     size_t ioHeight = mSurface->GetDevicePixelHeight();
 
     unsigned char* ioData = (unsigned char*)mSurface->GetBaseAddress();
 
     nsRefPtr<gfxImageSurface> imgSurface =
-      new gfxImageSurface(gfxIntSize(ioWidth, ioHeight), gfxImageFormatARGB32);
+      new gfxImageSurface(gfxIntSize(ioWidth, ioHeight), gfxImageFormat::ARGB32);
 
     for (size_t i = 0; i < ioHeight; i++) {
       memcpy(imgSurface->Data() + i * imgSurface->Stride(),
              ioData + i * bytesPerRow, ioWidth * 4);
     }
 
     mSurface->Unlock();
 
--- a/gfx/layers/RotatedBuffer.cpp
+++ b/gfx/layers/RotatedBuffer.cpp
@@ -291,17 +291,17 @@ RotatedContentBuffer::BufferContentType(
     if (mBufferProvider) {
       format = mBufferProvider->AsTextureClientDrawTarget()->GetFormat();
     } else if (mDTBuffer) {
       format = mDTBuffer->GetFormat();
     }
 
     return ContentForFormat(format);
   }
-  return GFX_CONTENT_SENTINEL;
+  return gfxContentType::SENTINEL;
 }
 
 bool
 RotatedContentBuffer::BufferSizeOkFor(const nsIntSize& aSize)
 {
   return (aSize == mBufferRect.Size() ||
           (SizedToVisibleBounds != mBufferSizePolicy &&
            aSize < mBufferRect.Size()));
@@ -409,18 +409,18 @@ RotatedContentBuffer::BeginPaint(ThebesL
   // drawing, because we might sample across the rotation boundary.
   bool canHaveRotation = gfxPlatform::BufferRotationEnabled() &&
                          !(aFlags & (PAINT_WILL_RESAMPLE | PAINT_NO_ROTATION));
 
   nsIntRegion validRegion = aLayer->GetValidRegion();
 
   bool canUseOpaqueSurface = aLayer->CanUseOpaqueSurface();
   ContentType contentType =
-    canUseOpaqueSurface ? GFX_CONTENT_COLOR :
-                          GFX_CONTENT_COLOR_ALPHA;
+    canUseOpaqueSurface ? gfxContentType::COLOR :
+                          gfxContentType::COLOR_ALPHA;
 
   SurfaceMode mode;
   nsIntRegion neededRegion;
   bool canReuseBuffer;
   nsIntRect destBufferRect;
 
   while (true) {
     mode = aLayer->GetSurfaceMode();
@@ -438,52 +438,52 @@ RotatedContentBuffer::BeginPaint(ThebesL
       } else {
         destBufferRect = neededRegion.GetBounds();
       }
     } else {
       // We won't be reusing the buffer.  Compute a new rect.
       destBufferRect = ComputeBufferRect(neededRegion.GetBounds());
     }
 
-    if (mode == SURFACE_COMPONENT_ALPHA) {
+    if (mode == SurfaceMode::SURFACE_COMPONENT_ALPHA) {
 #if defined(MOZ_GFX_OPTIMIZE_MOBILE) || defined(MOZ_WIDGET_GONK)
-      mode = SURFACE_SINGLE_CHANNEL_ALPHA;
+      mode = SurfaceMode::SURFACE_SINGLE_CHANNEL_ALPHA;
 #else
       if (!aLayer->GetParent() ||
           !aLayer->GetParent()->SupportsComponentAlphaChildren() ||
           !aLayer->Manager()->IsCompositingCheap() ||
           !aLayer->AsShadowableLayer() ||
           !aLayer->AsShadowableLayer()->HasShadow() ||
           !gfxPlatform::ComponentAlphaEnabled()) {
-        mode = SURFACE_SINGLE_CHANNEL_ALPHA;
+        mode = SurfaceMode::SURFACE_SINGLE_CHANNEL_ALPHA;
       } else {
-        contentType = GFX_CONTENT_COLOR;
+        contentType = gfxContentType::COLOR;
       }
 #endif
     }
 
     if ((aFlags & PAINT_WILL_RESAMPLE) &&
         (!neededRegion.GetBounds().IsEqualInterior(destBufferRect) ||
          neededRegion.GetNumRects() > 1)) {
       // The area we add to neededRegion might not be painted opaquely
-      if (mode == SURFACE_OPAQUE) {
-        contentType = GFX_CONTENT_COLOR_ALPHA;
-        mode = SURFACE_SINGLE_CHANNEL_ALPHA;
+      if (mode == SurfaceMode::SURFACE_OPAQUE) {
+        contentType = gfxContentType::COLOR_ALPHA;
+        mode = SurfaceMode::SURFACE_SINGLE_CHANNEL_ALPHA;
       }
 
       // We need to validate the entire buffer, to make sure that only valid
       // pixels are sampled
       neededRegion = destBufferRect;
     }
 
     // If we have an existing buffer, but the content type has changed or we
     // have transitioned into/out of component alpha, then we need to recreate it.
     if (HaveBuffer() &&
         (contentType != BufferContentType() ||
-        (mode == SURFACE_COMPONENT_ALPHA) != HaveBufferOnWhite())) {
+        (mode == SurfaceMode::SURFACE_COMPONENT_ALPHA) != HaveBufferOnWhite())) {
 
       // We're effectively clearing the valid region, so we need to draw
       // the entire needed region now.
       result.mRegionToInvalidate = aLayer->GetValidRegion();
       validRegion.SetEmpty();
       Clear();
       // Restart decision process with the cleared buffer. We can only go
       // around the loop one more iteration, since mDTBuffer is null now.
@@ -505,17 +505,17 @@ RotatedContentBuffer::BeginPaint(ThebesL
 
   if (result.mRegionToDraw.IsEmpty())
     return result;
 
   nsIntRect drawBounds = result.mRegionToDraw.GetBounds();
   RefPtr<DrawTarget> destDTBuffer;
   RefPtr<DrawTarget> destDTBufferOnWhite;
   uint32_t bufferFlags = canHaveRotation ? ALLOW_REPEAT : 0;
-  if (mode == SURFACE_COMPONENT_ALPHA) {
+  if (mode == SurfaceMode::SURFACE_COMPONENT_ALPHA) {
     bufferFlags |= BUFFER_COMPONENT_ALPHA;
   }
   if (canReuseBuffer) {
     if (!EnsureBuffer()) {
       return result;
     }
     nsIntRect keepArea;
     if (keepArea.IntersectRect(destBufferRect, mBufferRect)) {
@@ -537,17 +537,17 @@ RotatedContentBuffer::BeginPaint(ThebesL
         // buffer, so move the pixels we can keep into a position that
         // lets us redraw in just one quadrant.
         if (mBufferRotation == nsIntPoint(0,0)) {
           nsIntRect srcRect(nsIntPoint(0, 0), mBufferRect.Size());
           nsIntPoint dest = mBufferRect.TopLeft() - destBufferRect.TopLeft();
           MOZ_ASSERT(mDTBuffer);
           mDTBuffer->CopyRect(IntRect(srcRect.x, srcRect.y, srcRect.width, srcRect.height),
                               IntPoint(dest.x, dest.y));
-          if (mode == SURFACE_COMPONENT_ALPHA) {
+          if (mode == SurfaceMode::SURFACE_COMPONENT_ALPHA) {
             if (!EnsureBufferOnWhite()) {
               return result;
             }
             MOZ_ASSERT(mDTBufferOnWhite);
             mDTBufferOnWhite->CopyRect(IntRect(srcRect.x, srcRect.y, srcRect.width, srcRect.height),
                                        IntPoint(dest.x, dest.y));
           }
           result.mDidSelfCopy = true;
@@ -566,17 +566,17 @@ RotatedContentBuffer::BeginPaint(ThebesL
           if (mDTBuffer->LockBits(&data, &size, &stride, &format)) {
             uint8_t bytesPerPixel = BytesPerPixel(format);
             BufferUnrotate(data,
                            size.width * bytesPerPixel,
                            size.height, stride,
                            newRotation.x * bytesPerPixel, newRotation.y);
             mDTBuffer->ReleaseBits(data);
 
-            if (mode == SURFACE_COMPONENT_ALPHA) {
+            if (mode == SurfaceMode::SURFACE_COMPONENT_ALPHA) {
               if (!EnsureBufferOnWhite()) {
                 return result;
               }
               MOZ_ASSERT(mDTBufferOnWhite);
               mDTBufferOnWhite->LockBits(&data, &size, &stride, &format);
               uint8_t bytesPerPixel = BytesPerPixel(format);
               BufferUnrotate(data,
                              size.width * bytesPerPixel,
@@ -625,30 +625,30 @@ RotatedContentBuffer::BeginPaint(ThebesL
   NS_ASSERTION(!(aFlags & PAINT_WILL_RESAMPLE) || destBufferRect == neededRegion.GetBounds(),
                "If we're resampling, we need to validate the entire buffer");
 
   // If we have no buffered data already, then destBuffer will be a fresh buffer
   // and we do not need to clear it below.
   bool isClear = !HaveBuffer();
 
   if (destDTBuffer) {
-    if (!isClear && (mode != SURFACE_COMPONENT_ALPHA || HaveBufferOnWhite())) {
+    if (!isClear && (mode != SurfaceMode::SURFACE_COMPONENT_ALPHA || HaveBufferOnWhite())) {
       // Copy the bits
       nsIntPoint offset = -destBufferRect.TopLeft();
       Matrix mat;
       mat.Translate(offset.x, offset.y);
       destDTBuffer->SetTransform(mat);
       if (!EnsureBuffer()) {
         return result;
       }
        MOZ_ASSERT(mDTBuffer, "Have we got a Thebes buffer for some reason?");
       DrawBufferWithRotation(destDTBuffer, BUFFER_BLACK, 1.0, CompositionOp::OP_SOURCE);
       destDTBuffer->SetTransform(Matrix());
 
-      if (mode == SURFACE_COMPONENT_ALPHA) {
+      if (mode == SurfaceMode::SURFACE_COMPONENT_ALPHA) {
         NS_ASSERTION(destDTBufferOnWhite, "Must have a white buffer!");
         destDTBufferOnWhite->SetTransform(mat);
         if (!EnsureBufferOnWhite()) {
           return result;
         }
         MOZ_ASSERT(mDTBufferOnWhite, "Have we got a Thebes buffer for some reason?");
         DrawBufferWithRotation(destDTBufferOnWhite, BUFFER_WHITE, 1.0, CompositionOp::OP_SOURCE);
         destDTBufferOnWhite->SetTransform(Matrix());
@@ -661,49 +661,49 @@ RotatedContentBuffer::BeginPaint(ThebesL
     mBufferRotation = nsIntPoint(0,0);
   }
   NS_ASSERTION(canHaveRotation || mBufferRotation == nsIntPoint(0,0),
                "Rotation disabled, but we have nonzero rotation?");
 
   nsIntRegion invalidate;
   invalidate.Sub(aLayer->GetValidRegion(), destBufferRect);
   result.mRegionToInvalidate.Or(result.mRegionToInvalidate, invalidate);
-  result.mClip = CLIP_DRAW_SNAPPED;
+  result.mClip = DrawRegionClip::DRAW_SNAPPED;
   result.mMode = mode;
 
   return result;
 }
 
 DrawTarget*
 RotatedContentBuffer::BorrowDrawTargetForPainting(ThebesLayer* aLayer,
                                                   const PaintState& aPaintState)
 {
-  if (!aPaintState.mMode) {
+  if (aPaintState.mMode == SurfaceMode::SURFACE_NONE) {
     return nullptr;
   }
 
   DrawTarget* result = BorrowDrawTargetForQuadrantUpdate(aPaintState.mRegionToDraw.GetBounds(),
                                                          BUFFER_BOTH);
 
   bool canUseOpaqueSurface = aLayer->CanUseOpaqueSurface();
   ContentType contentType =
-    canUseOpaqueSurface ? GFX_CONTENT_COLOR :
-                          GFX_CONTENT_COLOR_ALPHA;
+    canUseOpaqueSurface ? gfxContentType::COLOR :
+                          gfxContentType::COLOR_ALPHA;
 
-  if (aPaintState.mMode == SURFACE_COMPONENT_ALPHA) {
+  if (aPaintState.mMode == SurfaceMode::SURFACE_COMPONENT_ALPHA) {
     MOZ_ASSERT(mDTBuffer && mDTBufferOnWhite);
     nsIntRegionRectIterator iter(aPaintState.mRegionToDraw);
     const nsIntRect *iterRect;
     while ((iterRect = iter.Next())) {
       mDTBuffer->FillRect(Rect(iterRect->x, iterRect->y, iterRect->width, iterRect->height),
                           ColorPattern(Color(0.0, 0.0, 0.0, 1.0)));
       mDTBufferOnWhite->FillRect(Rect(iterRect->x, iterRect->y, iterRect->width, iterRect->height),
                                  ColorPattern(Color(1.0, 1.0, 1.0, 1.0)));
     }
-  } else if (contentType == GFX_CONTENT_COLOR_ALPHA && HaveBuffer()) {
+  } else if (contentType == gfxContentType::COLOR_ALPHA && HaveBuffer()) {
     // HaveBuffer() => we have an existing buffer that we must clear
     nsIntRegionRectIterator iter(aPaintState.mRegionToDraw);
     const nsIntRect *iterRect;
     while ((iterRect = iter.Next())) {
       result->ClearRect(Rect(iterRect->x, iterRect->y, iterRect->width, iterRect->height));
     }
   }
 
--- a/gfx/layers/RotatedBuffer.h
+++ b/gfx/layers/RotatedBuffer.h
@@ -209,17 +209,17 @@ public:
    * by RotatedContentBuffer and must be redrawn on the screen.
    * mRegionToInvalidate is set when the buffer has changed from
    * opaque to transparent or vice versa, since the details of rendering can
    * depend on the buffer type.  mDidSelfCopy is true if we kept our buffer
    * but used MovePixels() to shift its content.
    */
   struct PaintState {
     PaintState()
-      : mMode(SURFACE_NONE)
+      : mMode(SurfaceMode::SURFACE_NONE)
       , mDidSelfCopy(false)
     {}
 
     nsIntRegion mRegionToDraw;
     nsIntRegion mRegionToInvalidate;
     SurfaceMode mMode;
     DrawRegionClip mClip;
     bool mDidSelfCopy;
--- a/gfx/layers/basic/BasicCompositor.cpp
+++ b/gfx/layers/basic/BasicCompositor.cpp
@@ -222,17 +222,17 @@ CreateBasicDeprecatedTextureHost(Surface
   result->SetFlags(aTextureFlags);
   return result.forget();
 }
 
 BasicCompositor::BasicCompositor(nsIWidget *aWidget)
   : mWidget(aWidget)
 {
   MOZ_COUNT_CTOR(BasicCompositor);
-  sBackend = LAYERS_BASIC;
+  sBackend = LayersBackend::LAYERS_BASIC;
 }
 
 BasicCompositor::~BasicCompositor()
 {
   MOZ_COUNT_DTOR(BasicCompositor);
 }
 
 void BasicCompositor::Destroy()
--- a/gfx/layers/basic/BasicCompositor.h
+++ b/gfx/layers/basic/BasicCompositor.h
@@ -46,17 +46,17 @@ public:
 
 
   virtual bool Initialize() MOZ_OVERRIDE { return true; };
 
   virtual void Destroy() MOZ_OVERRIDE;
 
   virtual TextureFactoryIdentifier GetTextureFactoryIdentifier() MOZ_OVERRIDE
   {
-    return TextureFactoryIdentifier(LAYERS_BASIC,
+    return TextureFactoryIdentifier(LayersBackend::LAYERS_BASIC,
                                     XRE_GetProcessType(),
                                     GetMaxTextureSize());
   }
 
   virtual TemporaryRef<CompositingRenderTarget>
   CreateRenderTarget(const gfx::IntRect &aRect, SurfaceInitMode aInit) MOZ_OVERRIDE;
 
   virtual TemporaryRef<CompositingRenderTarget>
--- a/gfx/layers/basic/BasicImageLayer.cpp
+++ b/gfx/layers/basic/BasicImageLayer.cpp
@@ -134,17 +134,17 @@ PaintContext(gfxPattern* aPattern,
   // outside the bounds of the video image.
   gfxPattern::GraphicsExtend extend = gfxPattern::EXTEND_PAD;
 
 #ifdef MOZ_X11
   // PAD is slow with cairo and old X11 servers, so prefer speed over
   // correctness and use NONE.
   if (aContext->IsCairo()) {
     nsRefPtr<gfxASurface> target = aContext->CurrentSurface();
-    if (target->GetType() == gfxSurfaceTypeXlib &&
+    if (target->GetType() == gfxSurfaceType::Xlib &&
         static_cast<gfxXlibSurface*>(target.get())->IsPadSlow()) {
       extend = gfxPattern::EXTEND_NONE;
     }
   }
 #endif
 
   aContext->NewPath();
   // No need to snap here; our transform has already taken care of it.
--- a/gfx/layers/basic/BasicLayerManager.cpp
+++ b/gfx/layers/basic/BasicLayerManager.cpp
@@ -88,30 +88,30 @@ BasicLayerManager::PushGroupForLayer(gfx
   // If we need to call PushGroup, we should clip to the smallest possible
   // area first to minimize the size of the temporary surface.
   bool didCompleteClip = ClipToContain(aContext, aRegion.GetBounds());
 
   nsRefPtr<gfxContext> result;
   if (aLayer->CanUseOpaqueSurface() &&
       ((didCompleteClip && aRegion.GetNumRects() == 1) ||
        !aContext->CurrentMatrix().HasNonIntegerTranslation())) {
-    // If the layer is opaque in its visible region we can push a GFX_CONTENT_COLOR
+    // If the layer is opaque in its visible region we can push a gfxContentType::COLOR
     // group. We need to make sure that only pixels inside the layer's visible
     // region are copied back to the destination. Remember if we've already
     // clipped precisely to the visible region.
     *aNeedsClipToVisibleRegion = !didCompleteClip || aRegion.GetNumRects() > 1;
     MOZ_ASSERT(!aContext->IsCairo());
-    result = PushGroupWithCachedSurface(aContext, GFX_CONTENT_COLOR);
+    result = PushGroupWithCachedSurface(aContext, gfxContentType::COLOR);
   } else {
     *aNeedsClipToVisibleRegion = false;
     result = aContext;
     if (aLayer->GetContentFlags() & Layer::CONTENT_COMPONENT_ALPHA) {
-      aContext->PushGroupAndCopyBackground(GFX_CONTENT_COLOR_ALPHA);
+      aContext->PushGroupAndCopyBackground(gfxContentType::COLOR_ALPHA);
     } else {
-      aContext->PushGroup(GFX_CONTENT_COLOR_ALPHA);
+      aContext->PushGroup(gfxContentType::COLOR_ALPHA);
     }
   }
   return result.forget();
 }
 
 static nsIntRect
 ToOutsideIntRect(const gfxRect &aRect)
 {
@@ -233,29 +233,29 @@ public:
   ReadbackProcessor* mReadback;
   gfxMatrix mTransform;
   bool mPushedOpaqueRect;
 };
 
 BasicLayerManager::BasicLayerManager(nsIWidget* aWidget) :
   mPhase(PHASE_NONE),
   mWidget(aWidget)
-  , mDoubleBuffering(BUFFER_NONE), mUsingDefaultTarget(false)
+  , mDoubleBuffering(BufferMode::BUFFER_NONE), mUsingDefaultTarget(false)
   , mCachedSurfaceInUse(false)
   , mTransactionIncomplete(false)
   , mCompositorMightResample(false)
 {
   MOZ_COUNT_CTOR(BasicLayerManager);
   NS_ASSERTION(aWidget, "Must provide a widget");
 }
 
 BasicLayerManager::BasicLayerManager() :
   mPhase(PHASE_NONE),
   mWidget(nullptr)
-  , mDoubleBuffering(BUFFER_NONE), mUsingDefaultTarget(false)
+  , mDoubleBuffering(BufferMode::BUFFER_NONE), mUsingDefaultTarget(false)
   , mCachedSurfaceInUse(false)
   , mTransactionIncomplete(false)
 {
   MOZ_COUNT_CTOR(BasicLayerManager);
 }
 
 BasicLayerManager::~BasicLayerManager()
 {
@@ -615,17 +615,17 @@ BasicLayerManager::EndTransactionInterna
       gfxContextMatrixAutoSaveRestore save(mTarget);
       mTarget->SetMatrix(gfxMatrix());
       clipRect = ToOutsideIntRect(mTarget->GetClipExtents());
     }
 
     if (IsRetained()) {
       nsIntRegion region;
       MarkLayersHidden(mRoot, clipRect, clipRect, region, ALLOW_OPAQUE);
-      if (mUsingDefaultTarget && mDoubleBuffering != BUFFER_NONE) {
+      if (mUsingDefaultTarget && mDoubleBuffering != BufferMode::BUFFER_NONE) {
         ApplyDoubleBuffering(mRoot, clipRect);
       }
     }
 
     PaintLayer(mTarget, mRoot, aCallback, aCallbackData, nullptr);
     if (mWidget) {
       FlashWidgetUpdateArea(mTarget);
     }
@@ -718,17 +718,17 @@ BasicLayerManager_Matrix3DToPixman(const
 
 static void
 PixmanTransform(const gfxImageSurface* aDest,
                 RefPtr<DataSourceSurface> aSrc,
                 const gfx3DMatrix& aTransform,
                 gfxPoint aDestOffset)
 {
   IntSize destSize = ToIntSize(aDest->GetSize());
-  pixman_image_t* dest = pixman_image_create_bits(aDest->Format() == gfxImageFormatARGB32 ? PIXMAN_a8r8g8b8 : PIXMAN_x8r8g8b8,
+  pixman_image_t* dest = pixman_image_create_bits(aDest->Format() == gfxImageFormat::ARGB32 ? PIXMAN_a8r8g8b8 : PIXMAN_x8r8g8b8,
                                                   destSize.width,
                                                   destSize.height,
                                                   (uint32_t*)aDest->Data(),
                                                   aDest->Stride());
 
   IntSize srcSize = aSrc->GetSize();
   pixman_image_t* src = pixman_image_create_bits(aSrc->GetFormat() == SurfaceFormat::B8G8R8A8 ? PIXMAN_a8r8g8b8 : PIXMAN_x8r8g8b8,
                                                  srcSize.width,
@@ -792,17 +792,17 @@ Transform3D(RefPtr<SourceSurface> aSourc
   aDestRect = aDest->GetClipExtents();
   aDestRect.IntersectRect(aDestRect, offsetRect);
   aDestRect.RoundOut();
 
   // Create a surface the size of the transformed object.
   nsRefPtr<gfxASurface> dest = aDest->CurrentSurface();
   nsRefPtr<gfxImageSurface> destImage = new gfxImageSurface(gfxIntSize(aDestRect.width,
                                                                        aDestRect.height),
-                                                            gfxImageFormatARGB32);
+                                                            gfxImageFormat::ARGB32);
   gfxPoint offset = aDestRect.TopLeft();
 
   // Include a translation to the correct origin.
   gfx3DMatrix translation = gfx3DMatrix::Translation(aBounds.x, aBounds.y, 0);
 
   // Transform the content and offset it such that the content begins at the origin.
   PixmanTransform(destImage, aSource->GetDataSurface(), translation * aTransform, offset);
 
--- a/gfx/layers/basic/BasicLayers.h
+++ b/gfx/layers/basic/BasicLayers.h
@@ -106,17 +106,17 @@ public:
   virtual already_AddRefed<ThebesLayer> CreateThebesLayer();
   virtual already_AddRefed<ContainerLayer> CreateContainerLayer();
   virtual already_AddRefed<ImageLayer> CreateImageLayer();
   virtual already_AddRefed<CanvasLayer> CreateCanvasLayer();
   virtual already_AddRefed<ColorLayer> CreateColorLayer();
   virtual already_AddRefed<ReadbackLayer> CreateReadbackLayer();
   virtual ImageFactory *GetImageFactory();
 
-  virtual LayersBackend GetBackendType() { return LAYERS_BASIC; }
+  virtual LayersBackend GetBackendType() { return LayersBackend::LAYERS_BASIC; }
   virtual void GetBackendName(nsAString& name) { name.AssignLiteral("Basic"); }
 
 #ifdef DEBUG
   bool InConstruction() { return mPhase == PHASE_CONSTRUCTION; }
   bool InDrawing() { return mPhase == PHASE_DRAWING; }
   bool InForward() { return mPhase == PHASE_FORWARD; }
 #endif
   bool InTransaction() { return mPhase != PHASE_NONE; }
--- a/gfx/layers/basic/BasicLayersImpl.cpp
+++ b/gfx/layers/basic/BasicLayersImpl.cpp
@@ -86,17 +86,17 @@ GetMaskData(Layer* aMaskLayer, AutoMaskD
 }
 
 void
 PaintWithMask(gfxContext* aContext, float aOpacity, Layer* aMaskLayer)
 {
   AutoMaskData mask;
   if (GetMaskData(aMaskLayer, &mask)) {
     if (aOpacity < 1.0) {
-      aContext->PushGroup(GFX_CONTENT_COLOR_ALPHA);
+      aContext->PushGroup(gfxContentType::COLOR_ALPHA);
       aContext->Paint(aOpacity);
       aContext->PopGroupToSource();
     }
     aContext->SetMatrix(mask.GetTransform());
     aContext->Mask(mask.GetSurface());
     return;
   }
 
@@ -105,17 +105,17 @@ PaintWithMask(gfxContext* aContext, floa
 }
 
 void
 FillWithMask(gfxContext* aContext, float aOpacity, Layer* aMaskLayer)
 {
   AutoMaskData mask;
   if (GetMaskData(aMaskLayer, &mask)) {
     if (aOpacity < 1.0) {
-      aContext->PushGroup(GFX_CONTENT_COLOR_ALPHA);
+      aContext->PushGroup(gfxContentType::COLOR_ALPHA);
       aContext->FillWithOpacity(aOpacity);
       aContext->PopGroupToSource();
       aContext->SetMatrix(mask.GetTransform());
       aContext->Mask(mask.GetSurface());
     } else {
       aContext->Save();
       aContext->Clip();
       aContext->SetMatrix(mask.GetTransform());
--- a/gfx/layers/basic/BasicThebesLayer.cpp
+++ b/gfx/layers/basic/BasicThebesLayer.cpp
@@ -94,17 +94,17 @@ BasicThebesLayer::PaintThebes(gfxContext
                                             &needsClipToVisibleRegion);
         if (GetOperator() != gfxContext::OPERATOR_OVER || mixBlendMode != gfxContext::OPERATOR_OVER) {
           needsClipToVisibleRegion = true;
         }
       } else {
         groupContext = aContext;
       }
       SetAntialiasingFlags(this, groupContext);
-      aCallback(this, groupContext, toDraw, CLIP_NONE, nsIntRegion(), aCallbackData);
+      aCallback(this, groupContext, toDraw, DrawRegionClip::CLIP_NONE, nsIntRegion(), aCallbackData);
       if (needsGroup) {
         BasicManager()->PopGroupToSourceWithCachedSurface(aContext, groupContext);
         if (needsClipToVisibleRegion) {
           gfxUtils::ClipToRegion(aContext, toDraw);
         }
         AutoSetOperator setOptimizedOperator(aContext, mixBlendMode != gfxContext::OPERATOR_OVER ? mixBlendMode : GetOperator());
         PaintWithMask(aContext, opacity, aMaskLayer);
       }
--- a/gfx/layers/client/CanvasClient.cpp
+++ b/gfx/layers/client/CanvasClient.cpp
@@ -32,17 +32,17 @@ namespace mozilla {
 namespace layers {
 
 /* static */ TemporaryRef<CanvasClient>
 CanvasClient::CreateCanvasClient(CanvasClientType aType,
                                  CompositableForwarder* aForwarder,
                                  TextureFlags aFlags)
 {
   if (aType == CanvasClientGLContext &&
-      aForwarder->GetCompositorBackendType() == LAYERS_OPENGL) {
+      aForwarder->GetCompositorBackendType() == LayersBackend::LAYERS_OPENGL) {
     aFlags |= TEXTURE_DEALLOCATE_CLIENT;
     return new CanvasClientSurfaceStream(aForwarder, aFlags);
   }
   if (gfxPlatform::GetPlatform()->UseDeprecatedTextures()) {
     aFlags |= TEXTURE_DEALLOCATE_CLIENT;
     return new DeprecatedCanvasClient2D(aForwarder, aFlags);
   }
   return new CanvasClient2D(aForwarder, aFlags);
@@ -56,18 +56,18 @@ CanvasClient2D::Update(gfx::IntSize aSiz
     GetForwarder()->AddForceRemovingTexture(mBuffer);
     mBuffer = nullptr;
   }
 
   bool bufferCreated = false;
   if (!mBuffer) {
     bool isOpaque = (aLayer->GetContentFlags() & Layer::CONTENT_OPAQUE);
     gfxContentType contentType = isOpaque
-                                                ? GFX_CONTENT_COLOR
-                                                : GFX_CONTENT_COLOR_ALPHA;
+                                                ? gfxContentType::COLOR
+                                                : gfxContentType::COLOR_ALPHA;
     gfxImageFormat format
       = gfxPlatform::GetPlatform()->OptimalFormatForContent(contentType);
     mBuffer = CreateBufferTextureClient(gfx::ImageFormatToSurfaceFormat(format));
     MOZ_ASSERT(mBuffer->AsTextureClientSurface());
     mBuffer->AsTextureClientSurface()->AllocateForSurface(aSize);
 
     bufferCreated = true;
   }
@@ -182,18 +182,18 @@ DeprecatedCanvasClient2D::DeprecatedCanv
   mTextureInfo.mCompositableType = BUFFER_IMAGE_SINGLE;
 }
 
 void
 DeprecatedCanvasClient2D::Update(gfx::IntSize aSize, ClientCanvasLayer* aLayer)
 {
   bool isOpaque = (aLayer->GetContentFlags() & Layer::CONTENT_OPAQUE);
   gfxContentType contentType = isOpaque
-                                              ? GFX_CONTENT_COLOR
-                                              : GFX_CONTENT_COLOR_ALPHA;
+                                              ? gfxContentType::COLOR
+                                              : gfxContentType::COLOR_ALPHA;
 
   if (!mDeprecatedTextureClient) {
     mDeprecatedTextureClient = CreateDeprecatedTextureClient(TEXTURE_CONTENT, contentType);
     if (!mDeprecatedTextureClient) {
       mDeprecatedTextureClient = CreateDeprecatedTextureClient(TEXTURE_FALLBACK, contentType);
       if (!mDeprecatedTextureClient) {
         NS_WARNING("Could not create texture client");
         return;
@@ -233,26 +233,26 @@ DeprecatedCanvasClientSurfaceStream::Dep
   mTextureInfo.mCompositableType = BUFFER_IMAGE_SINGLE;
 }
 
 void
 DeprecatedCanvasClientSurfaceStream::Update(gfx::IntSize aSize, ClientCanvasLayer* aLayer)
 {
   if (!mDeprecatedTextureClient) {
     mDeprecatedTextureClient = CreateDeprecatedTextureClient(TEXTURE_STREAM_GL,
-                                                             aLayer->GetSurfaceMode() == SURFACE_OPAQUE
-                                                               ? GFX_CONTENT_COLOR
-                                                               : GFX_CONTENT_COLOR_ALPHA);
+                                                             aLayer->GetSurfaceMode() == SurfaceMode::SURFACE_OPAQUE
+                                                               ? gfxContentType::COLOR
+                                                               : gfxContentType::COLOR_ALPHA);
     MOZ_ASSERT(mDeprecatedTextureClient, "Failed to create texture client");
   }
 
   NS_ASSERTION(aLayer->mGLContext, "CanvasClientSurfaceStream should only be used with GL canvases");
 
   // the content type won't be used
-  mDeprecatedTextureClient->EnsureAllocated(aSize, GFX_CONTENT_COLOR);
+  mDeprecatedTextureClient->EnsureAllocated(aSize, gfxContentType::COLOR);
 
   GLScreenBuffer* screen = aLayer->mGLContext->Screen();
   SurfaceStream* stream = screen->Stream();
 
   bool isCrossProcess = !(XRE_GetProcessType() == GeckoProcessType_Default);
   if (isCrossProcess) {
     // swap staging -> consumer so we can send it to the compositor
     SharedSurface* surf = stream->SwapConsumer();
--- a/gfx/layers/client/ClientCanvasLayer.cpp
+++ b/gfx/layers/client/ClientCanvasLayer.cpp
@@ -41,17 +41,17 @@ ClientCanvasLayer::Initialize(const Data
 
   if (mGLContext) {
     GLScreenBuffer* screen = mGLContext->Screen();
     SurfaceStreamType streamType =
         SurfaceStream::ChooseGLStreamType(SurfaceStream::OffMainThread,
                                           screen->PreserveBuffer());
     SurfaceFactory_GL* factory = nullptr;
     if (!mForceReadback) {
-      if (ClientManager()->AsShadowForwarder()->GetCompositorBackendType() == mozilla::layers::LAYERS_OPENGL) {
+      if (ClientManager()->AsShadowForwarder()->GetCompositorBackendType() == mozilla::layers::LayersBackend::LAYERS_OPENGL) {
         if (mGLContext->GetContextType() == GLContextType::EGL) {
           bool isCrossProcess = !(XRE_GetProcessType() == GeckoProcessType_Default);
 
           if (!isCrossProcess) {
             // [Basic/OGL Layers, OMTC] WebGL layer init.
             factory = SurfaceFactory_EGLImage::Create(mGLContext, screen->Caps());
           } else {
             // [Basic/OGL Layers, OOPC] WebGL layer init. (Out Of Process Compositing)
--- a/gfx/layers/client/ClientLayerManager.cpp
+++ b/gfx/layers/client/ClientLayerManager.cpp
@@ -269,17 +269,17 @@ ClientLayerManager::MakeSnapshotIfRequir
     return;
   }
   if (mWidget) {
     if (CompositorChild* remoteRenderer = GetRemoteRenderer()) {
       nsIntRect bounds;
       mWidget->GetBounds(bounds);
       SurfaceDescriptor inSnapshot, snapshot;
       if (mForwarder->AllocSurfaceDescriptor(bounds.Size().ToIntSize(),
-                                             GFX_CONTENT_COLOR_ALPHA,
+                                             gfxContentType::COLOR_ALPHA,
                                              &inSnapshot) &&
           // The compositor will usually reuse |snapshot| and return
           // it through |outSnapshot|, but if it doesn't, it's
           // responsible for freeing |snapshot|.
           remoteRenderer->SendMakeSnapshot(inSnapshot, &snapshot)) {
         AutoOpenSurface opener(OPEN_READ_ONLY, snapshot);
         gfxASurface* source = opener.Get();
 
@@ -447,21 +447,21 @@ ClientLayerManager::ClearLayer(Layer* aL
     ClearLayer(child);
   }
 }
 
 void
 ClientLayerManager::GetBackendName(nsAString& aName)
 {
   switch (mForwarder->GetCompositorBackendType()) {
-    case LAYERS_BASIC: aName.AssignLiteral("Basic"); return;
-    case LAYERS_OPENGL: aName.AssignLiteral("OpenGL"); return;
-    case LAYERS_D3D9: aName.AssignLiteral("Direct3D 9"); return;
-    case LAYERS_D3D10: aName.AssignLiteral("Direct3D 10"); return;
-    case LAYERS_D3D11: aName.AssignLiteral("Direct3D 11"); return;
+    case LayersBackend::LAYERS_BASIC: aName.AssignLiteral("Basic"); return;
+    case LayersBackend::LAYERS_OPENGL: aName.AssignLiteral("OpenGL"); return;
+    case LayersBackend::LAYERS_D3D9: aName.AssignLiteral("Direct3D 9"); return;
+    case LayersBackend::LAYERS_D3D10: aName.AssignLiteral("Direct3D 10"); return;
+    case LayersBackend::LAYERS_D3D11: aName.AssignLiteral("Direct3D 11"); return;
     default: NS_RUNTIMEABORT("Invalid backend");
   }
 }
 
 bool
 ClientLayerManager::ProgressiveUpdateCallback(bool aHasPendingNewThebesContent,
                                               ScreenRect& aCompositionBounds,
                                               CSSToScreenScale& aZoom,
--- a/gfx/layers/client/ClientLayerManager.h
+++ b/gfx/layers/client/ClientLayerManager.h
@@ -52,17 +52,17 @@ public:
   virtual void SetDefaultTargetConfiguration(BufferMode aDoubleBuffering, ScreenRotation aRotation);
   virtual void BeginTransactionWithTarget(gfxContext* aTarget);
   virtual void BeginTransaction();
   virtual bool EndEmptyTransaction(EndTransactionFlags aFlags = END_DEFAULT);
   virtual void EndTransaction(DrawThebesLayerCallback aCallback,
                               void* aCallbackData,
                               EndTransactionFlags aFlags = END_DEFAULT);
 
-  virtual LayersBackend GetBackendType() { return LAYERS_CLIENT; }
+  virtual LayersBackend GetBackendType() { return LayersBackend::LAYERS_CLIENT; }
   virtual void GetBackendName(nsAString& name);
   virtual const char* Name() const { return "Client"; }
 
   virtual void SetRoot(Layer* aLayer);
 
   virtual void Mutated(Layer* aLayer);
 
   virtual already_AddRefed<ThebesLayer> CreateThebesLayer();
--- a/gfx/layers/client/ClientThebesLayer.cpp
+++ b/gfx/layers/client/ClientThebesLayer.cpp
@@ -166,17 +166,17 @@ ClientLayerManager::CreateThebesLayer()
 already_AddRefed<ThebesLayer>
 ClientLayerManager::CreateThebesLayerWithHint(ThebesLayerCreationHint aHint)
 {
   NS_ASSERTION(InConstruction(), "Only allowed in construction phase");
   if (
 #ifdef MOZ_B2G
       aHint == SCROLLABLE &&
 #endif
-      gfxPlatform::GetPrefLayersEnableTiles() && AsShadowForwarder()->GetCompositorBackendType() == LAYERS_OPENGL) {
+      gfxPlatform::GetPrefLayersEnableTiles() && AsShadowForwarder()->GetCompositorBackendType() == LayersBackend::LAYERS_OPENGL) {
     nsRefPtr<ClientTiledThebesLayer> layer =
       new ClientTiledThebesLayer(this);
     CREATE_SHADOW(Thebes);
     return layer.forget();
   } else
   {
     nsRefPtr<ClientThebesLayer> layer =
       new ClientThebesLayer(this);
--- a/gfx/layers/client/CompositableClient.cpp
+++ b/gfx/layers/client/CompositableClient.cpp
@@ -97,69 +97,69 @@ CompositableClient::CreateDeprecatedText
                                                   gfxContentType aContentType)
 {
   MOZ_ASSERT(GetForwarder(), "Can't create a texture client if the compositable is not connected to the compositor.");
   LayersBackend parentBackend = GetForwarder()->GetCompositorBackendType();
   RefPtr<DeprecatedTextureClient> result;
 
   switch (aDeprecatedTextureClientType) {
   case TEXTURE_SHARED_GL:
-    if (parentBackend == LAYERS_OPENGL) {
+    if (parentBackend == LayersBackend::LAYERS_OPENGL) {
       result = new DeprecatedTextureClientSharedOGL(GetForwarder(), GetTextureInfo());
     }
      break;
   case TEXTURE_SHARED_GL_EXTERNAL:
-    if (parentBackend == LAYERS_OPENGL) {
+    if (parentBackend == LayersBackend::LAYERS_OPENGL) {
       result = new DeprecatedTextureClientSharedOGLExternal(GetForwarder(), GetTextureInfo());
     }
     break;
   case TEXTURE_STREAM_GL:
-    if (parentBackend == LAYERS_OPENGL) {
+    if (parentBackend == LayersBackend::LAYERS_OPENGL) {
       result = new DeprecatedTextureClientStreamOGL(GetForwarder(), GetTextureInfo());
     }
     break;
   case TEXTURE_YCBCR:
-    if (parentBackend == LAYERS_OPENGL ||
-        parentBackend == LAYERS_D3D9 ||
-        parentBackend == LAYERS_D3D11 ||
-        parentBackend == LAYERS_BASIC) {
+    if (parentBackend == LayersBackend::LAYERS_OPENGL ||
+        parentBackend == LayersBackend::LAYERS_D3D9 ||
+        parentBackend == LayersBackend::LAYERS_D3D11 ||
+        parentBackend == LayersBackend::LAYERS_BASIC) {
       result = new DeprecatedTextureClientShmemYCbCr(GetForwarder(), GetTextureInfo());
     }
     break;
   case TEXTURE_CONTENT:
 #ifdef XP_WIN
-    if (parentBackend == LAYERS_D3D11 && gfxWindowsPlatform::GetPlatform()->GetD2DDevice()) {
+    if (parentBackend == LayersBackend::LAYERS_D3D11 && gfxWindowsPlatform::GetPlatform()->GetD2DDevice()) {
       result = new DeprecatedTextureClientD3D11(GetForwarder(), GetTextureInfo());
       break;
     }
-    if (parentBackend == LAYERS_D3D9 &&
+    if (parentBackend == LayersBackend::LAYERS_D3D9 &&
         !GetForwarder()->ForwardsToDifferentProcess()) {
       // We can't use a d3d9 texture for an RGBA surface because we cannot get a DC for
       // for a gfxWindowsSurface.
       // We have to wait for the compositor thread to create a d3d9 device before we
       // can create d3d9 textures on the main thread (because we need to reset on the
       // compositor thread, and the d3d9 device must be reset on the same thread it was
       // created on).
-      if (aContentType == GFX_CONTENT_COLOR_ALPHA ||
+      if (aContentType == gfxContentType::COLOR_ALPHA ||
           !gfxWindowsPlatform::GetPlatform()->GetD3D9Device()) {
         result = new DeprecatedTextureClientDIB(GetForwarder(), GetTextureInfo());
       } else {
         result = new DeprecatedTextureClientD3D9(GetForwarder(), GetTextureInfo());
       }
       break;
     }
 #endif
      // fall through to TEXTURE_SHMEM
   case TEXTURE_SHMEM:
     result = new DeprecatedTextureClientShmem(GetForwarder(), GetTextureInfo());
     break;
   case TEXTURE_FALLBACK:
 #ifdef XP_WIN
-    if (parentBackend == LAYERS_D3D11 ||
-        parentBackend == LAYERS_D3D9) {
+    if (parentBackend == LayersBackend::LAYERS_D3D11 ||
+        parentBackend == LayersBackend::LAYERS_D3D9) {
       result = new DeprecatedTextureClientShmem(GetForwarder(), GetTextureInfo());
     }
 #endif
     break;
   default:
     MOZ_ASSERT(false, "Unhandled texture client type");
   }
 
@@ -202,25 +202,25 @@ CompositableClient::CreateBufferTextureC
 TemporaryRef<TextureClient>
 CompositableClient::CreateTextureClientForDrawing(SurfaceFormat aFormat,
                                                   TextureFlags aTextureFlags)
 {
   RefPtr<TextureClient> result;
 
 #ifdef XP_WIN
   LayersBackend parentBackend = GetForwarder()->GetCompositorBackendType();
-  if (parentBackend == LAYERS_D3D11 && gfxWindowsPlatform::GetPlatform()->GetD2DDevice() &&
+  if (parentBackend == LayersBackend::LAYERS_D3D11 && gfxWindowsPlatform::GetPlatform()->GetD2DDevice() &&
       !(aTextureFlags & TEXTURE_ALLOC_FALLBACK)) {
     result = new TextureClientD3D11(aFormat, aTextureFlags);
   }
-  if (parentBackend == LAYERS_D3D9 &&
+  if (parentBackend == LayersBackend::LAYERS_D3D9 &&
       !GetForwarder()->ForwardsToDifferentProcess() &&
       !(aTextureFlags & TEXTURE_ALLOC_FALLBACK)) {
     // non-DIB textures don't work with alpha, see notes in TextureD3D9.
-    if (ContentForFormat(aFormat) != GFX_CONTENT_COLOR) {
+    if (ContentForFormat(aFormat) != gfxContentType::COLOR) {
       result = new DIBTextureClientD3D9(aFormat, aTextureFlags);
     } else {
       result = new CairoTextureClientD3D9(aFormat, aTextureFlags);
     }
   }
 #endif
   // Can't do any better than a buffer texture client.
   if (!result) {
--- a/gfx/layers/client/CompositableClient.h
+++ b/gfx/layers/client/CompositableClient.h
@@ -77,17 +77,17 @@ public:
   virtual ~CompositableClient();
 
   virtual TextureInfo GetTextureInfo() const = 0;
 
   LayersBackend GetCompositorBackendType() const;
 
   TemporaryRef<DeprecatedTextureClient>
   CreateDeprecatedTextureClient(DeprecatedTextureClientType aDeprecatedTextureClientType,
-                                gfxContentType aContentType = GFX_CONTENT_SENTINEL);
+                                gfxContentType aContentType = gfxContentType::SENTINEL);
 
   virtual TemporaryRef<BufferTextureClient>
   CreateBufferTextureClient(gfx::SurfaceFormat aFormat,
                             TextureFlags aFlags = TEXTURE_FLAGS_DEFAULT);
 
   // If we return a non-null TextureClient, then AsTextureClientDrawTarget will
   // always be non-null.
   TemporaryRef<TextureClient>
--- a/gfx/layers/client/ContentClient.cpp
+++ b/gfx/layers/client/ContentClient.cpp
@@ -36,51 +36,51 @@ namespace mozilla {
 using namespace gfx;
 
 namespace layers {
 
 /* static */ TemporaryRef<ContentClient>
 ContentClient::CreateContentClient(CompositableForwarder* aForwarder)
 {
   LayersBackend backend = aForwarder->GetCompositorBackendType();
-  if (backend != LAYERS_OPENGL &&
-      backend != LAYERS_D3D9 &&
-      backend != LAYERS_D3D11 &&
-      backend != LAYERS_BASIC) {
+  if (backend != LayersBackend::LAYERS_OPENGL &&
+      backend != LayersBackend::LAYERS_D3D9 &&
+      backend != LayersBackend::LAYERS_D3D11 &&
+      backend != LayersBackend::LAYERS_BASIC) {
     return nullptr;
   }
 
   bool useDoubleBuffering = false;
   bool useDeprecatedTextures = true;
   // XXX We need support for gralloc with non-deprecated textures content before
   // we can use them with FirefoxOS (bug 946720). We need the same locking for
   // Windows.
 #if !defined(MOZ_WIDGET_GONK) && !defined(XP_WIN)
   useDeprecatedTextures = gfxPlatform::GetPlatform()->UseDeprecatedTextures();
 #endif
 
 #ifdef XP_WIN
-  if (backend == LAYERS_D3D11) {
+  if (backend == LayersBackend::LAYERS_D3D11) {
     useDoubleBuffering = !!gfxWindowsPlatform::GetPlatform()->GetD2DDevice();
   } else
 #endif
   {
     useDoubleBuffering = LayerManagerComposite::SupportsDirectTexturing() ||
-                         backend == LAYERS_BASIC;
+                         backend == LayersBackend::LAYERS_BASIC;
   }
 
   if (useDoubleBuffering || PR_GetEnv("MOZ_FORCE_DOUBLE_BUFFERING")) {
     if (useDeprecatedTextures) {
       return new DeprecatedContentClientDoubleBuffered(aForwarder);
     } else {
       return new ContentClientDoubleBuffered(aForwarder);
     }
   }
 #ifdef XP_MACOSX
-  if (backend == LAYERS_OPENGL) {
+  if (backend == LayersBackend::LAYERS_OPENGL) {
     return new ContentClientIncremental(aForwarder);
   }
 #endif
   if (useDeprecatedTextures) {
     return new DeprecatedContentClientSingleBuffered(aForwarder);
   } else {
     return new ContentClientSingleBuffered(aForwarder);
   }
@@ -1043,18 +1043,18 @@ ContentClientIncremental::BeginPaintBuff
   // We need to disable rotation if we're going to be resampled when
   // drawing, because we might sample across the rotation boundary.
   bool canHaveRotation =  !(aFlags & RotatedContentBuffer::PAINT_WILL_RESAMPLE);
 
   nsIntRegion validRegion = aLayer->GetValidRegion();
 
   bool canUseOpaqueSurface = aLayer->CanUseOpaqueSurface();
   ContentType contentType =
-    canUseOpaqueSurface ? GFX_CONTENT_COLOR :
-                          GFX_CONTENT_COLOR_ALPHA;
+    canUseOpaqueSurface ? gfxContentType::COLOR :
+                          gfxContentType::COLOR_ALPHA;
 
   SurfaceMode mode;
   nsIntRegion neededRegion;
   bool canReuseBuffer;
   nsIntRect destBufferRect;
 
   while (true) {
     mode = aLayer->GetSurfaceMode();
@@ -1073,44 +1073,44 @@ ContentClientIncremental::BeginPaintBuff
         // The buffer's big enough but doesn't contain everything that's
         // going to be visible. We'll move it.
         destBufferRect = nsIntRect(neededRegion.GetBounds().TopLeft(), mBufferRect.Size());
       }
     } else {
       destBufferRect = neededRegion.GetBounds();
     }
 
-    if (mode == SURFACE_COMPONENT_ALPHA) {
+    if (mode == SurfaceMode::SURFACE_COMPONENT_ALPHA) {
       if (!gfxPlatform::ComponentAlphaEnabled() ||
           !aLayer->GetParent() ||
           !aLayer->GetParent()->SupportsComponentAlphaChildren()) {
-        mode = SURFACE_SINGLE_CHANNEL_ALPHA;
+        mode = SurfaceMode::SURFACE_SINGLE_CHANNEL_ALPHA;
       } else {
-        contentType = GFX_CONTENT_COLOR;
+        contentType = gfxContentType::COLOR;
       }
     }
 
     if ((aFlags & RotatedContentBuffer::PAINT_WILL_RESAMPLE) &&
         (!neededRegion.GetBounds().IsEqualInterior(destBufferRect) ||
          neededRegion.GetNumRects() > 1)) {
       // The area we add to neededRegion might not be painted opaquely
-      if (mode == SURFACE_OPAQUE) {
-        contentType = GFX_CONTENT_COLOR_ALPHA;
-        mode = SURFACE_SINGLE_CHANNEL_ALPHA;
+      if (mode == SurfaceMode::SURFACE_OPAQUE) {
+        contentType = gfxContentType::COLOR_ALPHA;
+        mode = SurfaceMode::SURFACE_SINGLE_CHANNEL_ALPHA;
       }
-      // For component alpha layers, we leave contentType as GFX_CONTENT_COLOR.
+      // For component alpha layers, we leave contentType as gfxContentType::COLOR.
 
       // We need to validate the entire buffer, to make sure that only valid
       // pixels are sampled
       neededRegion = destBufferRect;
     }
 
     if (mHasBuffer &&
         (mContentType != contentType ||
-         (mode == SURFACE_COMPONENT_ALPHA) != mHasBufferOnWhite)) {
+         (mode == SurfaceMode::SURFACE_COMPONENT_ALPHA) != mHasBufferOnWhite)) {
       // We're effectively clearing the valid region, so we need to draw
       // the entire needed region now.
       result.mRegionToInvalidate = aLayer->GetValidRegion();
       validRegion.SetEmpty();
       mHasBuffer = false;
       mHasBufferOnWhite = false;
       mBufferRect.SetRect(0, 0, 0, 0);
       mBufferRotation.MoveTo(0, 0);
@@ -1143,17 +1143,17 @@ ContentClientIncremental::BeginPaintBuff
     mBufferRotation.MoveTo(0, 0);
     canReuseBuffer = false;
   }
 
   nsIntRect drawBounds = result.mRegionToDraw.GetBounds();
   bool createdBuffer = false;
 
   uint32_t bufferFlags = canHaveRotation ? TEXTURE_ALLOW_REPEAT : 0;
-  if (mode == SURFACE_COMPONENT_ALPHA) {
+  if (mode == SurfaceMode::SURFACE_COMPONENT_ALPHA) {
     bufferFlags |= TEXTURE_COMPONENT_ALPHA;
   }
   if (canReuseBuffer) {
     nsIntRect keepArea;
     if (keepArea.IntersectRect(destBufferRect, mBufferRect)) {
       // Set mBufferRotation so that the pixels currently in mBuffer
       // will still be rendered in the right place when mBufferRect
       // changes to destBufferRect.
@@ -1196,22 +1196,22 @@ ContentClientIncremental::BeginPaintBuff
                "If we're resampling, we need to validate the entire buffer");
 
   if (!createdBuffer && !mHasBuffer) {
     return result;
   }
 
   if (createdBuffer) {
     if (mHasBuffer &&
-        (mode != SURFACE_COMPONENT_ALPHA || mHasBufferOnWhite)) {
+        (mode != SurfaceMode::SURFACE_COMPONENT_ALPHA || mHasBufferOnWhite)) {
       mTextureInfo.mDeprecatedTextureHostFlags = TEXTURE_HOST_COPY_PREVIOUS;
     }
 
     mHasBuffer = true;
-    if (mode == SURFACE_COMPONENT_ALPHA) {
+    if (mode == SurfaceMode::SURFACE_COMPONENT_ALPHA) {
       mHasBufferOnWhite = true;
     }
     mBufferRect = destBufferRect;
     mBufferRotation = nsIntPoint(0,0);
     NotifyBufferCreated(contentType, bufferFlags);
   }
 
   NS_ASSERTION(canHaveRotation || mBufferRotation == nsIntPoint(0,0),
@@ -1223,38 +1223,38 @@ ContentClientIncremental::BeginPaintBuff
 
   // If we do partial updates, we have to clip drawing to the regionToDraw.
   // If we don't clip, background images will be fillrect'd to the region correctly,
   // while text or lines will paint outside of the regionToDraw. This becomes apparent
   // with concave regions. Right now the scrollbars invalidate a narrow strip of the bar
   // although they never cover it. This leads to two draw rects, the narow strip and the actually
   // newly exposed area. It would be wise to fix this glitch in any way to have simpler
   // clip and draw regions.
-  result.mClip = CLIP_DRAW;
+  result.mClip = DrawRegionClip::DRAW;
   result.mMode = mode;
 
   return result;
 }
 
 DrawTarget*
 ContentClientIncremental::BorrowDrawTargetForPainting(ThebesLayer* aLayer,
                                                       const PaintState& aPaintState)
 {
-  if (!aPaintState.mMode) {
+  if (aPaintState.mMode == SurfaceMode::SURFACE_NONE) {
     return nullptr;
   }
 
   DrawTarget* result = nullptr;
 
   nsIntRect drawBounds = aPaintState.mRegionToDraw.GetBounds();
   MOZ_ASSERT(!mLoanedDrawTarget);
 
   // BeginUpdate is allowed to modify the given region,
   // if it wants more to be repainted than we request.
-  if (aPaintState.mMode == SURFACE_COMPONENT_ALPHA) {
+  if (aPaintState.mMode == SurfaceMode::SURFACE_COMPONENT_ALPHA) {
     nsIntRegion drawRegionCopy = aPaintState.mRegionToDraw;
     nsRefPtr<gfxASurface> onBlack = GetUpdateSurface(BUFFER_BLACK, drawRegionCopy);
     nsRefPtr<gfxASurface> onWhite = GetUpdateSurface(BUFFER_WHITE, aPaintState.mRegionToDraw);
     if (onBlack && onWhite) {
       NS_ASSERTION(aPaintState.mRegionToDraw == drawRegionCopy,
                    "BeginUpdate should always modify the draw region in the same way!");
       FillSurface(onBlack, aPaintState.mRegionToDraw, nsIntPoint(drawBounds.x, drawBounds.y), gfxRGBA(0.0, 0.0, 0.0, 1.0));
       FillSurface(onWhite, aPaintState.mRegionToDraw, nsIntPoint(drawBounds.x, drawBounds.y), gfxRGBA(1.0, 1.0, 1.0, 1.0));
@@ -1276,17 +1276,17 @@ ContentClientIncremental::BorrowDrawTarg
   }
 
   result = mLoanedDrawTarget;
   mLoanedTransform = mLoanedDrawTarget->GetTransform();
   mLoanedTransform.Translate(-drawBounds.x, -drawBounds.y);
   result->SetTransform(mLoanedTransform);
   mLoanedTransform.Translate(drawBounds.x, drawBounds.y);
 
-  if (mContentType == GFX_CONTENT_COLOR_ALPHA) {
+  if (mContentType == gfxContentType::COLOR_ALPHA) {
     gfxUtils::ClipToRegion(result, aPaintState.mRegionToDraw);
     nsIntRect bounds = aPaintState.mRegionToDraw.GetBounds();
     result->ClearRect(Rect(bounds.x, bounds.y, bounds.width, bounds.height));
   }
 
   return result;
 }
 
--- a/gfx/layers/client/ContentClient.h
+++ b/gfx/layers/client/ContentClient.h
@@ -305,17 +305,17 @@ class DeprecatedContentClientRemoteBuffe
   using RotatedContentBuffer::BufferRotation;
 public:
   DeprecatedContentClientRemoteBuffer(CompositableForwarder* aForwarder)
     : ContentClientRemote(aForwarder)
     , RotatedContentBuffer(ContainsVisibleBounds)
     , mDeprecatedTextureClient(nullptr)
     , mIsNewBuffer(false)
     , mFrontAndBackBufferDiffer(false)
-    , mContentType(GFX_CONTENT_COLOR_ALPHA)
+    , mContentType(gfxContentType::COLOR_ALPHA)
   {}
 
   typedef RotatedContentBuffer::PaintState PaintState;
   typedef RotatedContentBuffer::ContentType ContentType;
 
   virtual void Clear() { RotatedContentBuffer::Clear(); }
 
   virtual PaintState BeginPaintBuffer(ThebesLayer* aLayer,
@@ -532,17 +532,17 @@ protected:
  * new ones each frame.
  */
 class ContentClientIncremental : public ContentClientRemote
                                , public BorrowDrawTarget
 {
 public:
   ContentClientIncremental(CompositableForwarder* aFwd)
     : ContentClientRemote(aFwd)
-    , mContentType(GFX_CONTENT_COLOR_ALPHA)
+    , mContentType(gfxContentType::COLOR_ALPHA)
     , mHasBuffer(false)
     , mHasBufferOnWhite(false)
   {
     mTextureInfo.mCompositableType = BUFFER_CONTENT_INC;
   }
 
   typedef RotatedContentBuffer::PaintState PaintState;
   typedef RotatedContentBuffer::ContentType ContentType;
--- a/gfx/layers/client/TextureClient.cpp
+++ b/gfx/layers/client/TextureClient.cpp
@@ -718,17 +718,17 @@ DeprecatedTextureClientShmem::EnsureAllo
 
     mContentType = aContentType;
     mSize = aSize;
 
     if (!mForwarder->AllocSurfaceDescriptor(mSize, mContentType,
                                             &mDescriptor)) {
       NS_WARNING("creating SurfaceDescriptor failed!");
     }
-    if (mContentType == GFX_CONTENT_COLOR_ALPHA) {
+    if (mContentType == gfxContentType::COLOR_ALPHA) {
       gfxASurface* surface = GetSurface();
       if (!surface) {
         return false;
       }
       nsRefPtr<gfxContext> context = new gfxContext(surface);
       context->SetColor(gfxRGBA(0, 0, 0, 0));
       context->SetOperator(gfxContext::OPERATOR_SOURCE);
       context->Paint();
@@ -881,17 +881,17 @@ DeprecatedTextureClientTile::EnsureAlloc
   if (!mSurface ||
       mSurface->Format() != gfxPlatform::GetPlatform()->OptimalFormatForContent(aType)) {
 #ifdef MOZ_ANDROID_OMTC
     // If we're using OMTC, we can save some cycles by not using shared
     // memory. Using shared memory here is a small, but significant
     // performance regression.
     gfxImageSurface* tmpTile = new gfxImageSurface(gfxIntSize(aSize.width, aSize.height),
                                                    gfxPlatform::GetPlatform()->OptimalFormatForContent(aType),
-                                                   aType != GFX_CONTENT_COLOR);
+                                                   aType != gfxContentType::COLOR);
     mSurface = new gfxReusableImageSurfaceWrapper(tmpTile);
 #else
     nsRefPtr<gfxSharedImageSurface> sharedImage =
       gfxSharedImageSurface::CreateUnsafe(mForwarder,
                                           gfxIntSize(aSize.width, aSize.height),
                                           gfxPlatform::GetPlatform()->OptimalFormatForContent(aType));
     mSurface = new gfxReusableSharedImageSurfaceWrapper(mForwarder, sharedImage);
 #endif
@@ -922,19 +922,19 @@ bool AutoLockShmemClient::Update(Image* 
   if (!aImage) {
     return false;
   }
 
   gfx::IntSize size = aImage->GetSize();
 
   gfxContentType contentType = aSurface->GetContentType();
   bool isOpaque = (aContentFlags & Layer::CONTENT_OPAQUE);
-  if (contentType != GFX_CONTENT_ALPHA &&
+  if (contentType != gfxContentType::ALPHA &&
       isOpaque) {
-    contentType = GFX_CONTENT_COLOR;
+    contentType = gfxContentType::COLOR;
   }
   mDeprecatedTextureClient->EnsureAllocated(size, contentType);
 
   OpenMode mode = mDeprecatedTextureClient->GetAccessMode() == DeprecatedTextureClient::ACCESS_READ_WRITE
                   ? OPEN_READ_WRITE
                   : OPEN_READ_ONLY;
   nsRefPtr<gfxASurface> tmpASurface =
     ShadowLayerForwarder::OpenDescriptor(mode,
--- a/gfx/layers/client/TextureClient.h
+++ b/gfx/layers/client/TextureClient.h
@@ -620,17 +620,17 @@ public:
   { }
   ~DeprecatedTextureClientShmemYCbCr() { ReleaseResources(); }
 
   virtual bool SupportsType(DeprecatedTextureClientType aType) MOZ_OVERRIDE { return aType == TEXTURE_YCBCR; }
   bool EnsureAllocated(gfx::IntSize aSize, gfxContentType aType) MOZ_OVERRIDE;
   virtual void SetDescriptorFromReply(const SurfaceDescriptor& aDescriptor) MOZ_OVERRIDE;
   virtual void SetDescriptor(const SurfaceDescriptor& aDescriptor) MOZ_OVERRIDE;
   virtual void ReleaseResources();
-  virtual gfxContentType GetContentType() MOZ_OVERRIDE { return GFX_CONTENT_COLOR_ALPHA; }
+  virtual gfxContentType GetContentType() MOZ_OVERRIDE { return gfxContentType::COLOR_ALPHA; }
 };
 
 class DeprecatedTextureClientTile : public DeprecatedTextureClient
 {
 public:
   DeprecatedTextureClientTile(const DeprecatedTextureClientTile& aOther);
   DeprecatedTextureClientTile(CompositableForwarder* aForwarder,
                               const TextureInfo& aTextureInfo,
--- a/gfx/layers/client/TiledContentClient.cpp
+++ b/gfx/layers/client/TiledContentClient.cpp
@@ -243,19 +243,19 @@ BasicTiledLayerBuffer::HasFormatChanged(
   return mThebesLayer->CanUseOpaqueSurface() != mLastPaintOpaque;
 }
 
 
 gfxContentType
 BasicTiledLayerBuffer::GetContentType() const
 {
   if (mThebesLayer->CanUseOpaqueSurface()) {
-    return GFX_CONTENT_COLOR;
+    return gfxContentType::COLOR;
   } else {
-    return GFX_CONTENT_COLOR_ALPHA;
+    return gfxContentType::COLOR_ALPHA;
   }
 }
 
 
 TileDescriptor
 BasicTiledLayerTile::GetTileDescriptor()
 {
   gfxReusableSurfaceWrapper* surface = GetSurface();
@@ -399,17 +399,17 @@ BasicTiledLayerBuffer::PaintThebes(const
 #ifdef GFX_TILEDLAYER_PREF_WARNINGS
     if (PR_IntervalNow() - start > 3) {
       printf_stderr("Slow alloc %i\n", PR_IntervalNow() - start);
     }
     start = PR_IntervalNow();
 #endif
     PROFILER_LABEL("BasicTiledLayerBuffer", "PaintThebesSingleBufferDraw");
 
-    mCallback(mThebesLayer, ctxt, aPaintRegion, CLIP_NONE, nsIntRegion(), mCallbackData);
+    mCallback(mThebesLayer, ctxt, aPaintRegion, DrawRegionClip::CLIP_NONE, nsIntRegion(), mCallbackData);
   }
 
 #ifdef GFX_TILEDLAYER_PREF_WARNINGS
   if (PR_IntervalNow() - start > 30) {
     const nsIntRect bounds = aPaintRegion.GetBounds();
     printf_stderr("Time to draw %i: %i, %i, %i, %i\n", PR_IntervalNow() - start, bounds.x, bounds.y, bounds.width, bounds.height);
     if (aPaintRegion.IsComplex()) {
       printf_stderr("Complex region\n");
@@ -508,17 +508,17 @@ BasicTiledLayerBuffer::ValidateTileInter
   } else {
     ctxt->NewPath();
     ctxt->Scale(mResolution, mResolution);
     ctxt->Translate(gfxPoint(-aTileOrigin.x, -aTileOrigin.y));
     nsIntPoint a = nsIntPoint(aTileOrigin.x, aTileOrigin.y);
     mCallback(mThebesLayer, ctxt,
               nsIntRegion(nsIntRect(a, nsIntSize(GetScaledTileLength(),
                                                  GetScaledTileLength()))),
-              CLIP_NONE,
+              DrawRegionClip::CLIP_NONE,
               nsIntRegion(), mCallbackData);
   }
 
 #ifdef GFX_TILEDLAYER_DEBUG_OVERLAY
   DrawDebugOverlay(writableSurface, aTileOrigin.x * mResolution,
                    aTileOrigin.y * mResolution);
 #endif
 
--- a/gfx/layers/composite/ImageLayerComposite.cpp
+++ b/gfx/layers/composite/ImageLayerComposite.cpp
@@ -114,19 +114,19 @@ ImageLayerComposite::ComputeEffectiveTra
   gfxRect sourceRect(0, 0, 0, 0);
   if (mImageHost &&
       mImageHost->IsAttached() &&
       (mImageHost->GetDeprecatedTextureHost() || mImageHost->GetAsTextureHost())) {
     IntSize size =
       mImageHost->GetAsTextureHost() ? mImageHost->GetAsTextureHost()->GetSize()
                                      : mImageHost->GetDeprecatedTextureHost()->GetSize();
     sourceRect.SizeTo(size.width, size.height);
-    if (mScaleMode != SCALE_NONE &&
+    if (mScaleMode != ScaleMode::SCALE_NONE &&
         sourceRect.width != 0.0 && sourceRect.height != 0.0) {
-      NS_ASSERTION(mScaleMode == SCALE_STRETCH,
+      NS_ASSERTION(mScaleMode == ScaleMode::STRETCH,
                    "No other scalemodes than stretch and none supported yet.");
       local.Scale(mScaleToSize.width / sourceRect.width,
                   mScaleToSize.height / sourceRect.height, 1.0);
     }
   }
   // Snap our local transform first, and snap the inherited transform as well.
   // This makes our snapping equivalent to what would happen if our content
   // was drawn into a ThebesLayer (gfxContext would snap using the local
--- a/gfx/layers/composite/LayerManagerComposite.cpp
+++ b/gfx/layers/composite/LayerManagerComposite.cpp
@@ -147,17 +147,17 @@ LayerManagerComposite::BeginTransaction(
   mInTransaction = true;
   
   if (!mCompositor->Ready()) {
     return;
   }
   
   mIsCompositorReady = true;
 
-  if (Compositor::GetBackend() == LAYERS_BASIC) {
+  if (Compositor::GetBackend() == LayersBackend::LAYERS_BASIC) {
     mClonedLayerTreeProperties = LayerProperties::CloneFrom(GetRoot());
   }
 }
 
 void
 LayerManagerComposite::BeginTransactionWithDrawTarget(DrawTarget* aTarget)
 {
   mInTransaction = true;
--- a/gfx/layers/composite/TextureHost.cpp
+++ b/gfx/layers/composite/TextureHost.cpp
@@ -106,38 +106,38 @@ TemporaryRef<DeprecatedTextureHost> Crea
 
 /* static */ TemporaryRef<DeprecatedTextureHost>
 DeprecatedTextureHost::CreateDeprecatedTextureHost(SurfaceDescriptorType aDescriptorType,
                                            uint32_t aDeprecatedTextureHostFlags,
                                            uint32_t aTextureFlags,
                                            CompositableHost* aCompositableHost)
 {
   switch (Compositor::GetBackend()) {
-    case LAYERS_OPENGL:
+    case LayersBackend::LAYERS_OPENGL:
       {
       RefPtr<DeprecatedTextureHost> result;
       result = CreateDeprecatedTextureHostOGL(aDescriptorType,
                                         aDeprecatedTextureHostFlags,
                                         aTextureFlags);
       if (aCompositableHost) {
         result->SetCompositableBackendSpecificData(aCompositableHost->GetCompositableBackendSpecificData());
       }
       return result;
       }
 #ifdef XP_WIN
-    case LAYERS_D3D9:
+    case LayersBackend::LAYERS_D3D9:
       return CreateDeprecatedTextureHostD3D9(aDescriptorType,
                                          aDeprecatedTextureHostFlags,
                                          aTextureFlags);
-    case LAYERS_D3D11:
+    case LayersBackend::LAYERS_D3D11:
       return CreateDeprecatedTextureHostD3D11(aDescriptorType,
                                           aDeprecatedTextureHostFlags,
                                           aTextureFlags);
 #endif
-    case LAYERS_BASIC:
+    case LayersBackend::LAYERS_BASIC:
       return CreateBasicDeprecatedTextureHost(aDescriptorType,
                                           aDeprecatedTextureHostFlags,
                                           aTextureFlags);
     default:
       MOZ_CRASH("Couldn't create texture host");
   }
 }
 
@@ -163,31 +163,31 @@ TemporaryRef<TextureHost> CreateTextureH
 
 // static
 TemporaryRef<TextureHost>
 TextureHost::Create(const SurfaceDescriptor& aDesc,
                     ISurfaceAllocator* aDeallocator,
                     TextureFlags aFlags)
 {
   switch (Compositor::GetBackend()) {
-    case LAYERS_OPENGL:
+    case LayersBackend::LAYERS_OPENGL:
       return CreateTextureHostOGL(aDesc, aDeallocator, aFlags);
-    case LAYERS_BASIC:
+    case LayersBackend::LAYERS_BASIC:
       return CreateTextureHostBasic(aDesc, aDeallocator, aFlags);
 #ifdef MOZ_WIDGET_GONK
-    case LAYERS_NONE:
+    case LayersBackend::LAYERS_NONE:
       // Power on video reqests to allocate TextureHost,
       // when Compositor is still not present. This is a very hacky workaround.
       // See Bug 944420.
       return CreateTextureHostOGL(aDesc, aDeallocator, aFlags);
 #endif
 #ifdef XP_WIN
-    case LAYERS_D3D11:
+    case LayersBackend::LAYERS_D3D11:
       return CreateTextureHostD3D11(aDesc, aDeallocator, aFlags);
-    case LAYERS_D3D9:
+    case LayersBackend::LAYERS_D3D9:
       return CreateTextureHostD3D9(aDesc, aDeallocator, aFlags);
 #endif
     default:
       MOZ_CRASH("Couldn't create texture host");
       return nullptr;
   }
 }
 
--- a/gfx/layers/d3d10/CanvasLayerD3D10.cpp
+++ b/gfx/layers/d3d10/CanvasLayerD3D10.cpp
@@ -94,24 +94,24 @@ CanvasLayerD3D10::Initialize(const Data&
     // bypassing Thebes
     mSurface = gfxPlatform::GetPlatform()->GetThebesSurfaceForDrawTarget(mDrawTarget);
   } else {
     NS_ERROR("CanvasLayer created without mSurface, mDrawTarget or mGLContext?");
   }
 
   mBounds.SetRect(0, 0, aData.mSize.width, aData.mSize.height);
 
-  if (mSurface && mSurface->GetType() == gfxSurfaceTypeD2D) {
+  if (mSurface && mSurface->GetType() == gfxSurfaceType::D2D) {
     void *data = mSurface->GetData(&gKeyD3D10Texture);
     if (data) {
       mTexture = static_cast<ID3D10Texture2D*>(data);
       mIsD2DTexture = true;
       device()->CreateShaderResourceView(mTexture, nullptr, getter_AddRefs(mSRView));
       mHasAlpha =
-        mSurface->GetContentType() == GFX_CONTENT_COLOR_ALPHA;
+        mSurface->GetContentType() == gfxContentType::COLOR_ALPHA;
       return;
     }
   }
 
   mIsD2DTexture = false;
 
   // Create a texture in case we need to readback.
   CD3D10_TEXTURE2D_DESC desc(DXGI_FORMAT_B8G8R8A8_UNORM, mBounds.width, mBounds.height, 1, 1);
@@ -203,17 +203,17 @@ CanvasLayerD3D10::UpdateSurface()
       return;
     }
 
     nsRefPtr<gfxImageSurface> dstSurface;
 
     dstSurface = new gfxImageSurface((unsigned char*)map.pData,
                                      gfxIntSize(mBounds.width, mBounds.height),
                                      map.RowPitch,
-                                     gfxImageFormatARGB32);
+                                     gfxImageFormat::ARGB32);
     nsRefPtr<gfxContext> ctx = new gfxContext(dstSurface);
     ctx->SetOperator(gfxContext::OPERATOR_SOURCE);
     ctx->SetSource(mSurface);
     ctx->Paint();
     
     mTexture->Unmap(0);
     mSRView = mUploadSRView;
   }
--- a/gfx/layers/d3d10/ImageLayerD3D10.cpp
+++ b/gfx/layers/d3d10/ImageLayerD3D10.cpp
@@ -52,33 +52,33 @@ static already_AddRefed<ID3D10Texture2D>
 SurfaceToTexture(ID3D10Device *aDevice,
                  gfxASurface *aSurface,
                  const IntSize &aSize)
 {
   if (!aSurface) {
     return nullptr;
   }
 
-  if (aSurface->GetType() == gfxSurfaceTypeD2D) {
+  if (aSurface->GetType() == gfxSurfaceType::D2D) {
     void *data = aSurface->GetData(&gKeyD3D10Texture);
     if (data) {
       nsRefPtr<ID3D10Texture2D> texture = static_cast<ID3D10Texture2D*>(data);
       ID3D10Device *dev;
       texture->GetDevice(&dev);
       if (dev == aDevice) {
         return texture.forget();
       }
     }
   }
 
   nsRefPtr<gfxImageSurface> imageSurface = aSurface->GetAsImageSurface();
 
   if (!imageSurface) {
     imageSurface = new gfxImageSurface(ThebesIntSize(aSize),
-                                       gfxImageFormatARGB32);
+                                       gfxImageFormat::ARGB32);
 
     nsRefPtr<gfxContext> context = new gfxContext(imageSurface);
     context->SetSource(aSurface);
     context->SetOperator(gfxContext::OPERATOR_SOURCE);
     context->Paint();
   }
 
   return DataToTexture(aDevice, imageSurface->Data(), imageSurface->Stride(), aSize);
@@ -100,23 +100,23 @@ ID3D10ShaderResourceView*
 ImageLayerD3D10::GetImageSRView(Image* aImage, bool& aHasAlpha, IDXGIKeyedMutex **aMutex)
 {
   NS_ASSERTION(aImage, "Null image.");
 
   if (aImage->GetFormat() == ImageFormat::REMOTE_IMAGE_BITMAP) {
     RemoteBitmapImage *remoteImage =
       static_cast<RemoteBitmapImage*>(aImage);
 
-    if (!aImage->GetBackendData(mozilla::layers::LAYERS_D3D10)) {
+    if (!aImage->GetBackendData(mozilla::layers::LayersBackend::LAYERS_D3D10)) {
       nsAutoPtr<TextureD3D10BackendData> dat(new TextureD3D10BackendData());
       dat->mTexture = DataToTexture(device(), remoteImage->mData, remoteImage->mStride, remoteImage->mSize);
 
       if (dat->mTexture) {
         device()->CreateShaderResourceView(dat->mTexture, nullptr, getter_AddRefs(dat->mSRView));
-        aImage->SetBackendData(mozilla::layers::LAYERS_D3D10, dat.forget());
+        aImage->SetBackendData(mozilla::layers::LayersBackend::LAYERS_D3D10, dat.forget());
       }
     }
 
     aHasAlpha = remoteImage->mFormat == RemoteImageData::BGRA32;
   } else if (aImage->GetFormat() == ImageFormat::REMOTE_IMAGE_DXGI_TEXTURE) {
     RemoteDXGITextureImage *remoteImage =
       static_cast<RemoteDXGITextureImage*>(aImage);
 
@@ -127,54 +127,54 @@ ImageLayerD3D10::GetImageSRView(Image* a
     CairoImage *cairoImage =
       static_cast<CairoImage*>(aImage);
 
     nsRefPtr<gfxASurface> surf = cairoImage->DeprecatedGetAsSurface();
     if (!surf) {
       return nullptr;
     }
 
-    if (!aImage->GetBackendData(mozilla::layers::LAYERS_D3D10)) {
+    if (!aImage->GetBackendData(mozilla::layers::LayersBackend::LAYERS_D3D10)) {
       nsAutoPtr<TextureD3D10BackendData> dat(new TextureD3D10BackendData());
       dat->mTexture = SurfaceToTexture(device(), surf, cairoImage->GetSize());
 
       if (dat->mTexture) {
         device()->CreateShaderResourceView(dat->mTexture, nullptr, getter_AddRefs(dat->mSRView));
-        aImage->SetBackendData(mozilla::layers::LAYERS_D3D10, dat.forget());
+        aImage->SetBackendData(mozilla::layers::LayersBackend::LAYERS_D3D10, dat.forget());
       }
     }
 
-    aHasAlpha = surf->GetContentType() == GFX_CONTENT_COLOR_ALPHA;
+    aHasAlpha = surf->GetContentType() == gfxContentType::COLOR_ALPHA;
   } else if (aImage->GetFormat() == ImageFormat::D3D9_RGB32_TEXTURE) {
-    if (!aImage->GetBackendData(mozilla::layers::LAYERS_D3D10)) {
+    if (!aImage->GetBackendData(mozilla::layers::LayersBackend::LAYERS_D3D10)) {
       // Use resource sharing to open the D3D9 texture as a D3D10 texture,
       HRESULT hr;
       D3D9SurfaceImage* d3dImage = reinterpret_cast<D3D9SurfaceImage*>(aImage);
       nsRefPtr<ID3D10Texture2D> texture;
       hr = device()->OpenSharedResource(d3dImage->GetShareHandle(),
                                         IID_ID3D10Texture2D,
                                         (void**)getter_AddRefs(texture));
       NS_ENSURE_TRUE(SUCCEEDED(hr), nullptr);
 
       nsAutoPtr<TextureD3D10BackendData> dat(new TextureD3D10BackendData());
       dat->mTexture = texture;
 
       hr = device()->CreateShaderResourceView(dat->mTexture, nullptr, getter_AddRefs(dat->mSRView));
       NS_ENSURE_TRUE(SUCCEEDED(hr) && dat->mSRView, nullptr);
 
-      aImage->SetBackendData(mozilla::layers::LAYERS_D3D10, dat.forget());
+      aImage->SetBackendData(mozilla::layers::LayersBackend::LAYERS_D3D10, dat.forget());
     }
     aHasAlpha = false;
   } else {
     NS_WARNING("Incorrect image type.");
     return nullptr;
   }
 
   TextureD3D10BackendData *data =
-    static_cast<TextureD3D10BackendData*>(aImage->GetBackendData(mozilla::layers::LAYERS_D3D10));
+    static_cast<TextureD3D10BackendData*>(aImage->GetBackendData(mozilla::layers::LayersBackend::LAYERS_D3D10));
 
   if (!data) {
     return nullptr;
   }
 
   if (aMutex &&
       SUCCEEDED(data->mTexture->QueryInterface(IID_IDXGIKeyedMutex, (void**)aMutex))) {
     if (FAILED((*aMutex)->AcquireSync(0, 0))) {
@@ -215,17 +215,17 @@ ImageLayerD3D10::RenderLayer()
   nsRefPtr<IDXGIKeyedMutex> keyedMutex;
   nsRefPtr<gfxASurface> surf = image->DeprecatedGetAsSurface();
 
   if (image->GetFormat() == ImageFormat::CAIRO_SURFACE ||
       image->GetFormat() == ImageFormat::REMOTE_IMAGE_BITMAP ||
       image->GetFormat() == ImageFormat::REMOTE_IMAGE_DXGI_TEXTURE ||
       image->GetFormat() == ImageFormat::D3D9_RGB32_TEXTURE) {
     NS_ASSERTION(image->GetFormat() != ImageFormat::CAIRO_SURFACE ||
-                 !surf || surf->GetContentType() != GFX_CONTENT_ALPHA,
+                 !surf || surf->GetContentType() != gfxContentType::ALPHA,
                  "Image layer has alpha image");
     bool hasAlpha = false;
 
     nsRefPtr<ID3D10ShaderResourceView> srView = GetImageSRView(image, hasAlpha, getter_AddRefs(keyedMutex));
     if (!srView) {
       return;
     }
 
@@ -250,22 +250,22 @@ ImageLayerD3D10::RenderLayer()
   } else if (image->GetFormat() == ImageFormat::PLANAR_YCBCR) {
     PlanarYCbCrImage *yuvImage =
       static_cast<PlanarYCbCrImage*>(image);
 
     if (!yuvImage->IsValid()) {
       return;
     }
 
-    if (!yuvImage->GetBackendData(mozilla::layers::LAYERS_D3D10)) {
+    if (!yuvImage->GetBackendData(mozilla::layers::LayersBackend::LAYERS_D3D10)) {
       AllocateTexturesYCbCr(yuvImage);
     }
 
     PlanarYCbCrD3D10BackendData *data =
-      static_cast<PlanarYCbCrD3D10BackendData*>(yuvImage->GetBackendData(mozilla::layers::LAYERS_D3D10));
+      static_cast<PlanarYCbCrD3D10BackendData*>(yuvImage->GetBackendData(mozilla::layers::LayersBackend::LAYERS_D3D10));
 
     if (!data) {
       return;
     }
 
     nsRefPtr<ID3D10Device> dev;
     data->mYTexture->GetDevice(getter_AddRefs(dev));
     if (dev != device()) {
@@ -389,17 +389,17 @@ void ImageLayerD3D10::AllocateTexturesYC
     LayerManagerD3D10::ReportFailure(NS_LITERAL_CSTRING("PlanarYCbCrImageD3D10::AllocateTextures(): Failed to create texture"),
                                      hr);
     return;
   }
   device()->CreateShaderResourceView(backendData->mYTexture, nullptr, getter_AddRefs(backendData->mYView));
   device()->CreateShaderResourceView(backendData->mCbTexture, nullptr, getter_AddRefs(backendData->mCbView));
   device()->CreateShaderResourceView(backendData->mCrTexture, nullptr, getter_AddRefs(backendData->mCrView));
 
-  aImage->SetBackendData(mozilla::layers::LAYERS_D3D10, backendData.forget());
+  aImage->SetBackendData(mozilla::layers::LayersBackend::LAYERS_D3D10, backendData.forget());
 }
 
 already_AddRefed<ID3D10ShaderResourceView>
 ImageLayerD3D10::GetAsTexture(gfx::IntSize* aSize)
 {
   if (!GetContainer()) {
     return nullptr;
   }
@@ -467,18 +467,18 @@ RemoteDXGITextureImage::DeprecatedGetAsS
   }
 
   device->CopyResource(softTexture, data->mTexture);
   keyedMutex->ReleaseSync(0);
 
   nsRefPtr<gfxImageSurface> surface =
     new gfxImageSurface(ThebesIntSize(mSize),
       mFormat == RemoteImageData::BGRX32 ?
-                 gfxImageFormatRGB24 :
-                 gfxImageFormatARGB32);
+                 gfxImageFormat::RGB24 :
+                 gfxImageFormat::ARGB32);
 
   if (!surface->CairoSurface() || surface->CairoStatus()) {
     NS_WARNING("Failed to created image surface for DXGI texture.");
     return nullptr;
   }
 
   D3D10_MAPPED_TEXTURE2D mapped;
   softTexture->Map(0, D3D10_MAP_READ, 0, &mapped);
@@ -492,19 +492,19 @@ RemoteDXGITextureImage::DeprecatedGetAsS
   softTexture->Unmap(0);
 
   return surface.forget();
 }
 
 TextureD3D10BackendData*
 RemoteDXGITextureImage::GetD3D10TextureBackendData(ID3D10Device *aDevice)
 {
-  if (GetBackendData(mozilla::layers::LAYERS_D3D10)) {
+  if (GetBackendData(mozilla::layers::LayersBackend::LAYERS_D3D10)) {
     TextureD3D10BackendData *data =
-      static_cast<TextureD3D10BackendData*>(GetBackendData(mozilla::layers::LAYERS_D3D10));
+      static_cast<TextureD3D10BackendData*>(GetBackendData(mozilla::layers::LayersBackend::LAYERS_D3D10));
 
     nsRefPtr<ID3D10Device> device;
     data->mTexture->GetDevice(getter_AddRefs(device));
 
     if (device == aDevice) {
       return data;
     }
   }
@@ -517,15 +517,15 @@ RemoteDXGITextureImage::GetD3D10TextureB
   }
 
   nsAutoPtr<TextureD3D10BackendData> data(new TextureD3D10BackendData());
 
   data->mTexture = texture;
 
   aDevice->CreateShaderResourceView(texture, nullptr, getter_AddRefs(data->mSRView));
 
-  SetBackendData(mozilla::layers::LAYERS_D3D10, data);
+  SetBackendData(mozilla::layers::LayersBackend::LAYERS_D3D10, data);
 
   return data.forget();
 }
 
 } /* layers */
 } /* mozilla */
--- a/gfx/layers/d3d10/LayerManagerD3D10.cpp
+++ b/gfx/layers/d3d10/LayerManagerD3D10.cpp
@@ -449,18 +449,18 @@ static void ReleaseTexture(void *texture
 {
   static_cast<ID3D10Texture2D*>(texture)->Release();
 }
 
 already_AddRefed<gfxASurface>
 LayerManagerD3D10::CreateOptimalSurface(const IntSize &aSize,
                                         gfxImageFormat aFormat)
 {
-  if ((aFormat != gfxImageFormatRGB24 &&
-       aFormat != gfxImageFormatARGB32)) {
+  if ((aFormat != gfxImageFormat::RGB24 &&
+       aFormat != gfxImageFormat::ARGB32)) {
     return LayerManager::CreateOptimalSurface(aSize, aFormat);
   }
 
   nsRefPtr<ID3D10Texture2D> texture;
   
   CD3D10_TEXTURE2D_DESC desc(DXGI_FORMAT_B8G8R8A8_UNORM, aSize.width, aSize.height, 1, 1);
   desc.BindFlags = D3D10_BIND_RENDER_TARGET | D3D10_BIND_SHADER_RESOURCE;
   desc.MiscFlags = D3D10_RESOURCE_MISC_GDI_COMPATIBLE;
@@ -468,35 +468,35 @@ LayerManagerD3D10::CreateOptimalSurface(
   HRESULT hr = device()->CreateTexture2D(&desc, nullptr, getter_AddRefs(texture));
 
   if (FAILED(hr)) {
     NS_WARNING("Failed to create new texture for CreateOptimalSurface!");
     return LayerManager::CreateOptimalSurface(aSize, aFormat);
   }
 
   nsRefPtr<gfxD2DSurface> surface =
-    new gfxD2DSurface(texture, aFormat == gfxImageFormatRGB24 ?
-      GFX_CONTENT_COLOR : GFX_CONTENT_COLOR_ALPHA);
+    new gfxD2DSurface(texture, aFormat == gfxImageFormat::RGB24 ?
+      gfxContentType::COLOR : gfxContentType::COLOR_ALPHA);
 
   if (!surface || surface->CairoStatus()) {
     return LayerManager::CreateOptimalSurface(aSize, aFormat);
   }
 
   surface->SetData(&gKeyD3D10Texture,
                    texture.forget().get(),
                    ReleaseTexture);
 
   return surface.forget();
 }
 
 
 already_AddRefed<gfxASurface>
 LayerManagerD3D10::CreateOptimalMaskSurface(const IntSize &aSize)
 {
-  return CreateOptimalSurface(aSize, gfxImageFormatARGB32);
+  return CreateOptimalSurface(aSize, gfxImageFormat::ARGB32);
 }
 
 
 TemporaryRef<DrawTarget>
 LayerManagerD3D10::CreateDrawTarget(const IntSize &aSize,
                                     SurfaceFormat aFormat)
 {
   if ((aFormat != SurfaceFormat::B8G8R8A8 &&
@@ -767,17 +767,17 @@ LayerManagerD3D10::PaintToTarget()
 
   D3D10_MAPPED_TEXTURE2D map;
   readTexture->Map(0, D3D10_MAP_READ, 0, &map);
 
   nsRefPtr<gfxImageSurface> tmpSurface =
     new gfxImageSurface((unsigned char*)map.pData,
                         gfxIntSize(bbDesc.Width, bbDesc.Height),
                         map.RowPitch,
-                        gfxImageFormatARGB32);
+                        gfxImageFormat::ARGB32);
 
   mTarget->SetSource(tmpSurface);
   mTarget->SetOperator(gfxContext::OPERATOR_OVER);
   mTarget->Paint();
 
   readTexture->Unmap(0);
 }
 
--- a/gfx/layers/d3d10/LayerManagerD3D10.h
+++ b/gfx/layers/d3d10/LayerManagerD3D10.h
@@ -115,17 +115,17 @@ public:
 
   virtual already_AddRefed<gfxASurface>
     CreateOptimalMaskSurface(const gfx::IntSize &aSize);
 
   virtual TemporaryRef<mozilla::gfx::DrawTarget>
     CreateDrawTarget(const gfx::IntSize &aSize,
                      mozilla::gfx::SurfaceFormat aFormat);
 
-  virtual LayersBackend GetBackendType() { return LAYERS_D3D10; }
+  virtual LayersBackend GetBackendType() { return LayersBackend::LAYERS_D3D10; }
   virtual void GetBackendName(nsAString& name) { name.AssignLiteral("Direct3D 10"); }
 
   virtual const char* Name() const { return "D3D10"; }
 
   // Public helpers
 
   ID3D10Device1 *device() const { return mDevice; }
 
--- a/gfx/layers/d3d10/ReadbackManagerD3D10.cpp
+++ b/gfx/layers/d3d10/ReadbackManagerD3D10.cpp
@@ -67,17 +67,17 @@ public:
       update->mLayer->GetSink()->SetUnknown(update->mSequenceCounter);
       return NS_OK;
     }
 
     nsRefPtr<gfxImageSurface> sourceSurface =
       new gfxImageSurface((unsigned char*)mappedTex.pData,
                           gfxIntSize(desc.Width, desc.Height),
                           mappedTex.RowPitch,
-                          gfxImageFormatRGB24);
+                          gfxImageFormat::RGB24);
 
     nsRefPtr<gfxContext> ctx =
       update->mLayer->GetSink()->BeginUpdate(update->mUpdateRect + offset,
                                              update->mSequenceCounter);
 
     if (ctx) {
       ctx->Translate(gfxPoint(offset.x, offset.y));
       ctx->SetSource(sourceSurface, gfxPoint(mTask->mOrigin.x,
--- a/gfx/layers/d3d10/ThebesLayerD3D10.cpp
+++ b/gfx/layers/d3d10/ThebesLayerD3D10.cpp
@@ -29,17 +29,17 @@
 using namespace mozilla::gfx;
 
 namespace mozilla {
 namespace layers {
 
 ThebesLayerD3D10::ThebesLayerD3D10(LayerManagerD3D10 *aManager)
   : ThebesLayer(aManager, nullptr)
   , LayerD3D10(aManager)
-  , mCurrentSurfaceMode(SURFACE_OPAQUE)
+  , mCurrentSurfaceMode(SurfaceMode::SURFACE_OPAQUE)
 {
   mImplData = static_cast<LayerD3D10*>(this);
 }
 
 ThebesLayerD3D10::~ThebesLayerD3D10()
 {
 }
 
@@ -89,23 +89,23 @@ ThebesLayerD3D10::RenderLayer()
   if (!mTexture) {
     return;
   }
 
   SetEffectTransformAndOpacity();
 
   ID3D10EffectTechnique *technique;
   switch (mCurrentSurfaceMode) {
-  case SURFACE_COMPONENT_ALPHA:
+  case SurfaceMode::SURFACE_COMPONENT_ALPHA:
     technique = SelectShader(SHADER_COMPONENT_ALPHA | LoadMaskTexture());
     break;
-  case SURFACE_OPAQUE:
+  case SurfaceMode::SURFACE_OPAQUE:
     technique = SelectShader(SHADER_RGB | SHADER_PREMUL | LoadMaskTexture());
     break;
-  case SURFACE_SINGLE_CHANNEL_ALPHA:
+  case SurfaceMode::SURFACE_SINGLE_CHANNEL_ALPHA:
     technique = SelectShader(SHADER_RGBA | SHADER_PREMUL | LoadMaskTexture());
     break;
   default:
     NS_ERROR("Unknown mode");
     return;
   }
 
   nsIntRegionRectIterator iter(mVisibleRegion);
@@ -149,35 +149,35 @@ ThebesLayerD3D10::Validate(ReadbackProce
 {
   if (mVisibleRegion.IsEmpty()) {
     return;
   }
 
   nsIntRect newTextureRect = mVisibleRegion.GetBounds();
 
   SurfaceMode mode = GetSurfaceMode();
-  if (mode == SURFACE_COMPONENT_ALPHA &&
+  if (mode == SurfaceMode::SURFACE_COMPONENT_ALPHA &&
       (!mParent || !mParent->SupportsComponentAlphaChildren())) {
-    mode = SURFACE_SINGLE_CHANNEL_ALPHA;
+    mode = SurfaceMode::SURFACE_SINGLE_CHANNEL_ALPHA;
   }
   // If we have a transform that requires resampling of our texture, then
   // we need to make sure we don't sample pixels that haven't been drawn.
   // We clamp sample coordinates to the texture rect, but when the visible region
   // doesn't fill the entire texture rect we need to make sure we draw all the
   // pixels in the texture rect anyway in case they get sampled.
   nsIntRegion neededRegion = mVisibleRegion;
   if (!neededRegion.GetBounds().IsEqualInterior(newTextureRect) ||
       neededRegion.GetNumRects() > 1) {
     if (MayResample()) {
       neededRegion = newTextureRect;
-      if (mode == SURFACE_OPAQUE) {
+      if (mode == SurfaceMode::SURFACE_OPAQUE) {
         // We're going to paint outside the visible region, but layout hasn't
         // promised that it will paint opaquely there, so we'll have to
         // treat this layer as transparent.
-        mode = SURFACE_SINGLE_CHANNEL_ALPHA;
+        mode = SurfaceMode::SURFACE_SINGLE_CHANNEL_ALPHA;
       }
     }
   }
   mCurrentSurfaceMode = mode;
 
   VerifyContentType(mode);
 
   nsTArray<ReadbackProcessor::Update> readbackUpdates;
@@ -221,17 +221,17 @@ ThebesLayerD3D10::Validate(ReadbackProce
                      mTextureOnWhite, newTextureRect.TopLeft(),
                      retainRegion, &mValidRegion);
         }
       }
     }
   }
   mTextureRect = newTextureRect;
 
-  if (!mTexture || (mode == SURFACE_COMPONENT_ALPHA && !mTextureOnWhite)) {
+  if (!mTexture || (mode == SurfaceMode::SURFACE_COMPONENT_ALPHA && !mTextureOnWhite)) {
     CreateNewTextures(gfx::IntSize(newTextureRect.width, newTextureRect.height), mode);
     mValidRegion.SetEmpty();
   }
 
   nsIntRegion drawRegion;
   drawRegion.Sub(neededRegion, mValidRegion);
 
   if (!drawRegion.IsEmpty()) {
@@ -281,47 +281,47 @@ ThebesLayerD3D10::GetLayer()
 {
   return this;
 }
 
 void
 ThebesLayerD3D10::VerifyContentType(SurfaceMode aMode)
 {
   if (mD2DSurface) {
-    gfxContentType type = aMode != SURFACE_SINGLE_CHANNEL_ALPHA ?
-      GFX_CONTENT_COLOR : GFX_CONTENT_COLOR_ALPHA;
+    gfxContentType type = aMode != SurfaceMode::SURFACE_SINGLE_CHANNEL_ALPHA ?
+      gfxContentType::COLOR : gfxContentType::COLOR_ALPHA;
 
     if (type != mD2DSurface->GetContentType()) {  
       mD2DSurface = new gfxD2DSurface(mTexture, type);
 
       if (!mD2DSurface || mD2DSurface->CairoStatus()) {
         NS_WARNING("Failed to create surface for ThebesLayerD3D10.");
         mD2DSurface = nullptr;
         return;
       }
 
       mValidRegion.SetEmpty();
     }
   } else if (mDrawTarget) {
-    SurfaceFormat format = aMode != SURFACE_SINGLE_CHANNEL_ALPHA ?
+    SurfaceFormat format = aMode != SurfaceMode::SURFACE_SINGLE_CHANNEL_ALPHA ?
       SurfaceFormat::B8G8R8X8 : SurfaceFormat::B8G8R8A8;
 
     if (format != mDrawTarget->GetFormat()) {
       mDrawTarget = Factory::CreateDrawTargetForD3D10Texture(mTexture, format);
 
       if (!mDrawTarget) {
         NS_WARNING("Failed to create drawtarget for ThebesLayerD3D10.");
         return;
       }
 
       mValidRegion.SetEmpty();
     }
   }    
 
-  if (aMode != SURFACE_COMPONENT_ALPHA && mTextureOnWhite) {
+  if (aMode != SurfaceMode::SURFACE_COMPONENT_ALPHA && mTextureOnWhite) {
     // If we've transitioned away from component alpha, we can delete those resources.
     mD2DSurfaceOnWhite = nullptr;
     mSRViewOnWhite = nullptr;
     mTextureOnWhite = nullptr;
     mValidRegion.SetEmpty();
   }
 }
 
@@ -395,17 +395,17 @@ ThebesLayerD3D10::DrawRegion(nsIntRegion
   nsIntRect visibleRect = mVisibleRegion.GetBounds();
 
   if (!mD2DSurface && !mDrawTarget) {
     return;
   }
 
   nsRefPtr<gfxASurface> destinationSurface;
   
-  if (aMode == SURFACE_COMPONENT_ALPHA) {
+  if (aMode == SurfaceMode::SURFACE_COMPONENT_ALPHA) {
     FillTexturesBlackWhite(aRegion, visibleRect.TopLeft());
     if (!gfxPlatform::GetPlatform()->SupportsAzureContent()) {
       gfxASurface* surfaces[2] = { mD2DSurface.get(), mD2DSurfaceOnWhite.get() };
       destinationSurface = new gfxTeeSurface(surfaces, ArrayLength(surfaces));
       // Using this surface as a source will likely go horribly wrong, since
       // only the onBlack surface will really be used, so alpha information will
       // be incorrect.
       destinationSurface->SetAllowUseAsSource(false);
@@ -413,28 +413,28 @@ ThebesLayerD3D10::DrawRegion(nsIntRegion
   } else {
     destinationSurface = mD2DSurface;
   }
 
   MOZ_ASSERT(mDrawTarget);
   nsRefPtr<gfxContext> context = new gfxContext(mDrawTarget);
 
   context->Translate(gfxPoint(-visibleRect.x, -visibleRect.y));
-  if (aMode == SURFACE_SINGLE_CHANNEL_ALPHA) {
+  if (aMode == SurfaceMode::SURFACE_SINGLE_CHANNEL_ALPHA) {
     nsIntRegionRectIterator iter(aRegion);
     const nsIntRect *iterRect;
     while ((iterRect = iter.Next())) {
       mDrawTarget->ClearRect(Rect(iterRect->x, iterRect->y, iterRect->width, iterRect->height));
     }
   }
 
   mDrawTarget->SetPermitSubpixelAA(!(mContentFlags & CONTENT_COMPONENT_ALPHA));
 
   LayerManagerD3D10::CallbackInfo cbInfo = mD3DManager->GetCallbackInfo();
-  cbInfo.Callback(this, context, aRegion, CLIP_DRAW, nsIntRegion(), cbInfo.CallbackData);
+  cbInfo.Callback(this, context, aRegion, DrawRegionClip::DRAW, nsIntRegion(), cbInfo.CallbackData);
 }
 
 void
 ThebesLayerD3D10::CreateNewTextures(const gfx::IntSize &aSize, SurfaceMode aMode)
 {
   if (aSize.width == 0 || aSize.height == 0) {
     // Nothing to do.
     return;
@@ -455,61 +455,61 @@ ThebesLayerD3D10::CreateNewTextures(cons
 
     hr = device()->CreateShaderResourceView(mTexture, nullptr, getter_AddRefs(mSRView));
 
     if (FAILED(hr)) {
       NS_WARNING("Failed to create shader resource view for ThebesLayerD3D10.");
     }
 
     if (!gfxPlatform::GetPlatform()->SupportsAzureContent()) {
-      mD2DSurface = new gfxD2DSurface(mTexture, aMode != SURFACE_SINGLE_CHANNEL_ALPHA ?
-                                                GFX_CONTENT_COLOR : GFX_CONTENT_COLOR_ALPHA);
+      mD2DSurface = new gfxD2DSurface(mTexture, aMode != SurfaceMode::SURFACE_SINGLE_CHANNEL_ALPHA ?
+                                                gfxContentType::COLOR : gfxContentType::COLOR_ALPHA);
 
       if (!mD2DSurface || mD2DSurface->CairoStatus()) {
         NS_WARNING("Failed to create surface for ThebesLayerD3D10.");
         mD2DSurface = nullptr;
         return;
       }
     } else {
       mDrawTarget = nullptr;
     }
   }
 
-  if (aMode == SURFACE_COMPONENT_ALPHA && !mTextureOnWhite) {
+  if (aMode == SurfaceMode::SURFACE_COMPONENT_ALPHA && !mTextureOnWhite) {
     hr = device()->CreateTexture2D(&desc, nullptr, getter_AddRefs(mTextureOnWhite));
 
     if (FAILED(hr)) {
       NS_WARNING("Failed to create new texture for ThebesLayerD3D10!");
       return;
     }
 
     hr = device()->CreateShaderResourceView(mTextureOnWhite, nullptr, getter_AddRefs(mSRViewOnWhite));
 
     if (FAILED(hr)) {
       NS_WARNING("Failed to create shader resource view for ThebesLayerD3D10.");
     }
 
     if (!gfxPlatform::GetPlatform()->SupportsAzureContent()) {
-      mD2DSurfaceOnWhite = new gfxD2DSurface(mTextureOnWhite, GFX_CONTENT_COLOR);
+      mD2DSurfaceOnWhite = new gfxD2DSurface(mTextureOnWhite, gfxContentType::COLOR);
 
       if (!mD2DSurfaceOnWhite || mD2DSurfaceOnWhite->CairoStatus()) {
         NS_WARNING("Failed to create surface for ThebesLayerD3D10.");
         mD2DSurfaceOnWhite = nullptr;
         return;
       }
     } else {
       mDrawTarget = nullptr;
     }
   }
 
   if (gfxPlatform::GetPlatform()->SupportsAzureContent() && !mDrawTarget) {
-    if (aMode == SURFACE_COMPONENT_ALPHA) {
+    if (aMode == SurfaceMode::SURFACE_COMPONENT_ALPHA) {
       mDrawTarget = Factory::CreateDualDrawTargetForD3D10Textures(mTexture, mTextureOnWhite, SurfaceFormat::B8G8R8X8);
     } else {
-      mDrawTarget = Factory::CreateDrawTargetForD3D10Texture(mTexture, aMode != SURFACE_SINGLE_CHANNEL_ALPHA ?
+      mDrawTarget = Factory::CreateDrawTargetForD3D10Texture(mTexture, aMode != SurfaceMode::SURFACE_SINGLE_CHANNEL_ALPHA ?
         SurfaceFormat::B8G8R8X8 : SurfaceFormat::B8G8R8A8);
     }
 
     if (!mDrawTarget) {
       NS_WARNING("Failed to create DrawTarget for ThebesLayerD3D10.");
       mDrawTarget = nullptr;
       return;
     }
--- a/gfx/layers/d3d11/CompositorD3D11.cpp
+++ b/gfx/layers/d3d11/CompositorD3D11.cpp
@@ -60,17 +60,17 @@ struct DeviceAttachmentsD3D11
 };
 
 CompositorD3D11::CompositorD3D11(nsIWidget* aWidget)
   : mAttachments(nullptr)
   , mWidget(aWidget)
   , mHwnd(nullptr)
   , mDisableSequenceForNextFrame(false)
 {
-  sBackend = LAYERS_D3D11;
+  sBackend = LayersBackend::LAYERS_D3D11;
 }
 
 CompositorD3D11::~CompositorD3D11()
 {
   if (mDevice) {
     int referenceCount = 0;
     UINT size = sizeof(referenceCount);
     HRESULT hr = mDevice->GetPrivateData(sLayerManagerCount, &size, &referenceCount);
@@ -347,17 +347,17 @@ CompositorD3D11::CreateDataTextureSource
 }
 
 TextureFactoryIdentifier
 CompositorD3D11::GetTextureFactoryIdentifier()
 {
   TextureFactoryIdentifier ident;
   ident.mMaxTextureSize = GetMaxTextureSize();
   ident.mParentProcessId = XRE_GetProcessType();
-  ident.mParentBackend = LAYERS_D3D11;
+  ident.mParentBackend = LayersBackend::LAYERS_D3D11;
   return ident;
 }
 
 bool
 CompositorD3D11::CanUseCanvasLayerForSize(const gfx::IntSize& aSize)
 {
   int32_t maxTextureSize = GetMaxTextureSize();
 
--- a/gfx/layers/d3d11/TextureD3D11.cpp
+++ b/gfx/layers/d3d11/TextureD3D11.cpp
@@ -589,23 +589,23 @@ DeprecatedTextureClientD3D11::EnsureDraw
   if (mDrawTarget) {
     return;
   }
 
   LockTexture();
 
   SurfaceFormat format;
   switch (mContentType) {
-  case GFX_CONTENT_ALPHA:
+  case gfxContentType::ALPHA:
     format = SurfaceFormat::A8;
     break;
-  case GFX_CONTENT_COLOR:
+  case gfxContentType::COLOR:
     format = SurfaceFormat::B8G8R8X8;
     break;
-  case GFX_CONTENT_COLOR_ALPHA:
+  case gfxContentType::COLOR_ALPHA:
     format = SurfaceFormat::B8G8R8A8;
     break;
   default:
     format = SurfaceFormat::B8G8R8A8;
   }
 
   mDrawTarget = Factory::CreateDrawTargetForD3D10Texture(mTexture, format);
   ReleaseTexture();
@@ -693,27 +693,27 @@ DeprecatedTextureHostShmemD3D11::UpdateI
   nsRefPtr<gfxImageSurface> surf = openSurf.GetAsImage();
 
   gfx::IntSize size = gfx::ToIntSize(surf->GetSize());
 
   uint32_t bpp = 0;
 
   DXGI_FORMAT dxgiFormat;
   switch (surf->Format()) {
-  case gfxImageFormatRGB24:
+  case gfxImageFormat::RGB24:
     mFormat = SurfaceFormat::B8G8R8X8;
     dxgiFormat = DXGI_FORMAT_B8G8R8X8_UNORM;
     bpp = 4;
     break;
-  case gfxImageFormatARGB32:
+  case gfxImageFormat::ARGB32:
     mFormat = SurfaceFormat::B8G8R8A8;
     dxgiFormat = DXGI_FORMAT_B8G8R8A8_UNORM;
     bpp = 4;
     break;
-  case gfxImageFormatA8:
+  case gfxImageFormat::A8:
     mFormat = SurfaceFormat::A8;
     dxgiFormat = DXGI_FORMAT_A8_UNORM;
     bpp = 1;
     break;
   default:
     NS_ERROR("Bad image format");
   }
 
--- a/gfx/layers/d3d9/CanvasLayerD3D9.cpp
+++ b/gfx/layers/d3d9/CanvasLayerD3D9.cpp
@@ -127,38 +127,38 @@ CanvasLayerD3D9::UpdateSurface()
       NS_WARNING("Failed to lock CanvasLayer texture.");
       return;
     }
 
     D3DLOCKED_RECT lockedRect = textureLock.GetLockRect();
 
     nsRefPtr<gfxImageSurface> sourceSurface;
 
-    if (mSurface->GetType() == gfxSurfaceTypeWin32) {
+    if (mSurface->GetType() == gfxSurfaceType::Win32) {
       sourceSurface = mSurface->GetAsImageSurface();
-    } else if (mSurface->GetType() == gfxSurfaceTypeImage) {
+    } else if (mSurface->GetType() == gfxSurfaceType::Image) {
       sourceSurface = static_cast<gfxImageSurface*>(mSurface.get());
-      if (sourceSurface->Format() != gfxImageFormatARGB32 &&
-          sourceSurface->Format() != gfxImageFormatRGB24)
+      if (sourceSurface->Format() != gfxImageFormat::ARGB32 &&
+          sourceSurface->Format() != gfxImageFormat::RGB24)
       {
         return;
       }
     } else {
       sourceSurface = new gfxImageSurface(gfxIntSize(mBounds.width, mBounds.height),
-                                          gfxImageFormatARGB32);
+                                          gfxImageFormat::ARGB32);
       nsRefPtr<gfxContext> ctx = new gfxContext(sourceSurface);
       ctx->SetOperator(gfxContext::OPERATOR_SOURCE);
       ctx->SetSource(mSurface);
       ctx->Paint();
     }
 
     uint8_t *startBits = sourceSurface->Data();
     uint32_t sourceStride = sourceSurface->Stride();
 
-    if (sourceSurface->Format() != gfxImageFormatARGB32) {
+    if (sourceSurface->Format() != gfxImageFormat::ARGB32) {
       mHasAlpha = false;
     } else {
       mHasAlpha = true;
     }
 
     for (int y = 0; y < mBounds.height; y++) {
       memcpy((uint8_t*)lockedRect.pBits + lockedRect.Pitch * y,
              startBits + sourceStride * y,
--- a/gfx/layers/d3d9/CompositorD3D9.cpp
+++ b/gfx/layers/d3d9/CompositorD3D9.cpp
@@ -21,17 +21,17 @@ using namespace mozilla::gfx;
 namespace mozilla {
 namespace layers {
 
 CompositorD3D9::CompositorD3D9(PCompositorParent* aParent, nsIWidget *aWidget)
   : Compositor(aParent)
   , mWidget(aWidget)
   , mDeviceResetCount(0)
 {
-  sBackend = LAYERS_D3D9;
+  sBackend = LayersBackend::LAYERS_D3D9;
 }
 
 CompositorD3D9::~CompositorD3D9()
 {
   mSwapChain = nullptr;
   mDeviceManager = nullptr;
 }
 
@@ -58,17 +58,17 @@ CompositorD3D9::Initialize()
   return true;
 }
 
 TextureFactoryIdentifier
 CompositorD3D9::GetTextureFactoryIdentifier()
 {
   TextureFactoryIdentifier ident;
   ident.mMaxTextureSize = GetMaxTextureSize();
-  ident.mParentBackend = LAYERS_D3D9;
+  ident.mParentBackend = LayersBackend::LAYERS_D3D9;
   ident.mParentProcessId = XRE_GetProcessType();
   return ident;
 }
 
 bool
 CompositorD3D9::CanUseCanvasLayerForSize(const IntSize &aSize)
 {
   int32_t maxTextureSize = GetMaxTextureSize();
--- a/gfx/layers/d3d9/ImageLayerD3D9.cpp
+++ b/gfx/layers/d3d9/ImageLayerD3D9.cpp
@@ -22,17 +22,17 @@
 namespace mozilla {
 namespace layers {
 
 using namespace mozilla::gfx;
 
 static inline _D3DFORMAT
 D3dFormatForGfxFormat(gfxImageFormat aFormat)
 {
-  if (aFormat == gfxImageFormatA8) {
+  if (aFormat == gfxImageFormat::A8) {
     return D3DFMT_A8;
   }
 
   return D3DFMT_A8R8G8B8;
 }
 
 static already_AddRefed<IDirect3DTexture9>
 DataToTexture(IDirect3DDevice9 *aDevice,
@@ -136,17 +136,17 @@ SurfaceToTexture(IDirect3DDevice9 *aDevi
                  gfxASurface *aSurface,
                  const IntSize &aSize)
 {
 
   nsRefPtr<gfxImageSurface> imageSurface = aSurface->GetAsImageSurface();
 
   if (!imageSurface) {
     imageSurface = new gfxImageSurface(ThebesIntSize(aSize),
-                                       gfxImageFormatARGB32);
+                                       gfxImageFormat::ARGB32);
 
     nsRefPtr<gfxContext> context = new gfxContext(imageSurface);
     context->SetSource(aSurface);
     context->SetOperator(gfxContext::OPERATOR_SOURCE);
     context->Paint();
   }
 
   return DataToTexture(aDevice, imageSurface->Data(), imageSurface->Stride(),
@@ -301,17 +301,17 @@ static void AllocateTexturesYCbCr(Planar
     backendData->mCrTexture->GetSurfaceLevel(0, getter_AddRefs(dstSurface));
     aDevice->UpdateSurface(tmpSurfaceCr, nullptr, dstSurface, nullptr);
   } else {
     backendData->mYTexture->UnlockRect(0);
     backendData->mCbTexture->UnlockRect(0);
     backendData->mCrTexture->UnlockRect(0);
   }
 
-  aImage->SetBackendData(mozilla::layers::LAYERS_D3D9, backendData.forget());
+  aImage->SetBackendData(mozilla::layers::LayersBackend::LAYERS_D3D9, backendData.forget());
 }
 
 Layer*
 ImageLayerD3D9::GetLayer()
 {
   return this;
 }
 
@@ -326,62 +326,62 @@ IDirect3DTexture9*
 ImageLayerD3D9::GetTexture(Image *aImage, bool& aHasAlpha)
 {
   NS_ASSERTION(aImage, "Null image.");
 
   if (aImage->GetFormat() == REMOTE_IMAGE_BITMAP) {
     RemoteBitmapImage *remoteImage =
       static_cast<RemoteBitmapImage*>(aImage);
 
-    if (!aImage->GetBackendData(mozilla::layers::LAYERS_D3D9)) {
+    if (!aImage->GetBackendData(mozilla::layers::LayersBackend::LAYERS_D3D9)) {
       nsAutoPtr<TextureD3D9BackendData> dat(new TextureD3D9BackendData());
       dat->mTexture = DataToTexture(device(), remoteImage->mData, remoteImage->mStride, remoteImage->mSize, D3DFMT_A8R8G8B8);
       if (dat->mTexture) {
-        aImage->SetBackendData(mozilla::layers::LAYERS_D3D9, dat.forget());
+        aImage->SetBackendData(mozilla::layers::LayersBackend::LAYERS_D3D9, dat.forget());
       }
     }
 
     aHasAlpha = remoteImage->mFormat == RemoteImageData::BGRA32;
   } else if (aImage->GetFormat() == CAIRO_SURFACE) {
     CairoImage *cairoImage =
       static_cast<CairoImage*>(aImage);
 
     nsRefPtr<gfxASurface> surf = cairoImage->DeprecatedGetAsSurface();
     if (!surf) {
       return nullptr;
     }
 
-    if (!aImage->GetBackendData(mozilla::layers::LAYERS_D3D9)) {
+    if (!aImage->GetBackendData(mozilla::layers::LayersBackend::LAYERS_D3D9)) {
       nsAutoPtr<TextureD3D9BackendData> dat(new TextureD3D9BackendData());
       dat->mTexture = SurfaceToTexture(device(), surf, cairoImage->GetSize());
       if (dat->mTexture) {
-        aImage->SetBackendData(mozilla::layers::LAYERS_D3D9, dat.forget());
+        aImage->SetBackendData(mozilla::layers::LayersBackend::LAYERS_D3D9, dat.forget());
       }
     }
 
-    aHasAlpha = surf->GetContentType() == GFX_CONTENT_COLOR_ALPHA;
+    aHasAlpha = surf->GetContentType() == gfxContentType::COLOR_ALPHA;
   } else if (aImage->GetFormat() == D3D9_RGB32_TEXTURE) {
-    if (!aImage->GetBackendData(mozilla::layers::LAYERS_D3D9)) {
+    if (!aImage->GetBackendData(mozilla::layers::LayersBackend::LAYERS_D3D9)) {
       // The texture in which the frame is stored belongs to DXVA's D3D9 device.
       // We need to open it on our device before we can use it.
       nsAutoPtr<TextureD3D9BackendData> backendData(new TextureD3D9BackendData());
       D3D9SurfaceImage* image = static_cast<D3D9SurfaceImage*>(aImage);
       backendData->mTexture = OpenSharedTexture(image->GetDesc(), image->GetShareHandle(), device());
       if (backendData->mTexture) {
-        aImage->SetBackendData(mozilla::layers::LAYERS_D3D9, backendData.forget());
+        aImage->SetBackendData(mozilla::layers::LayersBackend::LAYERS_D3D9, backendData.forget());
       }
     }
     aHasAlpha = false;
   } else {
     NS_WARNING("Inappropriate image type.");
     return nullptr;
   }
 
   TextureD3D9BackendData *data =
-    static_cast<TextureD3D9BackendData*>(aImage->GetBackendData(mozilla::layers::LAYERS_D3D9));
+    static_cast<TextureD3D9BackendData*>(aImage->GetBackendData(mozilla::layers::LayersBackend::LAYERS_D3D9));
 
   if (!data) {
     return nullptr;
   }
 
   nsRefPtr<IDirect3DDevice9> dev;
   data->mTexture->GetDevice(getter_AddRefs(dev));
   if (dev != device()) {
@@ -411,17 +411,17 @@ ImageLayerD3D9::RenderLayer()
   gfx::IntSize size = image->GetSize();
 
   if (image->GetFormat() == CAIRO_SURFACE ||
       image->GetFormat() == REMOTE_IMAGE_BITMAP ||
       image->GetFormat() == D3D9_RGB32_TEXTURE)
   {
     nsRefPtr<gfxASurface> surf = image->DeprecatedGetAsSurface();
     NS_ASSERTION(image->GetFormat() != CAIRO_SURFACE ||
-                 !surf || surf->GetContentType() != GFX_CONTENT_ALPHA,
+                 !surf || surf->GetContentType() != gfxContentType::ALPHA,
                  "Image layer has alpha image");
 
     bool hasAlpha = false;
     nsRefPtr<IDirect3DTexture9> texture = GetTexture(image, hasAlpha);
 
     device()->SetVertexShaderConstantF(CBvLayerQuad,
                                        ShaderConstantRect(0,
                                                           0,
@@ -452,22 +452,22 @@ ImageLayerD3D9::RenderLayer()
   } else {
     PlanarYCbCrImage *yuvImage =
       static_cast<PlanarYCbCrImage*>(image);
 
     if (!yuvImage->IsValid()) {
       return;
     }
 
-    if (!yuvImage->GetBackendData(mozilla::layers::LAYERS_D3D9)) {
+    if (!yuvImage->GetBackendData(mozilla::layers::LayersBackend::LAYERS_D3D9)) {
       AllocateTexturesYCbCr(yuvImage, device(), mD3DManager);
     }
 
     PlanarYCbCrD3D9BackendData *data =
-      static_cast<PlanarYCbCrD3D9BackendData*>(yuvImage->GetBackendData(mozilla::layers::LAYERS_D3D9));
+      static_cast<PlanarYCbCrD3D9BackendData*>(yuvImage->GetBackendData(mozilla::layers::LayersBackend::LAYERS_D3D9));
 
     if (!data) {
       return;
     }
 
     nsRefPtr<IDirect3DDevice9> dev;
     data->mYTexture->GetDevice(getter_AddRefs(dev));
     if (dev != device()) {
--- a/gfx/layers/d3d9/LayerManagerD3D9.cpp
+++ b/gfx/layers/d3d9/LayerManagerD3D9.cpp
@@ -342,17 +342,17 @@ LayerManagerD3D9::PaintToTarget()
 
   D3DLOCKED_RECT rect;
   destSurf->LockRect(&rect, nullptr, D3DLOCK_READONLY);
 
   nsRefPtr<gfxImageSurface> imageSurface =
     new gfxImageSurface((unsigned char*)rect.pBits,
                         gfxIntSize(desc.Width, desc.Height),
                         rect.Pitch,
-                        gfxImageFormatARGB32);
+                        gfxImageFormat::ARGB32);
 
   mTarget->SetSource(imageSurface);
   mTarget->SetOperator(gfxContext::OPERATOR_OVER);
   mTarget->Paint();
   destSurf->UnlockRect();
 }
 
 LayerD3D9::LayerD3D9(LayerManagerD3D9 *aManager)
--- a/gfx/layers/d3d9/LayerManagerD3D9.h
+++ b/gfx/layers/d3d9/LayerManagerD3D9.h
@@ -98,17 +98,17 @@ public:
   virtual already_AddRefed<ImageLayer> CreateImageLayer();
 
   virtual already_AddRefed<ColorLayer> CreateColorLayer();
 
   virtual already_AddRefed<CanvasLayer> CreateCanvasLayer();
 
   virtual already_AddRefed<ReadbackLayer> CreateReadbackLayer();
 
-  virtual LayersBackend GetBackendType() { return LAYERS_D3D9; }
+  virtual LayersBackend GetBackendType() { return LayersBackend::LAYERS_D3D9; }
   virtual void GetBackendName(nsAString& name) { name.AssignLiteral("Direct3D 9"); }
   bool DeviceWasRemoved() { return deviceManager()->DeviceWasRemoved(); }
 
   /*
    * Helper methods.
    */
   void SetClippingEnabled(bool aEnabled);
 
--- a/gfx/layers/d3d9/TextureD3D9.cpp
+++ b/gfx/layers/d3d9/TextureD3D9.cpp
@@ -327,27 +327,27 @@ DeprecatedTextureHostShmemD3D9::UpdateIm
   nsRefPtr<gfxImageSurface> surf = openSurf.GetAsImage();
 
   mSize = ToIntSize(surf->GetSize());
 
   uint32_t bpp = 0;
 
   _D3DFORMAT format = D3DFMT_A8R8G8B8;
   switch (surf->Format()) {
-  case gfxImageFormatRGB24:
+  case gfxImageFormat::RGB24:
     mFormat = SurfaceFormat::B8G8R8X8;
     format = D3DFMT_X8R8G8B8;
     bpp = 4;
     break;
-  case gfxImageFormatARGB32:
+  case gfxImageFormat::ARGB32:
     mFormat = SurfaceFormat::B8G8R8A8;
     format = D3DFMT_A8R8G8B8;
     bpp = 4;
     break;
-  case gfxImageFormatA8:
+  case gfxImageFormat::A8:
     mFormat = SurfaceFormat::A8;
     format = D3DFMT_A8;
     bpp = 1;
     break;
   default:
     NS_ERROR("Bad image format");
   }
 
@@ -661,27 +661,27 @@ DeprecatedTextureHostDIB::UpdateImpl(con
     dont_AddRef(reinterpret_cast<gfxWindowsSurface*>(aImage.get_SurfaceDescriptorDIB().surface()));
 
   mSize = ToIntSize(surf->GetSize());
 
   uint32_t bpp = 0;
 
   _D3DFORMAT format = D3DFMT_A8R8G8B8;
   switch (gfxPlatform::GetPlatform()->OptimalFormatForContent(surf->GetContentType())) {
-  case gfxImageFormatRGB24:
+  case gfxImageFormat::RGB24:
     mFormat = SurfaceFormat::B8G8R8X8;
     format = D3DFMT_X8R8G8B8;
     bpp = 4;
     break;
-  case gfxImageFormatARGB32:
+  case gfxImageFormat::ARGB32:
     mFormat = SurfaceFormat::B8G8R8A8;
     format = D3DFMT_A8R8G8B8;
     bpp = 4;
     break;
-  case gfxImageFormatA8:
+  case gfxImageFormat::A8:
     mFormat = SurfaceFormat::A8;
     format = D3DFMT_A8;
     bpp = 1;
     break;
   default:
     NS_ERROR("Bad image format");
   }
 
@@ -756,23 +756,23 @@ DeprecatedTextureClientD3D9::EnsureAlloc
     mD3D9Surface = nullptr;
     mTexture = nullptr;
   }
 
   mSize = aSize;
 
   _D3DFORMAT format = D3DFMT_A8R8G8B8;
   switch (aType) {
-  case GFX_CONTENT_COLOR:
+  case gfxContentType::COLOR:
     format = D3DFMT_X8R8G8B8;
     break;
-  case GFX_CONTENT_COLOR_ALPHA:
+  case gfxContentType::COLOR_ALPHA:
     // fallback to DIB texture client
     return false;
-  case GFX_CONTENT_ALPHA:
+  case gfxContentType::ALPHA:
     format = D3DFMT_A8;
     break;
   default:
     NS_ERROR("Bad image type");
   }
 
   DeviceManagerD3D9* deviceManager = gfxWindowsPlatform::GetPlatform()->GetD3D9DeviceManager();
   if (!deviceManager ||
--- a/gfx/layers/d3d9/ThebesLayerD3D9.cpp
+++ b/gfx/layers/d3d9/ThebesLayerD3D9.cpp
@@ -126,17 +126,17 @@ ThebesLayerD3D9::UpdateTextures(SurfaceM
       // should silently ignore the failure. In the future when device failures
       // are properly handled we should test for the type of failure and gracefully
       // handle different failures. See bug 569081.
       if (!HaveTextures(aMode)) {
         mValidRegion.SetEmpty();
       } else {
         CopyRegion(oldTexture, mTextureRect.TopLeft(), mTexture, visibleRect.TopLeft(),
                    retainRegion, &mValidRegion);
-        if (aMode == SURFACE_COMPONENT_ALPHA) {
+        if (aMode == SurfaceMode::SURFACE_COMPONENT_ALPHA) {
           CopyRegion(oldTextureOnWhite, mTextureRect.TopLeft(), mTextureOnWhite, visibleRect.TopLeft(),
                      retainRegion, &mValidRegion);
         }
       }
 
       mTextureRect = visibleRect;
     }
   } else {
@@ -177,35 +177,35 @@ ThebesLayerD3D9::RenderThebesLayer(Readb
 {
   if (mVisibleRegion.IsEmpty()) {
     return;
   }
 
   nsIntRect newTextureRect = mVisibleRegion.GetBounds();
 
   SurfaceMode mode = GetSurfaceMode();
-  if (mode == SURFACE_COMPONENT_ALPHA &&
+  if (mode == SurfaceMode::SURFACE_COMPONENT_ALPHA &&
       (!mParent || !mParent->SupportsComponentAlphaChildren())) {
-    mode = SURFACE_SINGLE_CHANNEL_ALPHA;
+    mode = SurfaceMode::SURFACE_SINGLE_CHANNEL_ALPHA;
   }
   // If we have a transform that requires resampling of our texture, then
   // we need to make sure we don't sample pixels that haven't been drawn.
   // We clamp sample coordinates to the texture rect, but when the visible region
   // doesn't fill the entire texture rect we need to make sure we draw all the
   // pixels in the texture rect anyway in case they get sampled.
   nsIntRegion neededRegion = mVisibleRegion;
   if (!neededRegion.GetBounds().IsEqualInterior(newTextureRect) ||
       neededRegion.GetNumRects() > 1) {
     if (MayResample()) {
       neededRegion = newTextureRect;
-      if (mode == SURFACE_OPAQUE) {
+      if (mode == SurfaceMode::SURFACE_OPAQUE) {
         // We're going to paint outside the visible region, but layout hasn't
         // promised that it will paint opaquely there, so we'll have to
         // treat this layer as transparent.
-        mode = SURFACE_SINGLE_CHANNEL_ALPHA;
+        mode = SurfaceMode::SURFACE_SINGLE_CHANNEL_ALPHA;
       }
     }
   }
 
   VerifyContentType(mode);
   UpdateTextures(mode);
   if (!HaveTextures(mode)) {
     NS_WARNING("Texture creation failed");
@@ -241,17 +241,17 @@ ThebesLayerD3D9::RenderThebesLayer(Readb
   }
 
   if (mD3DManager->CompositingDisabled()) {
     return;
   }
 
   SetShaderTransformAndOpacity();
 
-  if (mode == SURFACE_COMPONENT_ALPHA) {
+  if (mode == SurfaceMode::SURFACE_COMPONENT_ALPHA) {
     mD3DManager->SetShaderMode(DeviceManagerD3D9::COMPONENTLAYERPASS1,
                                GetMaskLayer());
     device()->SetTexture(0, mTexture);
     device()->SetTexture(1, mTextureOnWhite);
     device()->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_ZERO);
     device()->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_INVSRCCOLOR);
     RenderRegion(neededRegion);
 
@@ -310,27 +310,27 @@ ThebesLayerD3D9::VerifyContentType(Surfa
 {
   if (!mTexture)
     return;
 
   D3DSURFACE_DESC desc;
   mTexture->GetLevelDesc(0, &desc);
 
   switch (aMode) {
-  case SURFACE_OPAQUE:
+  case SurfaceMode::SURFACE_OPAQUE:
     if (desc.Format == D3DFMT_X8R8G8B8 && !mTextureOnWhite)
       return;
     break;
 
-  case SURFACE_SINGLE_CHANNEL_ALPHA:
+  case SurfaceMode::SURFACE_SINGLE_CHANNEL_ALPHA:
     if (desc.Format == D3DFMT_A8R8G8B8 && !mTextureOnWhite)
       return;
     break;
 
-  case SURFACE_COMPONENT_ALPHA:
+  case SurfaceMode::SURFACE_COMPONENT_ALPHA:
     if (mTextureOnWhite) {
       NS_ASSERTION(desc.Format == D3DFMT_X8R8G8B8, "Wrong format for component alpha texture");
       return;
     }
     break;
   }
 
   // The new format isn't compatible with the old texture(s), toss out the old
@@ -427,44 +427,44 @@ ThebesLayerD3D9::DrawRegion(nsIntRegion 
   nsRefPtr<gfxASurface> destinationSurface;
   nsIntRect bounds = aRegion.GetBounds();
   nsRefPtr<IDirect3DTexture9> tmpTexture;
   OpaqueRenderer opaqueRenderer(aRegion);
   OpaqueRenderer opaqueRendererOnWhite(aRegion);
 
   switch (aMode)
   {
-    case SURFACE_OPAQUE:
+    case SurfaceMode::SURFACE_OPAQUE:
       destinationSurface = opaqueRenderer.Begin(this);
       break;
 
-    case SURFACE_SINGLE_CHANNEL_ALPHA: {
+    case SurfaceMode::SURFACE_SINGLE_CHANNEL_ALPHA: {
       hr = device()->CreateTexture(bounds.width, bounds.height, 1,
                                    0, D3DFMT_A8R8G8B8,
                                    D3DPOOL_SYSTEMMEM, getter_AddRefs(tmpTexture), nullptr);
 
       if (FAILED(hr)) {
         ReportFailure(NS_LITERAL_CSTRING("Failed to create temporary texture in system memory."), hr);
         return;
       }
 
       // XXX - We may consider retaining a SYSTEMMEM texture texture the size
       // of our DEFAULT texture and then use UpdateTexture and add dirty rects
       // to update in a single call.
       nsRefPtr<gfxWindowsSurface> dest = new gfxWindowsSurface(
-          gfxIntSize(bounds.width, bounds.height), gfxImageFormatARGB32);
+          gfxIntSize(bounds.width, bounds.height), gfxImageFormat::ARGB32);
       // If the contents of this layer don't require component alpha in the
       // end of rendering, it's safe to enable Cleartype since all the Cleartype
       // glyphs must be over (or under) opaque pixels.
       dest->SetSubpixelAntialiasingEnabled(!(mContentFlags & CONTENT_COMPONENT_ALPHA));
       destinationSurface = dest.forget();
       break;
     }
 
-    case SURFACE_COMPONENT_ALPHA: {
+    case SurfaceMode::SURFACE_COMPONENT_ALPHA: {
       nsRefPtr<gfxWindowsSurface> onBlack = opaqueRenderer.Begin(this);
       nsRefPtr<gfxWindowsSurface> onWhite = opaqueRendererOnWhite.Begin(this);
       if (onBlack && onWhite) {
         FillSurface(onBlack, aRegion, bounds.TopLeft(), gfxRGBA(0.0, 0.0, 0.0, 1.0));
         FillSurface(onWhite, aRegion, bounds.TopLeft(), gfxRGBA(1.0, 1.0, 1.0, 1.0));
         gfxASurface* surfaces[2] = { onBlack.get(), onWhite.get() };
         destinationSurface = new gfxTeeSurface(surfaces, ArrayLength(surfaces));
         // Using this surface as a source will likely go horribly wrong, since
@@ -488,20 +488,20 @@ ThebesLayerD3D9::DrawRegion(nsIntRegion 
 
     context = new gfxContext(dt);
   } else {
     context = new gfxContext(destinationSurface);
   }
 
   context->Translate(gfxPoint(-bounds.x, -bounds.y));
   LayerManagerD3D9::CallbackInfo cbInfo = mD3DManager->GetCallbackInfo();
-  cbInfo.Callback(this, context, aRegion, CLIP_NONE, nsIntRegion(), cbInfo.CallbackData);
+  cbInfo.Callback(this, context, aRegion, DrawRegionClip::CLIP_NONE, nsIntRegion(), cbInfo.CallbackData);
 
   for (uint32_t i = 0; i < aReadbackUpdates.Length(); ++i) {
-    NS_ASSERTION(aMode == SURFACE_OPAQUE,
+    NS_ASSERTION(aMode == SurfaceMode::SURFACE_OPAQUE,
                  "Transparent surfaces should not be used for readback");
     const ReadbackProcessor::Update& update = aReadbackUpdates[i];
     nsIntPoint offset = update.mLayer->GetBackgroundLayerOffset();
     nsRefPtr<gfxContext> ctx =
         update.mLayer->GetSink()->BeginUpdate(update.mUpdateRect + offset,
                                               update.mSequenceCounter);
     if (ctx) {
       ctx->Translate(gfxPoint(offset.x, offset.y));
@@ -513,38 +513,38 @@ ThebesLayerD3D9::DrawRegion(nsIntRegion 
 
   // Release the cairo d3d9 surface before we try to composite it
   context = nullptr;
 
   nsAutoTArray<IDirect3DTexture9*,2> srcTextures;
   nsAutoTArray<IDirect3DTexture9*,2> destTextures;
   switch (aMode)
   {
-    case SURFACE_OPAQUE:
+    case SurfaceMode::SURFACE_OPAQUE:
       // Must release reference to dest surface before ending drawing
       destinationSurface = nullptr;
       opaqueRenderer.End();
       srcTextures.AppendElement(opaqueRenderer.GetTexture());
       destTextures.AppendElement(mTexture);
       break;
 
-    case SURFACE_SINGLE_CHANNEL_ALPHA: {
+    case SurfaceMode::SURFACE_SINGLE_CHANNEL_ALPHA: {
       LockTextureRectD3D9 textureLock(tmpTexture);
       if (!textureLock.HasLock()) {
         NS_WARNING("Failed to lock ThebesLayer tmpTexture texture.");
         return;
       }
 
       D3DLOCKED_RECT r = textureLock.GetLockRect();
 
       nsRefPtr<gfxImageSurface> imgSurface =
         new gfxImageSurface((unsigned char *)r.pBits,
                             bounds.Size(),
                             r.Pitch,
-                            gfxImageFormatARGB32);
+                            gfxImageFormat::ARGB32);
 
       if (destinationSurface) {
         nsRefPtr<gfxContext> context = new gfxContext(imgSurface);
         context->SetSource(destinationSurface);
         context->SetOperator(gfxContext::OPERATOR_SOURCE);
         context->Paint();
       }
 
@@ -552,17 +552,17 @@ ThebesLayerD3D9::DrawRegion(nsIntRegion 
       destinationSurface = nullptr;
       imgSurface = nullptr;
 
       srcTextures.AppendElement(tmpTexture);
       destTextures.AppendElement(mTexture);
       break;
     }
 
-    case SURFACE_COMPONENT_ALPHA: {
+    case SurfaceMode::SURFACE_COMPONENT_ALPHA: {
       // Must release reference to dest surface before ending drawing
       destinationSurface = nullptr;
       opaqueRenderer.End();
       opaqueRendererOnWhite.End();
       srcTextures.AppendElement(opaqueRenderer.GetTexture());
       destTextures.AppendElement(mTexture);
       srcTextures.AppendElement(opaqueRendererOnWhite.GetTexture());
       destTextures.AppendElement(mTextureOnWhite);
@@ -605,25 +605,25 @@ ThebesLayerD3D9::CreateNewTextures(const
     // Nothing to do.
     return;
   }
 
   mTexture = nullptr;
   mTextureOnWhite = nullptr;
   HRESULT hr = device()->CreateTexture(aSize.width, aSize.height, 1,
                                        D3DUSAGE_RENDERTARGET,
-                                       aMode != SURFACE_SINGLE_CHANNEL_ALPHA ? D3DFMT_X8R8G8B8 : D3DFMT_A8R8G8B8,
+                                       aMode != SurfaceMode::SURFACE_SINGLE_CHANNEL_ALPHA ? D3DFMT_X8R8G8B8 : D3DFMT_A8R8G8B8,
                                        D3DPOOL_DEFAULT, getter_AddRefs(mTexture), nullptr);
   if (FAILED(hr)) {
     ReportFailure(NS_LITERAL_CSTRING("ThebesLayerD3D9::CreateNewTextures(): Failed to create texture"),
                   hr);
     return;
   }
 
-  if (aMode == SURFACE_COMPONENT_ALPHA) {
+  if (aMode == SurfaceMode::SURFACE_COMPONENT_ALPHA) {
     hr = device()->CreateTexture(aSize.width, aSize.height, 1,
                                  D3DUSAGE_RENDERTARGET,
                                  D3DFMT_X8R8G8B8,
                                  D3DPOOL_DEFAULT, getter_AddRefs(mTextureOnWhite), nullptr);
     if (FAILED(hr)) {
       ReportFailure(NS_LITERAL_CSTRING("ThebesLayerD3D9::CreateNewTextures(): Failed to create texture (2)"),
                     hr);
       return;
--- a/gfx/layers/d3d9/ThebesLayerD3D9.h
+++ b/gfx/layers/d3d9/ThebesLayerD3D9.h
@@ -46,17 +46,17 @@ private:
   nsRefPtr<IDirect3DTexture9> mTextureOnWhite;
   /**
    * Visible region bounds used when we drew the contents of the textures
    */
   nsIntRect mTextureRect;
 
   bool HaveTextures(SurfaceMode aMode)
   {
-    return mTexture && (aMode != SURFACE_COMPONENT_ALPHA || mTextureOnWhite);
+    return mTexture && (aMode != SurfaceMode::SURFACE_COMPONENT_ALPHA || mTextureOnWhite);
   }
 
   /* Checks if our surface has the right content type */
   void VerifyContentType(SurfaceMode aMode);
 
   /* Ensures we have the necessary texture object(s) and that they correspond
    * to mVisibleRegion.GetBounds(). This creates new texture objects as
    * necessary and also copies existing valid texture data if necessary.
--- a/gfx/layers/ipc/AsyncPanZoomController.cpp
+++ b/gfx/layers/ipc/AsyncPanZoomController.cpp
@@ -1318,18 +1318,18 @@ const CSSRect AsyncPanZoomController::Ca
   EnlargeDisplayPortAlongAxis(&(displayPort.y), &(displayPort.height),
     estimatedPaintDurationMillis, velocity.y,
     gYStationarySizeMultiplier, gYSkateSizeMultiplier);
 
   CSSRect scrollableRect = aFrameMetrics.GetExpandedScrollableRect();
   displayPort = displayPort.ForceInside(scrollableRect) - scrollOffset;
 
   APZC_LOG_FM(aFrameMetrics,
-    "%p calculated displayport as (%f %f %f %f) from velocity (%f %f) acceleration (%f %f) paint time %f metrics",
-    this, displayPort.x, displayPort.y, displayPort.width, displayPort.height,
+    "Calculated displayport as (%f %f %f %f) from velocity (%f %f) acceleration (%f %f) paint time %f metrics",
+    displayPort.x, displayPort.y, displayPort.width, displayPort.height,
     aVelocity.x, aVelocity.y, aAcceleration.x, aAcceleration.y,
     (float)estimatedPaintDurationMillis);
 
   return displayPort;
 }
 
 void AsyncPanZoomController::ScheduleComposite() {
   if (mCompositorParent) {
--- a/gfx/layers/ipc/CompositorParent.cpp
+++ b/gfx/layers/ipc/CompositorParent.cpp
@@ -720,34 +720,34 @@ CompositorParent::ShadowLayersUpdated(La
 void
 CompositorParent::InitializeLayerManager(const nsTArray<LayersBackend>& aBackendHints)
 {
   NS_ASSERTION(!mLayerManager, "Already initialised mLayerManager");
   NS_ASSERTION(!mCompositor,   "Already initialised mCompositor");
 
   for (size_t i = 0; i < aBackendHints.Length(); ++i) {
     RefPtr<Compositor> compositor;
-    if (aBackendHints[i] == LAYERS_OPENGL) {
+    if (aBackendHints[i] == LayersBackend::LAYERS_OPENGL) {
       compositor = new CompositorOGL(mWidget,
                                      mEGLSurfaceSize.width,
                                      mEGLSurfaceSize.height,
                                      mUseExternalSurfaceSize);
-    } else if (aBackendHints[i] == LAYERS_BASIC) {
+    } else if (aBackendHints[i] == LayersBackend::LAYERS_BASIC) {
       compositor = new BasicCompositor(mWidget);
 #ifdef XP_WIN
-    } else if (aBackendHints[i] == LAYERS_D3D11) {
+    } else if (aBackendHints[i] == LayersBackend::LAYERS_D3D11) {
       compositor = new CompositorD3D11(mWidget);
-    } else if (aBackendHints[i] == LAYERS_D3D9) {
+    } else if (aBackendHints[i] == LayersBackend::LAYERS_D3D9) {
       compositor = new CompositorD3D9(this, mWidget);
 #endif
     }
 
     if (!compositor) {
       // We passed a backend hint for which we can't create a compositor.
-      // For example, we sometime pass LAYERS_NONE as filler in aBackendHints.
+      // For example, we sometime pass LayersBackend::LAYERS_NONE as filler in aBackendHints.
       continue;
     }
 
     compositor->SetCompositorID(mCompositorID);
     RefPtr<LayerManagerComposite> layerManager = new LayerManagerComposite(compositor);
 
     if (layerManager->Initialize()) {
       mLayerManager = layerManager;
--- a/gfx/layers/ipc/ISurfaceAllocator.cpp
+++ b/gfx/layers/ipc/ISurfaceAllocator.cpp
@@ -95,17 +95,17 @@ ISurfaceAllocator::AllocSurfaceDescripto
     uint8_t *data = new (std::nothrow) uint8_t[stride * aSize.height];
     if (!data) {
       return false;
     }
     GfxMemoryImageReporter::DidAlloc(data);
 #ifdef XP_MACOSX
     // Workaround a bug in Quartz where drawing an a8 surface to another a8
     // surface with OPERATOR_SOURCE still requires the destination to be clear.
-    if (format == gfxImageFormatA8) {
+    if (format == gfxImageFormat::A8) {
       memset(data, 0, stride * aSize.height);
     }
 #endif
     *aBuffer = MemoryImage((uintptr_t)data, aSize, stride, format);
     return true;
   }
 
   nsRefPtr<gfxSharedImageSurface> buffer;
--- a/gfx/layers/ipc/ImageBridgeParent.cpp
+++ b/gfx/layers/ipc/ImageBridgeParent.cpp
@@ -66,17 +66,17 @@ ImageBridgeParent::ActorDestroy(ActorDes
     NewRunnableMethod(this, &ImageBridgeParent::DeferredDestroy));
 }
 
 bool
 ImageBridgeParent::RecvUpdate(const EditArray& aEdits, EditReplyArray* aReply)
 {
   // If we don't actually have a compositor, then don't bother
   // creating any textures.
-  if (Compositor::GetBackend() == LAYERS_NONE) {
+  if (Compositor::GetBackend() == LayersBackend::LAYERS_NONE) {
     return true;
   }
 
   EditReplyVector replyv;
   for (EditArray::index_type i = 0; i < aEdits.Length(); ++i) {
     ReceiveCompositableUpdate(aEdits[i], replyv);
   }
 
--- a/gfx/layers/ipc/LayersSurfaces.ipdlh
+++ b/gfx/layers/ipc/LayersSurfaces.ipdlh
@@ -13,16 +13,17 @@ using struct mozilla::layers::MagicGrall
 using struct mozilla::layers::SurfaceDescriptorX11 from "gfxipc/ShadowLayerUtils.h";
 using struct mozilla::null_t from "ipc/IPCMessageUtils.h";
 using mozilla::WindowsHandle from "ipc/IPCMessageUtils.h";
 using mozilla::gl::SharedTextureHandle from "GLContextTypes.h";
 using mozilla::gl::SharedTextureShareType from "GLContextTypes.h";
 using mozilla::gfx::SurfaceStreamHandle from "SurfaceTypes.h";
 using mozilla::gfx::SurfaceFormat from "mozilla/gfx/Types.h";
 using mozilla::gfx::IntSize from "mozilla/gfx/Point.h";
+using gfxImageFormat from "gfxTypes.h";
 
 namespace mozilla {
 namespace layers {
 
 union MaybeMagicGrallocBufferHandle {
   MagicGrallocBufferHandle;
   null_t;
 };
@@ -132,25 +133,25 @@ struct YCbCrImage {
   Shmem data;
   uint64_t owner;
 };
 
 // XXX remove RGBImage (see bug 847914)
 struct RGBImage {
   Shmem data;
   nsIntRect picture;
-  uint32_t rgbFormat;
+  gfxImageFormat rgbFormat;
   uint64_t owner;
 };
 
 struct MemoryImage {
   uintptr_t data;
   IntSize size;
   uint32_t stride;
-  uint32_t format;
+  gfxImageFormat format;
 };
 
 /**
  * Used for shmem-backed YCbCr and (flavors of) RGBA textures
  */
 struct SurfaceDescriptorShmem {
   Shmem data;
   SurfaceFormat format;
--- a/gfx/layers/ipc/PCompositor.ipdl
+++ b/gfx/layers/ipc/PCompositor.ipdl
@@ -73,17 +73,17 @@ parent:
 
   sync StartFrameTimeRecording(int32_t bufferSize)
     returns (uint32_t startIndex);
 
   sync StopFrameTimeRecording(uint32_t startIndex)
     returns (float[] intervals);
 
   // layersBackendHints is an ordered list of preffered backends where
-  // layersBackendHints[0] is the best backend. If any hints are LAYERS_NONE
+  // layersBackendHints[0] is the best backend. If any hints are LayersBackend::LAYERS_NONE
   // that hint is ignored.
   sync PLayerTransaction(LayersBackend[] layersBackendHints, uint64_t id)
     returns (TextureFactoryIdentifier textureFactoryIdentifier, bool success);
 
   // Notify the compositor that a region of the screen has been invalidated.
   async NotifyRegionInvalidated(nsIntRegion region);
 
 child:
--- a/gfx/layers/ipc/ShadowLayerUtilsGralloc.cpp
+++ b/gfx/layers/ipc/ShadowLayerUtilsGralloc.cpp
@@ -146,41 +146,41 @@ MagicGrallocBufferHandle::MagicGrallocBu
 //-----------------------------------------------------------------------------
 // Parent process
 
 static gfxImageFormat
 ImageFormatForPixelFormat(android::PixelFormat aFormat)
 {
   switch (aFormat) {
   case PIXEL_FORMAT_RGBA_8888:
-    return gfxImageFormatARGB32;
+    return gfxImageFormat::ARGB32;
   case PIXEL_FORMAT_RGBX_8888:
-    return gfxImageFormatRGB24;
+    return gfxImageFormat::RGB24;
   case PIXEL_FORMAT_RGB_565:
-    return gfxImageFormatRGB16_565;
+    return gfxImageFormat::RGB16_565;
   default:
     MOZ_CRASH("Unknown gralloc pixel format");
   }
-  return gfxImageFormatARGB32;
+  return gfxImageFormat::ARGB32;
 }
 
 static android::PixelFormat
 PixelFormatForImageFormat(gfxImageFormat aFormat)
 {
   switch (aFormat) {
-  case gfxImageFormatARGB32:
+  case gfxImageFormat::ARGB32:
     return android::PIXEL_FORMAT_RGBA_8888;
-  case gfxImageFormatRGB24:
+  case gfxImageFormat::RGB24:
     return android::PIXEL_FORMAT_RGBX_8888;
-  case gfxImageFormatRGB16_565:
+  case gfxImageFormat::RGB16_565:
     return android::PIXEL_FORMAT_RGB_565;
   default:
     MOZ_CRASH("Unknown gralloc pixel format");
   }
-  return gfxImageFormatARGB32;
+  return android::PIXEL_FORMAT_RGBA_8888;
 }
 
 static size_t
 BytesPerPixelForPixelFormat(android::PixelFormat aFormat)
 {
   switch (aFormat) {
   case PIXEL_FORMAT_RGBA_8888:
   case PIXEL_FORMAT_RGBX_8888:
--- a/gfx/layers/ipc/ShadowLayerUtilsX11.cpp
+++ b/gfx/layers/ipc/ShadowLayerUtilsX11.cpp
@@ -44,17 +44,17 @@ namespace layers {
 // Return true if we're likely compositing using X and so should use
 // Xlib surfaces in shadow layers.
 static bool
 UsingXCompositing()
 {
   if (!PR_GetEnv("MOZ_LAYERS_ENABLE_XLIB_SURFACES")) {
       return false;
   }
-  return (gfxSurfaceTypeXlib ==
+  return (gfxSurfaceType::Xlib ==
           gfxPlatform::GetPlatform()->ScreenReferenceSurface()->GetType());
 }
 
 // LookReturn a pointer to |aFormat| that lives in the Xrender library.
 // All code using render formats assumes it doesn't need to copy.
 static XRenderPictFormat*
 GetXRenderPictFormatFromId(Display* aDisplay, PictFormat aFormatId)
 {
@@ -132,17 +132,17 @@ ISurfaceAllocator::PlatformAllocSurfaceD
     // general.  Fall back on Shmem.
     return false;
   }
 
   gfxPlatform* platform = gfxPlatform::GetPlatform();
   nsRefPtr<gfxASurface> buffer =
     platform->CreateOffscreenSurface(gfx::ThebesIntSize(aSize), aContent);
   if (!buffer ||
-      buffer->GetType() != gfxSurfaceTypeXlib) {
+      buffer->GetType() != gfxSurfaceType::Xlib) {
     NS_ERROR("creating Xlib front/back surfaces failed!");
     return false;
   }
 
   gfxXlibSurface* bufferX = static_cast<gfxXlibSurface*>(buffer.get());
   // Release Pixmap ownership to the layers model
   bufferX->ReleasePixmap();
 
--- a/gfx/layers/ipc/ShadowLayers.cpp
+++ b/gfx/layers/ipc/ShadowLayers.cpp
@@ -680,23 +680,23 @@ ShadowLayerForwarder::GetDescriptorSurfa
   gfxASurface** aSurface)
 {
   gfxImageFormat format;
   if (PlatformGetDescriptorSurfaceImageFormat(aDescriptor, aMode, &format, aSurface)) {
     return format;
   }
 
   nsRefPtr<gfxASurface> surface = OpenDescriptor(aMode, aDescriptor);
-  NS_ENSURE_TRUE(surface, gfxImageFormatUnknown);
+  NS_ENSURE_TRUE(surface, gfxImageFormat::Unknown);
 
   nsRefPtr<gfxImageSurface> img = surface->GetAsImageSurface();
-  NS_ENSURE_TRUE(img, gfxImageFormatUnknown);
+  NS_ENSURE_TRUE(img, gfxImageFormat::Unknown);
 
   format = img->Format();
-  NS_ASSERTION(format != gfxImageFormatUnknown,
+  NS_ASSERTION(format != gfxImageFormat::Unknown,
                "ImageSurface RGB format should be known");
 
   *aSurface = surface.forget().get();
   return format;
 }
 
 /*static*/ void
 ShadowLayerForwarder::CloseDescriptor(const SurfaceDescriptor& aDescriptor)
@@ -809,17 +809,17 @@ AutoOpenSurface::ContentType()
 
 gfxImageFormat
 AutoOpenSurface::ImageFormat()
 {
   if (mSurface) {
     nsRefPtr<gfxImageSurface> img = mSurface->GetAsImageSurface();
     if (img) {
       gfxImageFormat format = img->Format();
-      NS_ASSERTION(format != gfxImageFormatUnknown,
+      NS_ASSERTION(format != gfxImageFormat::Unknown,
                    "ImageSurface RGB format should be known");
 
       return format;
     }
   }
 
   return ShadowLayerForwarder::GetDescriptorSurfaceImageFormat(
     mDescriptor, mMode, getter_AddRefs(mSurface));
--- a/gfx/layers/ipc/ShadowLayers.h
+++ b/gfx/layers/ipc/ShadowLayers.h
@@ -446,17 +446,17 @@ private:
                            OpenMode aMode,
                            gfxASurface** aSurface);
   static bool
   PlatformGetDescriptorSurfaceSize(const SurfaceDescriptor& aDescriptor,
                                    OpenMode aMode,
                                    gfx::IntSize* aSize,
                                    gfxASurface** aSurface);
   // And again, for the image format.
-  // This function will return gfxImageFormatUnknown only if |aDescriptor|
+  // This function will return gfxImageFormat::Unknown only if |aDescriptor|
   // describes a non-ImageSurface.
   static gfxImageFormat
   GetDescriptorSurfaceImageFormat(const SurfaceDescriptor& aDescriptor,
                                   OpenMode aMode,
                                   gfxASurface** aSurface);
   static bool
   PlatformGetDescriptorSurfaceImageFormat(const SurfaceDescriptor& aDescriptor,
                                           OpenMode aMode,
--- a/gfx/layers/ipc/SharedRGBImage.cpp
+++ b/gfx/layers/ipc/SharedRGBImage.cpp
@@ -49,19 +49,19 @@ DeprecatedSharedRGBImage::~DeprecatedSha
   delete mShmem;
 }
 
 already_AddRefed<Image>
 CreateSharedRGBImage(ImageContainer *aImageContainer,
                      nsIntSize aSize,
                      gfxImageFormat aImageFormat)
 {
-  NS_ASSERTION(aImageFormat == gfxImageFormatARGB32 ||
-               aImageFormat == gfxImageFormatRGB24 ||
-               aImageFormat == gfxImageFormatRGB16_565,
+  NS_ASSERTION(aImageFormat == gfxImageFormat::ARGB32 ||
+               aImageFormat == gfxImageFormat::RGB24 ||
+               aImageFormat == gfxImageFormat::RGB16_565,
                "RGB formats supported only");
 
   if (!aImageContainer) {
     NS_WARNING("No ImageContainer to allocate DeprecatedSharedRGBImage");
     return nullptr;
   }
 
   ImageFormat format = SHARED_RGB;
--- a/gfx/layers/opengl/CompositorOGL.cpp
+++ b/gfx/layers/opengl/CompositorOGL.cpp
@@ -248,17 +248,17 @@ CompositorOGL::CompositorOGL(nsIWidget *
   , mSurfaceSize(aSurfaceWidth, aSurfaceHeight)
   , mHasBGRA(0)
   , mUseExternalSurfaceSize(aUseExternalSurfaceSize)
   , mFrameInProgress(false)
   , mDestroyed(false)
   , mHeight(0)
 {
   MOZ_COUNT_CTOR(CompositorOGL);
-  sBackend = LAYERS_OPENGL;
+  sBackend = LayersBackend::LAYERS_OPENGL;
 }
 
 CompositorOGL::~CompositorOGL()
 {
   MOZ_COUNT_DTOR(CompositorOGL);
   Destroy();
 }
 
@@ -1502,17 +1502,17 @@ CompositorOGL::CopyToTarget(DrawTarget *
 
   DataSourceSurface::MappedSurface map;
   source->Map(DataSourceSurface::MapType::WRITE, &map);
   // XXX we should do this properly one day without using the gfxImageSurface
   nsRefPtr<gfxImageSurface> surf =
     new gfxImageSurface(map.mData,
                         gfxIntSize(width, height),
                         map.mStride,
-                        gfxImageFormatARGB32);
+                        gfxImageFormat::ARGB32);
   ReadPixelsIntoImageSurface(mGLContext, surf);
   source->Unmap();
 
   // Map from GL space to Cairo space and reverse the world transform.
   Matrix glToCairoTransform = ToMatrix(aTransform);
   glToCairoTransform.Invert();
   glToCairoTransform.Scale(1.0, -1.0);
   glToCairoTransform.Translate(0.0, -height);
--- a/gfx/layers/opengl/CompositorOGL.h
+++ b/gfx/layers/opengl/CompositorOGL.h
@@ -71,17 +71,17 @@ public:
   CreateDataTextureSource(TextureFlags aFlags = 0) MOZ_OVERRIDE;
 
   virtual bool Initialize() MOZ_OVERRIDE;
 
   virtual void Destroy() MOZ_OVERRIDE;
 
   virtual TextureFactoryIdentifier GetTextureFactoryIdentifier() MOZ_OVERRIDE
   {
-    return TextureFactoryIdentifier(LAYERS_OPENGL,
+    return TextureFactoryIdentifier(LayersBackend::LAYERS_OPENGL,
                                     XRE_GetProcessType(),
                                     GetMaxTextureSize(),
                                     mFBOTextureTarget == LOCAL_GL_TEXTURE_2D,
                                     SupportsPartialTextureUpdate());
   }
 
   virtual TemporaryRef<CompositingRenderTarget> 
   CreateRenderTarget(const gfx::IntRect &aRect, SurfaceInitMode aInit) MOZ_OVERRIDE;
--- a/gfx/layers/opengl/GLManager.cpp
+++ b/gfx/layers/opengl/GLManager.cpp
@@ -45,17 +45,17 @@ public:
 private:
   RefPtr<CompositorOGL> mImpl;
 };
 
 /* static */ GLManager*
 GLManager::CreateGLManager(LayerManagerComposite* aManager)
 {
   if (aManager &&
-      Compositor::GetBackend() == LAYERS_OPENGL) {
+      Compositor::GetBackend() == LayersBackend::LAYERS_OPENGL) {
     return new GLManagerCompositor(static_cast<CompositorOGL*>(
       aManager->GetCompositor()));
   }
   return nullptr;
 }
 
 }
 }
--- a/gfx/layers/opengl/OGLShaderProgram.h
+++ b/gfx/layers/opengl/OGLShaderProgram.h
@@ -90,17 +90,17 @@ ShaderProgramFromTargetAndFormat(GLenum 
     default:
       return ShaderProgramFromSurfaceFormat(aFormat);
   }
 }
 
 static inline ShaderProgramType
 ShaderProgramFromContentType(gfxContentType aContentType)
 {
-  if (aContentType == GFX_CONTENT_COLOR_ALPHA)
+  if (aContentType == gfxContentType::COLOR_ALPHA)
     return RGBALayerProgramType;
   return RGBXLayerProgramType;
 }
 
 /**
  * This struct represents the shaders that make up a program and the uniform
  * and attribute parmeters that those shaders take.
  * It is used by ShaderProgramOGL.
--- a/gfx/layers/opengl/TextureClientOGL.h
+++ b/gfx/layers/opengl/TextureClientOGL.h
@@ -91,17 +91,17 @@ class DeprecatedTextureClientSharedOGL :
 {
 public:
   DeprecatedTextureClientSharedOGL(CompositableForwarder* aForwarder, const TextureInfo& aTextureInfo);
   ~DeprecatedTextureClientSharedOGL() { ReleaseResources(); }
 
   virtual bool SupportsType(DeprecatedTextureClientType aType) MOZ_OVERRIDE { return aType == TEXTURE_SHARED_GL; }
   virtual bool EnsureAllocated(gfx::IntSize aSize, gfxContentType aType);
   virtual void ReleaseResources();
-  virtual gfxContentType GetContentType() MOZ_OVERRIDE { return GFX_CONTENT_COLOR_ALPHA; }
+  virtual gfxContentType GetContentType() MOZ_OVERRIDE { return gfxContentType::COLOR_ALPHA; }
 
 protected:
   gl::GLContext* mGL;
   gfx::IntSize mSize;
 
   friend class CompositingFactory;
 };
 
@@ -123,15 +123,15 @@ public:
   DeprecatedTextureClientStreamOGL(CompositableForwarder* aForwarder, const TextureInfo& aTextureInfo)
     : DeprecatedTextureClient(aForwarder, aTextureInfo)
   {}
   ~DeprecatedTextureClientStreamOGL() { ReleaseResources(); }
 
   virtual bool SupportsType(DeprecatedTextureClientType aType) MOZ_OVERRIDE { return aType == TEXTURE_STREAM_GL; }
   virtual bool EnsureAllocated(gfx::IntSize aSize, gfxContentType aType) { return true; }
   virtual void ReleaseResources() { mDescriptor = SurfaceDescriptor(); }
-  virtual gfxContentType GetContentType() MOZ_OVERRIDE { return GFX_CONTENT_COLOR_ALPHA; }
+  virtual gfxContentType GetContentType() MOZ_OVERRIDE { return gfxContentType::COLOR_ALPHA; }
 };
 
 } // namespace
 } // namespace
 
 #endif
--- a/gfx/layers/opengl/TextureHostOGL.cpp
+++ b/gfx/layers/opengl/TextureHostOGL.cpp
@@ -745,17 +745,17 @@ TextureImageDeprecatedTextureHostOGL::Up
   AutoOpenSurface surf(OPEN_READ_ONLY, aImage);
   gfx::IntSize size = surf.Size();
   TextureImage::ImageFormat format = surf.ImageFormat();
 
   if (!mTexture ||
       (mTexture->GetSize() != size && !aOffset) ||
       mTexture->GetContentType() != surf.ContentType() ||
       (mTexture->GetImageFormat() != format &&
-       mTexture->GetImageFormat() != gfxImageFormatUnknown)) {
+       mTexture->GetImageFormat() != gfxImageFormat::Unknown)) {
 
     mTexture = CreateTextureImage(mGL,
                                   size,
                                   surf.ContentType(),
                                   WrapMode(mGL, mFlags & TEXTURE_ALLOW_REPEAT),
                                   FlagsToGLFlags(mFlags),
                                   format);
   }
@@ -1074,50 +1074,50 @@ YCbCrDeprecatedTextureHostOGL::UpdateImp
   YCbCrImageDataDeserializer deserializer(aImage.get_YCbCrImage().data().get<uint8_t>());
 
   gfx::IntSize gfxSize = deserializer.GetYSize();
   gfx::IntSize gfxCbCrSize = deserializer.GetCbCrSize();
 
   if (!mYTexture->mTexImage || mYTexture->mTexImage->GetSize() != gfxSize) {
     mYTexture->mTexImage = CreateBasicTextureImage(mGL,
                                                    gfxSize,
-                                                   GFX_CONTENT_ALPHA,
+                                                   gfxContentType::ALPHA,
                                                    WrapMode(mGL, mFlags & TEXTURE_ALLOW_REPEAT),
                                                    FlagsToGLFlags(mFlags));
   }
   if (!mCbTexture->mTexImage || mCbTexture->mTexImage->GetSize() != gfxCbCrSize) {
     mCbTexture->mTexImage = CreateBasicTextureImage(mGL,
                                                     gfxCbCrSize,
-                                                    GFX_CONTENT_ALPHA,
+                                                    gfxContentType::ALPHA,
                                                     WrapMode(mGL, mFlags & TEXTURE_ALLOW_REPEAT),
                                                     FlagsToGLFlags(mFlags));
   }
   if (!mCrTexture->mTexImage || mCrTexture->mTexImage->GetSize() != gfxCbCrSize) {
     mCrTexture->mTexImage = CreateBasicTextureImage(mGL,
                                                     gfxCbCrSize,
-                                                    GFX_CONTENT_ALPHA,
+                                                    gfxContentType::ALPHA,
                                                     WrapMode(mGL, mFlags & TEXTURE_ALLOW_REPEAT),
                                                     FlagsToGLFlags(mFlags));
   }
 
   RefPtr<gfxImageSurface> tempY =
     new gfxImageSurface(deserializer.GetYData(),
                         gfx::ThebesIntSize(gfxSize),
                         deserializer.GetYStride(),
-                        gfxImageFormatA8);
+                        gfxImageFormat::A8);
   RefPtr<gfxImageSurface> tempCb =
     new gfxImageSurface(deserializer.GetCbData(),
                         gfx::ThebesIntSize(gfxCbCrSize),
                         deserializer.GetCbCrStride(),
-                        gfxImageFormatA8);
+                        gfxImageFormat::A8);
   RefPtr<gfxImageSurface> tempCr =
     new gfxImageSurface(deserializer.GetCrData(),
                         gfx::ThebesIntSize(gfxCbCrSize),
                         deserializer.GetCbCrStride(),
-                        gfxImageFormatA8);
+                        gfxImageFormat::A8);
 
   nsIntRegion yRegion(nsIntRect(0, 0, gfxSize.width, gfxSize.height));
   nsIntRegion cbCrRegion(nsIntRect(0, 0, gfxCbCrSize.width, gfxCbCrSize.height));
 
   mYTexture->mTexImage->DirectUpdate(tempY, yRegion);
   mCbTexture->mTexImage->DirectUpdate(tempCb, cbCrRegion);
   mCrTexture->mTexImage->DirectUpdate(tempCr, cbCrRegion);
 }
@@ -1141,17 +1141,17 @@ TiledDeprecatedTextureHostOGL::BindTextu
   mGL->fBindTexture(LOCAL_GL_TEXTURE_2D, mTextureHandle);
 }
 
 static void
 GetFormatAndTileForImageFormat(gfxImageFormat aFormat,
                                GLenum& aOutFormat,
                                GLenum& aOutType)
 {
-  if (aFormat == gfxImageFormatRGB16_565) {
+  if (aFormat == gfxImageFormat::RGB16_565) {
     aOutFormat = LOCAL_GL_RGB;
     aOutType = LOCAL_GL_UNSIGNED_SHORT_5_6_5;
   } else {
     aOutFormat = LOCAL_GL_RGBA;
     aOutType = LOCAL_GL_UNSIGNED_BYTE;
   }
 }
 
--- a/gfx/layers/opengl/TextureHostOGL.h
+++ b/gfx/layers/opengl/TextureHostOGL.h
@@ -735,18 +735,18 @@ public:
     MOZ_ASSERT(mGL);
     // Lock already bound us!
     MOZ_ASSERT(activetex == LOCAL_GL_TEXTURE0);
   }
   GLuint GetTextureID() { return mTextureHandle; }
   ContentType GetContentType()
   {
     return (mFormat == gfx::SurfaceFormat::B8G8R8A8) ?
-             GFX_CONTENT_COLOR_ALPHA :
-             GFX_CONTENT_COLOR;
+             gfxContentType::COLOR_ALPHA :
+             gfxContentType::COLOR;
   }
 
   virtual gfx3DMatrix GetTextureTransform() MOZ_OVERRIDE;
 
   virtual TemporaryRef<gfx::DataSourceSurface> GetAsSurface() MOZ_OVERRIDE;
 
   virtual const char* Name() { return "SharedDeprecatedTextureHostOGL"; }
 
@@ -814,18 +814,18 @@ public:
     return mTextureTarget;
   }
 
   void BindTexture(GLenum activetex) MOZ_OVERRIDE;
 
   GLuint GetTextureID() { return mTextureHandle; }
   ContentType GetContentType() {
     return (mFormat == gfx::SurfaceFormat::B8G8R8A8) ?
-             GFX_CONTENT_COLOR_ALPHA :
-             GFX_CONTENT_COLOR;
+             gfxContentType::COLOR_ALPHA :
+             gfxContentType::COLOR;
   }
 
   virtual TemporaryRef<gfx::DataSourceSurface> GetAsSurface() MOZ_OVERRIDE;
 
   virtual const char* Name() { return "SurfaceStreamHostOGL"; }
 
   SurfaceStreamHostOGL()
     : mGL(nullptr)
--- a/gfx/src/nsDeviceContext.cpp
+++ b/gfx/src/nsDeviceContext.cpp
@@ -302,33 +302,33 @@ void
 nsDeviceContext::SetDPI()
 {
     float dpi = -1.0f;
 
     // PostScript, PDF and Mac (when printing) all use 72 dpi
     // Use a printing DC to determine the other dpi values
     if (mPrintingSurface) {
         switch (mPrintingSurface->GetType()) {
-        case gfxSurfaceTypePDF:
-        case gfxSurfaceTypePS:
-        case gfxSurfaceTypeQuartz:
+        case gfxSurfaceType::PDF:
+        case gfxSurfaceType::PS:
+        case gfxSurfaceType::Quartz:
             dpi = 72.0f;
             break;
 #ifdef XP_WIN
-        case gfxSurfaceTypeWin32:
-        case gfxSurfaceTypeWin32Printing: {
+        case gfxSurfaceType::Win32:
+        case gfxSurfaceType::Win32Printing: {
             HDC dc = reinterpret_cast<gfxWindowsSurface*>(mPrintingSurface.get())->GetDC();
             int32_t OSVal = GetDeviceCaps(dc, LOGPIXELSY);
             dpi = 144.0f;
             mPrintingScale = float(OSVal) / dpi;
             break;
         }
 #endif
 #ifdef XP_OS2
-        case gfxSurfaceTypeOS2: {
+        case gfxSurfaceType::OS2: {
             LONG lDPI;
             HDC dc = GpiQueryDevice(reinterpret_cast<gfxOS2Surface*>(mPrintingSurface.get())->GetPS());
             if (DevQueryCaps(dc, CAPS_VERTICAL_FONT_RES, 1, &lDPI))
                 dpi = lDPI;
             break;
         }
 #endif
         default:
@@ -650,61 +650,61 @@ nsDeviceContext::CalcPrintingSize()
 {
     if (!mPrintingSurface)
         return;
 
     bool inPoints = true;
 
     gfxSize size(0, 0);
     switch (mPrintingSurface->GetType()) {
-    case gfxSurfaceTypeImage:
+    case gfxSurfaceType::Image:
         inPoints = false;
         size = reinterpret_cast<gfxImageSurface*>(mPrintingSurface.get())->GetSize();
         break;
 
 #if defined(MOZ_PDF_PRINTING)
-    case gfxSurfaceTypePDF:
+    case gfxSurfaceType::PDF:
         inPoints = true;
         size = reinterpret_cast<gfxPDFSurface*>(mPrintingSurface.get())->GetSize();
         break;
 #endif
 
 #ifdef MOZ_WIDGET_GTK
-    case gfxSurfaceTypePS:
+    case gfxSurfaceType::PS:
         inPoints = true;
         size = reinterpret_cast<gfxPSSurface*>(mPrintingSurface.get())->GetSize();
         break;
 #endif
 
 #ifdef XP_MACOSX
-    case gfxSurfaceTypeQuartz:
+    case gfxSurfaceType::Quartz:
         inPoints = true; // this is really only true when we're printing
         size = reinterpret_cast<gfxQuartzSurface*>(mPrintingSurface.get())->GetSize();
         break;
 #endif
 
 #ifdef XP_WIN
-    case gfxSurfaceTypeWin32:
-    case gfxSurfaceTypeWin32Printing:
+    case gfxSurfaceType::Win32:
+    case gfxSurfaceType::Win32Printing:
         {
             inPoints = false;
             HDC dc = reinterpret_cast<gfxWindowsSurface*>(mPrintingSurface.get())->GetDC();
             if (!dc)
                 dc = GetDC((HWND)mWidget->GetNativeData(NS_NATIVE_WIDGET));
             size.width = NSFloatPixelsToAppUnits(::GetDeviceCaps(dc, HORZRES)/mPrintingScale, AppUnitsPerDevPixel());
             size.height = NSFloatPixelsToAppUnits(::GetDeviceCaps(dc, VERTRES)/mPrintingScale, AppUnitsPerDevPixel());
             mDepth = (uint32_t)::GetDeviceCaps(dc, BITSPIXEL);
             if (dc != reinterpret_cast<gfxWindowsSurface*>(mPrintingSurface.get())->GetDC())
                 ReleaseDC((HWND)mWidget->GetNativeData(NS_NATIVE_WIDGET), dc);
             break;
         }
 #endif
 
 #ifdef XP_OS2
-    case gfxSurfaceTypeOS2:
+    case gfxSurfaceType::OS2:
         {
             inPoints = false;
             // we already set the size in the surface constructor we set for
             // printing, so just get those values here
             size = reinterpret_cast<gfxOS2Surface*>(mPrintingSurface.get())->GetSize();
             // as they are in pixels we need to scale them to app units
             size.width = NSFloatPixelsToAppUnits(size.width, AppUnitsPerDevPixel());
             size.height = NSFloatPixelsToAppUnits(size.height, AppUnitsPerDevPixel());
--- a/gfx/tests/gtest/TestLayers.cpp
+++ b/gfx/tests/gtest/TestLayers.cpp
@@ -14,17 +14,17 @@ class TestLayerManager: public LayerMana
 public:
   TestLayerManager()
     : LayerManager()
   {}
 
   virtual bool EndEmptyTransaction(EndTransactionFlags aFlags = END_DEFAULT) { return false; }
   virtual already_AddRefed<ContainerLayer> CreateContainerLayer() { return nullptr; }
   virtual void GetBackendName(nsAString& aName) {}
-  virtual LayersBackend GetBackendType() { return LAYERS_BASIC; }
+  virtual LayersBackend GetBackendType() { return LayersBackend::LAYERS_BASIC; }
   virtual void BeginTransaction() {}
   virtual already_AddRefed<ImageLayer> CreateImageLayer() { return nullptr; }
   virtual void SetRoot(Layer* aLayer) {}
   virtual already_AddRefed<ColorLayer> CreateColorLayer() { return nullptr; }
   virtual void BeginTransactionWithTarget(gfxContext* aTarget) {}
   virtual already_AddRefed<CanvasLayer> CreateCanvasLayer() { return nullptr; }
   virtual void EndTransaction(DrawThebesLayerCallback aCallback,
                               void* aCallbackData,
--- a/gfx/tests/gtest/TestTextures.cpp
+++ b/gfx/tests/gtest/TestTextures.cpp
@@ -204,19 +204,19 @@ void TestTextureClientYCbCr(TextureClien
 
   AssertYCbCrSurfacesEqual(&ycbcrData, &data);
   host->Unlock();
 }
 
 TEST(Layers, TextureSerialization) {
   // the test is run on all the following image formats
   gfxImageFormat formats[3] = {
-    gfxImageFormatARGB32,
-    gfxImageFormatRGB24,
-    gfxImageFormatA8,
+    gfxImageFormat::ARGB32,
+    gfxImageFormat::RGB24,
+    gfxImageFormat::A8,
   };
 
   for (int f = 0; f < 3; ++f) {
     RefPtr<gfxImageSurface> surface = new gfxImageSurface(gfxIntSize(400,300), formats[f]);
     SetupSurface(surface.get());
     AssertSurfacesEqual(surface, surface);
 
     RefPtr<TextureClient> client
@@ -226,19 +226,19 @@ TEST(Layers, TextureSerialization) {
 
     TestTextureClientSurface(client, surface);
 
     // XXX - Test more texture client types.
   }
 }
 
 TEST(Layers, TextureYCbCrSerialization) {
-  RefPtr<gfxImageSurface> ySurface = new gfxImageSurface(gfxIntSize(400,300), gfxImageFormatA8);
-  RefPtr<gfxImageSurface> cbSurface = new gfxImageSurface(gfxIntSize(200,150), gfxImageFormatA8);
-  RefPtr<gfxImageSurface> crSurface = new gfxImageSurface(gfxIntSize(200,150), gfxImageFormatA8);
+  RefPtr<gfxImageSurface> ySurface = new gfxImageSurface(gfxIntSize(400,300), gfxImageFormat::A8);
+  RefPtr<gfxImageSurface> cbSurface = new gfxImageSurface(gfxIntSize(200,150), gfxImageFormat::A8);
+  RefPtr<gfxImageSurface> crSurface = new gfxImageSurface(gfxIntSize(200,150), gfxImageFormat::A8);
   SetupSurface(ySurface.get());
   SetupSurface(cbSurface.get());
   SetupSurface(crSurface.get());
 
   PlanarYCbCrData clientData;
   clientData.mYChannel = ySurface->Data();
   clientData.mCbChannel = cbSurface->Data();
   clientData.mCrChannel = crSurface->Data();
--- a/gfx/tests/gtest/gfxFontSelectionTest.cpp
+++ b/gfx/tests/gtest/gfxFontSelectionTest.cpp
@@ -184,17 +184,17 @@ static already_AddRefed<gfxContext>
 MakeContext ()
 {
     const int size = 200;
 
     nsRefPtr<gfxASurface> surface;
 
     surface = gfxPlatform::GetPlatform()->
         CreateOffscreenSurface(gfxIntSize(size, size),
-                               gfxASurface::ContentFromFormat(gfxImageFormatRGB24));
+                               gfxASurface::ContentFromFormat(gfxImageFormat::RGB24));
     nsRefPtr<gfxContext> ctx = new gfxContext(surface);
     return ctx.forget();
 }
 
 TestEntry*
 AddTest (nsTArray<TestEntry>& testList,
          const char *utf8FamilyString,
          const gfxFontStyle& fontStyle,
--- a/gfx/tests/gtest/gfxSurfaceRefCountTest.cpp
+++ b/gfx/tests/gtest/gfxSurfaceRefCountTest.cpp
@@ -39,17 +39,17 @@ SurfaceDestroyNotifier (void *data) {
     *(int *)data = 1;
 }
 
 int
 TestNewSurface () {
     int failures = 0;
     int destroyed = 0;
 
-    nsRefPtr<gfxASurface> s = new gfxImageSurface (gfxIntSize(10, 10), gfxImageFormatARGB32);
+    nsRefPtr<gfxASurface> s = new gfxImageSurface (gfxIntSize(10, 10), gfxImageFormat::ARGB32);
     cairo_surface_t *cs = s->CairoSurface();
 
     cairo_surface_set_user_data (cs, &destruction_key, &destroyed, SurfaceDestroyNotifier);
 
     failures += CheckInt (GetASurfaceRefCount(s.get()), 1);
     failures += CheckInt (cairo_surface_get_reference_count(cs), 1);
     failures += CheckInt (destroyed, 0);
 
--- a/gfx/tests/gtest/gfxTextRunPerfTest.cpp
+++ b/gfx/tests/gtest/gfxTextRunPerfTest.cpp
@@ -36,17 +36,17 @@ static already_AddRefed<gfxContext>
 MakeContext ()
 {
     const int size = 200;
 
     nsRefPtr<gfxASurface> surface;
 
     surface = gfxPlatform::GetPlatform()->
         CreateOffscreenSurface(gfxIntSize(size, size),
-                               gfxASurface::ContentFromFormat(gfxImageFormatRGB24));
+                               gfxASurface::ContentFromFormat(gfxImageFormat::RGB24));
     nsRefPtr<gfxContext> ctx = new gfxContext(surface);
     return ctx.forget();
 }
 
 const char* lastFamilies = nullptr;
 
 static void
 RunTest (TestEntry *test, gfxContext *ctx) {
--- a/gfx/tests/gtest/gfxWordCacheTest.cpp
+++ b/gfx/tests/gtest/gfxWordCacheTest.cpp
@@ -77,17 +77,17 @@ static already_AddRefed<gfxContext>
 MakeContext ()
 {
    const int size = 200;
 
    nsRefPtr<gfxASurface> surface;
 
    surface = gfxPlatform::GetPlatform()->
        CreateOffscreenSurface(gfxIntSize(size, size),
-                              gfxASurface::ContentFromFormat(gfxImageFormatRGB24));
+                              gfxASurface::ContentFromFormat(gfxImageFormat::RGB24));
    nsRefPtr<gfxContext> ctx = new gfxContext(surface);
    return ctx.forget();
 }
 
 TEST(Gfx, WordCache) {
    gTextRuns = new FrameTextRunCache();
 
    nsRefPtr<gfxContext> ctx = MakeContext();
--- a/gfx/thebes/gfx2DGlue.h
+++ b/gfx/thebes/gfx2DGlue.h
@@ -204,58 +204,58 @@ inline JoinStyle ToJoinStyle(gfxContext:
   }
   MOZ_CRASH("Incomplete switch");
 }
 
 inline gfxImageFormat SurfaceFormatToImageFormat(SurfaceFormat aFormat)
 {
   switch (aFormat) {
   case SurfaceFormat::B8G8R8A8:
-    return gfxImageFormatARGB32;
+    return gfxImageFormat::ARGB32;
   case SurfaceFormat::B8G8R8X8:
-    return gfxImageFormatRGB24;
+    return gfxImageFormat::RGB24;
   case SurfaceFormat::R5G6B5:
-    return gfxImageFormatRGB16_565;
+    return gfxImageFormat::RGB16_565;
   case SurfaceFormat::A8:
-    return gfxImageFormatA8;
+    return gfxImageFormat::A8;
   default:
-    return gfxImageFormatUnknown;
+    return gfxImageFormat::Unknown;
   }
 }
 
 inline SurfaceFormat ImageFormatToSurfaceFormat(gfxImageFormat aFormat)
 {
   switch (aFormat) {
-  case gfxImageFormatARGB32:
+  case gfxImageFormat::ARGB32:
     return SurfaceFormat::B8G8R8A8;
-  case gfxImageFormatRGB24:
+  case gfxImageFormat::RGB24:
     return SurfaceFormat::B8G8R8X8;
-  case gfxImageFormatRGB16_565:
+  case gfxImageFormat::RGB16_565:
     return SurfaceFormat::R5G6B5;
-  case gfxImageFormatA8:
+  case gfxImageFormat::A8:
     return SurfaceFormat::A8;
   default:
-  case gfxImageFormatUnknown:
+  case gfxImageFormat::Unknown:
     return SurfaceFormat::B8G8R8A8;
   }
 }
 
 inline gfxContentType ContentForFormat(const SurfaceFormat &aFormat)
 {
   switch (aFormat) {
   case SurfaceFormat::R5G6B5:
   case SurfaceFormat::B8G8R8X8:
   case SurfaceFormat::R8G8B8X8:
-    return GFX_CONTENT_COLOR;
+    return gfxContentType::COLOR;
   case SurfaceFormat::A8:
-    return GFX_CONTENT_ALPHA;
+    return gfxContentType::ALPHA;
   case SurfaceFormat::B8G8R8A8:
   case SurfaceFormat::R8G8B8A8:
   default:
-    return GFX_CONTENT_COLOR_ALPHA;
+    return gfxContentType::COLOR_ALPHA;
   }
 }
 
 inline CompositionOp CompositionOpForOp(gfxContext::GraphicsOperator aOp)
 {
   switch (aOp) {
   case gfxContext::OPERATOR_ADD:
     return CompositionOp::OP_ADD;
--- a/gfx/thebes/gfxASurface.cpp
+++ b/gfx/thebes/gfxASurface.cpp
@@ -323,48 +323,48 @@ already_AddRefed<gfxASurface>
 gfxASurface::CreateSimilarSurface(gfxContentType aContent,
                                   const nsIntSize& aSize)
 {
     if (!mSurface || !mSurfaceValid) {
       return nullptr;
     }
     
     cairo_surface_t *surface =
-        cairo_surface_create_similar(mSurface, cairo_content_t(aContent),
+        cairo_surface_create_similar(mSurface, cairo_content_t(int(aContent)),
                                      aSize.width, aSize.height);
     if (cairo_surface_status(surface)) {
         cairo_surface_destroy(surface);
         return nullptr;
     }
 
     nsRefPtr<gfxASurface> result = Wrap(surface);
     cairo_surface_destroy(surface);
     return result.forget();
 }
 
 already_AddRefed<gfxImageSurface>
 gfxASurface::GetAsReadableARGB32ImageSurface()
 {
     nsRefPtr<gfxImageSurface> imgSurface = GetAsImageSurface();
-    if (!imgSurface || imgSurface->Format() != gfxImageFormatARGB32) {
+    if (!imgSurface || imgSurface->Format() != gfxImageFormat::ARGB32) {
       imgSurface = CopyToARGB32ImageSurface();
     }
     return imgSurface.forget();
 }
 
 already_AddRefed<gfxImageSurface>
 gfxASurface::CopyToARGB32ImageSurface()
 {
     if (!mSurface || !mSurfaceValid) {
       return nullptr;
     }
 
     const nsIntSize size = GetSize();
     nsRefPtr<gfxImageSurface> imgSurface =
-        new gfxImageSurface(size, gfxImageFormatARGB32);
+        new gfxImageSurface(size, gfxImageFormat::ARGB32);
 
     if (gfxPlatform::GetPlatform()->SupportsAzureContent()) {
         RefPtr<DrawTarget> dt = gfxPlatform::GetPlatform()->CreateDrawTargetForSurface(imgSurface, IntSize(size.width, size.height));
         RefPtr<SourceSurface> source = gfxPlatform::GetPlatform()->GetSourceSurfaceForSurface(dt, this);
 
         dt->CopySurface(source, IntRect(0, 0, size.width, size.height), IntPoint());
     } else {
         gfxContext ctx(imgSurface);
@@ -427,17 +427,17 @@ gfxASurface::CheckSurfaceSize(const nsIn
 
     return true;
 }
 
 /* static */
 int32_t
 gfxASurface::FormatStrideForWidth(gfxImageFormat format, int32_t width)
 {
-    return cairo_format_stride_for_width((cairo_format_t)format, (int)width);
+    return cairo_format_stride_for_width((cairo_format_t)(int)format, (int)width);
 }
 
 nsresult
 gfxASurface::BeginPrinting(const nsAString& aTitle, const nsAString& aPrintToFileName)
 {
     return NS_OK;
 }
 
@@ -464,28 +464,28 @@ gfxASurface::EndPage()
 {
     return NS_OK;
 }
 
 gfxContentType
 gfxASurface::ContentFromFormat(gfxImageFormat format)
 {
     switch (format) {
-        case gfxImageFormatARGB32:
-            return GFX_CONTENT_COLOR_ALPHA;
-        case gfxImageFormatRGB24:
-        case gfxImageFormatRGB16_565:
-            return GFX_CONTENT_COLOR;
-        case gfxImageFormatA8:
-        case gfxImageFormatA1:
-            return GFX_CONTENT_ALPHA;
+        case gfxImageFormat::ARGB32:
+            return gfxContentType::COLOR_ALPHA;
+        case gfxImageFormat::RGB24:
+        case gfxImageFormat::RGB16_565:
+            return gfxContentType::COLOR;
+        case gfxImageFormat::A8:
+        case gfxImageFormat::A1:
+            return gfxContentType::ALPHA;
 
-        case gfxImageFormatUnknown:
+        case gfxImageFormat::Unknown:
         default:
-            return GFX_CONTENT_COLOR;
+            return gfxContentType::COLOR;
     }
 }
 
 void
 gfxASurface::SetSubpixelAntialiasingEnabled(bool aEnabled)
 {
 #ifdef MOZ_TREE_CAIRO
     if (!mSurfaceValid)
@@ -505,29 +505,29 @@ gfxASurface::GetSubpixelAntialiasingEnab
 #else
     return true;
 #endif
 }
 
 gfxMemoryLocation
 gfxASurface::GetMemoryLocation() const
 {
-    return GFX_MEMORY_IN_PROCESS_HEAP;
+    return gfxMemoryLocation::IN_PROCESS_HEAP;
 }
 
 int32_t
 gfxASurface::BytePerPixelFromFormat(gfxImageFormat format)
 {
     switch (format) {
-        case gfxImageFormatARGB32:
-        case gfxImageFormatRGB24:
+        case gfxImageFormat::ARGB32:
+        case gfxImageFormat::RGB24:
             return 4;
-        case gfxImageFormatRGB16_565:
+        case gfxImageFormat::RGB16_565:
             return 2;
-        case gfxImageFormatA8:
+        case gfxImageFormat::A8:
             return 1;
         default:
             NS_WARNING("Unknown byte per pixel value for Image format");
     }
     return 0;
 }
 
 void
@@ -614,27 +614,27 @@ static const SurfaceMemoryReporterAttrs 
     {"gfx-surface-tee", nullptr},
     {"gfx-surface-xml", nullptr},
     {"gfx-surface-skia", nullptr},
     {"gfx-surface-subsurface", nullptr},
     {"gfx-surface-d2d", nullptr},
 };
 
 PR_STATIC_ASSERT(NS_ARRAY_LENGTH(sSurfaceMemoryReporterAttrs) ==
-                 gfxSurfaceTypeMax);
+                 size_t(gfxSurfaceType::Max));
 #ifdef CAIRO_HAS_D2D_SURFACE
 PR_STATIC_ASSERT(uint32_t(CAIRO_SURFACE_TYPE_D2D) ==
-                 uint32_t(gfxSurfaceTypeD2D));
+                 uint32_t(gfxSurfaceType::D2D));
 #endif
 PR_STATIC_ASSERT(uint32_t(CAIRO_SURFACE_TYPE_SKIA) ==
-                 uint32_t(gfxSurfaceTypeSkia));
+                 uint32_t(gfxSurfaceType::Skia));
 
 /* Surface size memory reporting */
 
-static int64_t gSurfaceMemoryUsed[gfxSurfaceTypeMax] = { 0 };
+static int64_t gSurfaceMemoryUsed[size_t(gfxSurfaceType::Max)] = { 0 };
 
 class SurfaceMemoryReporter MOZ_FINAL : public nsIMemoryReporter
 {
 public:
     NS_DECL_ISUPPORTS
 
     NS_IMETHOD CollectReports(nsIMemoryReporterCallback *aCb,
                               nsISupports *aClosure)
@@ -663,28 +663,28 @@ public:
 };
 
 NS_IMPL_ISUPPORTS1(SurfaceMemoryReporter, nsIMemoryReporter)
 
 void
 gfxASurface::RecordMemoryUsedForSurfaceType(gfxSurfaceType aType,
                                             int32_t aBytes)
 {
-    if (aType < 0 || aType >= gfxSurfaceTypeMax) {
+    if (int(aType) < 0 || aType >= gfxSurfaceType::Max) {
         NS_WARNING("Invalid type to RecordMemoryUsedForSurfaceType!");
         return;
     }
 
     static bool registered = false;
     if (!registered) {
         RegisterStrongMemoryReporter(new SurfaceMemoryReporter());
         registered = true;
     }
 
-    gSurfaceMemoryUsed[aType] += aBytes;
+    gSurfaceMemoryUsed[size_t(aType)] += aBytes;
 }
 
 void
 gfxASurface::RecordMemoryUsed(int32_t aBytes)
 {
     RecordMemoryUsedForSurfaceType(GetType(), aBytes);
     mBytesRecorded += aBytes;
 }
@@ -710,27 +710,27 @@ gfxASurface::SizeOfIncludingThis(MallocS
 {
     return aMallocSizeOf(this) + SizeOfExcludingThis(aMallocSizeOf);
 }
 
 /* static */ uint8_t
 gfxASurface::BytesPerPixel(gfxImageFormat aImageFormat)
 {
   switch (aImageFormat) {
-    case gfxImageFormatARGB32:
+    case gfxImageFormat::ARGB32:
       return 4;
-    case gfxImageFormatRGB24:
+    case gfxImageFormat::RGB24:
       return 4;
-    case gfxImageFormatRGB16_565:
+    case gfxImageFormat::RGB16_565:
       return 2;
-    case gfxImageFormatA8:
+    case gfxImageFormat::A8:
       return 1;
-    case gfxImageFormatA1:
+    case gfxImageFormat::A1:
       return 1; // Close enough
-    case gfxImageFormatUnknown:
+    case gfxImageFormat::Unknown:
     default:
       NS_NOTREACHED("Not really sure what you want me to say here");
       return 0;
   }
 }
 
 void
 gfxASurface::WriteAsPNG(const char* aFile)
@@ -770,26 +770,26 @@ gfxASurface::CopyAsDataURL()
  */
 void
 gfxASurface::WriteAsPNG_internal(FILE* aFile, bool aBinary)
 {
   nsRefPtr<gfxImageSurface> imgsurf = GetAsImageSurface();
   nsIntSize size;
 
   // FIXME/bug 831898: hack r5g6b5 for now.
-  if (!imgsurf || imgsurf->Format() == gfxImageFormatRGB16_565) {
+  if (!imgsurf || imgsurf->Format() == gfxImageFormat::RGB16_565) {
     size = GetSize();
     if (size.width == -1 && size.height == -1) {
       printf("Could not determine surface size\n");
       return;
     }
 
     imgsurf =
       new gfxImageSurface(nsIntSize(size.width, size.height),
-                          gfxImageFormatARGB32);
+                          gfxImageFormat::ARGB32);
 
     if (!imgsurf || imgsurf->CairoStatus()) {
       printf("Could not allocate image surface\n");
       return;
     }
 
     nsRefPtr<gfxContext> ctx = new gfxContext(imgsurf);
     if (!ctx || ctx->HasError()) {
--- a/gfx/thebes/gfxAlphaRecovery.cpp
+++ b/gfx/thebes/gfxAlphaRecovery.cpp
@@ -12,20 +12,20 @@
 
 /* static */ bool
 gfxAlphaRecovery::RecoverAlpha(gfxImageSurface* blackSurf,
                                const gfxImageSurface* whiteSurf)
 {
     gfxIntSize size = blackSurf->GetSize();
 
     if (size != whiteSurf->GetSize() ||
-        (blackSurf->Format() != gfxImageFormatARGB32 &&
-         blackSurf->Format() != gfxImageFormatRGB24) ||
-        (whiteSurf->Format() != gfxImageFormatARGB32 &&
-         whiteSurf->Format() != gfxImageFormatRGB24))
+        (blackSurf->Format() != gfxImageFormat::ARGB32 &&
+         blackSurf->Format() != gfxImageFormat::RGB24) ||
+        (whiteSurf->Format() != gfxImageFormat::ARGB32 &&
+         whiteSurf->Format() != gfxImageFormat::RGB24))
         return false;
 
 #ifdef MOZILLA_MAY_SUPPORT_SSE2
     if (mozilla::supports_sse2() &&
         RecoverAlphaSSE2(blackSurf, whiteSurf)) {
         return true;
     }
 #endif
--- a/gfx/thebes/gfxAlphaRecoverySSE2.cpp
+++ b/gfx/thebes/gfxAlphaRecoverySSE2.cpp
@@ -29,20 +29,20 @@ static uint32_t alphaMaski[] = { 0xff000
 
 bool
 gfxAlphaRecovery::RecoverAlphaSSE2(gfxImageSurface* blackSurf,
                                    const gfxImageSurface* whiteSurf)
 {
     gfxIntSize size = blackSurf->GetSize();
 
     if (size != whiteSurf->GetSize() ||
-        (blackSurf->Format() != gfxImageFormatARGB32 &&
-         blackSurf->Format() != gfxImageFormatRGB24) ||
-        (whiteSurf->Format() != gfxImageFormatARGB32 &&
-         whiteSurf->Format() != gfxImageFormatRGB24))
+        (blackSurf->Format() != gfxImageFormat::ARGB32 &&
+         blackSurf->Format() != gfxImageFormat::RGB24) ||
+        (whiteSurf->Format() != gfxImageFormat::ARGB32 &&
+         whiteSurf->Format() != gfxImageFormat::RGB24))
         return false;
 
     blackSurf->Flush();
     whiteSurf->Flush();
 
     unsigned char* blackData = blackSurf->Data();
     unsigned char* whiteData = whiteSurf->Data();
 
@@ -136,17 +136,17 @@ ByteAlignment(int32_t aAlignToLog2, int3
 {
     return (aX + aStride * aY) & ((1 << aAlignToLog2) - 1);
 }
 
 /*static*/ nsIntRect
 gfxAlphaRecovery::AlignRectForSubimageRecovery(const nsIntRect& aRect,
                                                gfxImageSurface* aSurface)
 {
-    NS_ASSERTION(gfxImageFormatARGB32 == aSurface->Format(),
+    NS_ASSERTION(gfxImageFormat::ARGB32 == aSurface->Format(),
                  "Thebes grew support for non-ARGB32 COLOR_ALPHA?");
     static const int32_t kByteAlignLog2 = GoodAlignmentLog2();
     static const int32_t bpp = 4;
     static const int32_t pixPerAlign = (1 << kByteAlignLog2) / bpp;
     //
     // We're going to create a subimage of the surface with size
     // <sw,sh> for alpha recovery, and want a SIMD fast-path.  The
     // rect <x,y, w,h> /needs/ to be redrawn, but it might not be
--- a/gfx/thebes/gfxAndroidPlatform.cpp
+++ b/gfx/thebes/gfxAndroidPlatform.cpp
@@ -112,21 +112,21 @@ gfxAndroidPlatform::gfxAndroidPlatform()
 
     nsCOMPtr<nsIScreenManager> screenMgr = do_GetService("@mozilla.org/gfx/screenmanager;1");
     nsCOMPtr<nsIScreen> screen;
     screenMgr->GetPrimaryScreen(getter_AddRefs(screen));
     mScreenDepth = 24;
     screen->GetColorDepth(&mScreenDepth);
 
     mOffscreenFormat = mScreenDepth == 16
-                       ? gfxImageFormatRGB16_565
-                       : gfxImageFormatRGB24;
+                       ? gfxImageFormat::RGB16_565
+                       : gfxImageFormat::RGB24;
 
     if (Preferences::GetBool("gfx.android.rgb16.force", false)) {
-        mOffscreenFormat = gfxImageFormatRGB16_565;
+        mOffscreenFormat = gfxImageFormat::RGB16_565;
     }
 
 }
 
 gfxAndroidPlatform::~gfxAndroidPlatform()
 {
     cairo_debug_reset_static_data();
 
--- a/gfx/thebes/gfxBaseSharedMemorySurface.h
+++ b/gfx/thebes/gfxBaseSharedMemorySurface.h
@@ -14,17 +14,17 @@
 #include "gfxImageSurface.h"
 #include "pratom.h"
 
 typedef struct _cairo_user_data_key cairo_user_data_key_t;
 
 struct SharedImageInfo {
     int32_t width;
     int32_t height;
-    int32_t format;
+    gfxImageFormat format;
     int32_t readCount;
 };
 
 inline SharedImageInfo*
 GetShmInfoPtr(const mozilla::ipc::Shmem& aShmem)
 {
     return reinterpret_cast<SharedImageInfo*>
         (aShmem.get<char>() + aShmem.Size<char>() - sizeof(SharedImageInfo));
@@ -99,17 +99,17 @@ public:
         return Create<ShmemAllocator, true>(aAllocator, aSize, aFormat, aShmType);
     }
 
     Shmem& GetShmem() { return mShmem; }
 
     static bool IsSharedImage(gfxASurface *aSurface)
     {
         return (aSurface
-                && aSurface->GetType() == gfxSurfaceTypeImage
+                && aSurface->GetType() == gfxSurfaceType::Image
                 && aSurface->GetData(&SHM_KEY));
     }
 
 protected:
     gfxBaseSharedMemorySurface(const gfxIntSize& aSize, long aStride, 
                                gfxImageFormat aFormat, 
                                const Shmem& aShmem)
       : Base(aShmem.get<unsigned char>(), aSize, aStride, aFormat)
--- a/gfx/thebes/gfxBlur.cpp
+++ b/gfx/thebes/gfxBlur.cpp
@@ -66,17 +66,17 @@ gfxAlphaBoxBlur::Init(const gfxRect& aRe
         gfxPlatform::GetPlatform()->CreateDrawTargetForData(mData, size,
                                                             mBlur->GetStride(),
                                                             SurfaceFormat::A8);
     if (!dt) {
         nsRefPtr<gfxImageSurface> image =
             new gfxImageSurface(mData,
                                 gfxIntSize(size.width, size.height),
                                 mBlur->GetStride(),
-                                gfxImageFormatA8);
+                                gfxImageFormat::A8);
         dt = Factory::CreateDrawTargetForCairoSurface(image->CairoSurface(), size);
         if (!dt) {
             return nullptr;
         }
     }
 
     IntRect irect = mBlur->GetRect();
     gfxPoint topleft(irect.TopLeft().x, irect.TopLeft().y);
--- a/gfx/thebes/gfxCachedTempSurface.cpp
+++ b/gfx/thebes/gfxCachedTempSurface.cpp
@@ -89,17 +89,17 @@ gfxCachedTempSurface::Get(gfxContentType
     cleared = true;
     mType = aSimilarTo->GetType();
   }
   mSurface->SetDeviceOffset(-aRect.TopLeft());
 
   nsRefPtr<gfxContext> ctx = new gfxContext(mSurface);
   ctx->Rectangle(aRect);
   ctx->Clip();
-  if (!cleared && aContentType != GFX_CONTENT_COLOR) {
+  if (!cleared && aContentType != gfxContentType::COLOR) {
     ctx->SetOperator(gfxContext::OPERATOR_CLEAR);
     ctx->Paint();
     ctx->SetOperator(gfxContext::OPERATOR_OVER);
   }
 
   CachedSurfaceExpirationTracker::MarkSurfaceUsed(this);
 
   return ctx.forget();
--- a/gfx/thebes/gfxContext.cpp
+++ b/gfx/thebes/gfxContext.cpp
@@ -1567,17 +1567,17 @@ gfxContext::Paint(gfxFloat alpha)
 }
 
 // groups
 
 void
 gfxContext::PushGroup(gfxContentType content)
 {
   if (mCairo) {
-    cairo_push_group_with_content(mCairo, (cairo_content_t) content);
+    cairo_push_group_with_content(mCairo, (cairo_content_t)(int) content);
   } else {
     PushNewDT(content);
 
     PushClipsToDT(mDT);
     mDT->SetTransform(GetDTTransform());
   }
 }
 
@@ -1603,27 +1603,27 @@ CopySurface(gfxASurface* aSrc, gfxASurfa
   cairo_paint(cr);
   cairo_destroy(cr);
 }
 
 void
 gfxContext::PushGroupAndCopyBackground(gfxContentType content)
 {
   if (mCairo) {
-    if (content == GFX_CONTENT_COLOR_ALPHA &&
+    if (content == gfxContentType::COLOR_ALPHA &&
       !(GetFlags() & FLAG_DISABLE_COPY_BACKGROUND)) {
       nsRefPtr<gfxASurface> s = CurrentSurface();
-      if ((s->GetAllowUseAsSource() || s->GetType() == gfxSurfaceTypeTee) &&
-          (s->GetContentType() == GFX_CONTENT_COLOR ||
+      if ((s->GetAllowUseAsSource() || s->GetType() == gfxSurfaceType::Tee) &&
+          (s->GetContentType() == gfxContentType::COLOR ||
               s->GetOpaqueRect().Contains(GetRoundOutDeviceClipExtents(this)))) {
         cairo_push_group_with_content(mCairo, CAIRO_CONTENT_COLOR);
         nsRefPtr<gfxASurface> d = CurrentSurface();
 
-        if (d->GetType() == gfxSurfaceTypeTee) {
-          NS_ASSERTION(s->GetType() == gfxSurfaceTypeTee, "Mismatched types");
+        if (d->GetType() == gfxSurfaceType::Tee) {
+          NS_ASSERTION(s->GetType() == gfxSurfaceType::Tee, "Mismatched types");
           nsAutoTArray<nsRefPtr<gfxASurface>,2> ss;
           nsAutoTArray<nsRefPtr<gfxASurface>,2> ds;
           static_cast<gfxTeeSurface*>(s.get())->GetSurfaces(&ss);
           static_cast<gfxTeeSurface*>(d.get())->GetSurfaces(&ds);
           NS_ASSERTION(ss.Length() == ds.Length(), "Mismatched lengths");
           gfxPoint translation = d->GetDeviceOffset() - s->GetDeviceOffset();
           for (uint32_t i = 0; i < ss.Length(); ++i) {
               CopySurface(ss[i], ds[i], translation);
@@ -1643,17 +1643,17 @@ gfxContext::PushGroupAndCopyBackground(g
     }
     if ((mDT->GetFormat() == SurfaceFormat::B8G8R8X8 ||
          mDT->GetOpaqueRect().Contains(clipExtents)) &&
         !mDT->GetUserData(&sDontUseAsSourceKey)) {
       DrawTarget *oldDT = mDT;
       RefPtr<SourceSurface> source = mDT->Snapshot();
       Point oldDeviceOffset = CurrentState().deviceOffset;
 
-      PushNewDT(GFX_CONTENT_COLOR);
+      PushNewDT(gfxContentType::COLOR);
 
       Point offset = CurrentState().deviceOffset - oldDeviceOffset;
       Rect surfRect(0, 0, Float(mDT->GetSize().width), Float(mDT->GetSize().height));
       Rect sourceRect = surfRect;
       sourceRect.x += offset.x;
       sourceRect.y += offset.y;
 
       mDT->SetTransform(Matrix());
--- a/gfx/thebes/gfxContext.h
+++ b/gfx/thebes/gfxContext.h
@@ -620,29 +620,29 @@ public:
      * This is conservative; it may return false even when the given rectangle is 
      * fully contained by the current clip.
      */
     bool ClipContainsRect(const gfxRect& aRect);
 
     /**
      * Groups
      */
-    void PushGroup(gfxContentType content = GFX_CONTENT_COLOR);
+    void PushGroup(gfxContentType content = gfxContentType::COLOR);
     /**
-     * Like PushGroup, but if the current surface is GFX_CONTENT_COLOR and
-     * content is GFX_CONTENT_COLOR_ALPHA, makes the pushed surface GFX_CONTENT_COLOR
+     * Like PushGroup, but if the current surface is gfxContentType::COLOR and
+     * content is gfxContentType::COLOR_ALPHA, makes the pushed surface gfxContentType::COLOR
      * instead and copies the contents of the current surface to the pushed
      * surface. This is good for pushing opacity groups, since blending the
      * group back to the current surface with some alpha applied will give
      * the correct results and using an opaque pushed surface gives better
      * quality and performance.
      * This API really only makes sense if you do a PopGroupToSource and
      * immediate Paint with OPERATOR_OVER.
      */
-    void PushGroupAndCopyBackground(gfxContentType content = GFX_CONTENT_COLOR);
+    void PushGroupAndCopyBackground(gfxContentType content = gfxContentType::COLOR);
     already_AddRefed<gfxPattern> PopGroup();
     void PopGroupToSource();
 
     /**
      ** Hit Testing - check if given point is in the current path
      **/
     bool PointInFill(const gfxPoint& pt);
     bool PointInStroke(const gfxPoint& pt);
--- a/gfx/thebes/gfxD2DSurface.cpp
+++ b/gfx/thebes/gfxD2DSurface.cpp
@@ -8,46 +8,46 @@
 #include "cairo-win32.h"
 #include "gfxWindowsPlatform.h"
 
 gfxD2DSurface::gfxD2DSurface(HWND aWnd, gfxContentType aContent)
 {
     Init(cairo_d2d_surface_create_for_hwnd(
         gfxWindowsPlatform::GetPlatform()->GetD2DDevice(),
         aWnd,
-        (cairo_content_t)aContent));
+        (cairo_content_t)(int)aContent));
 }
 
 gfxD2DSurface::gfxD2DSurface(HANDLE handle, gfxContentType aContent)
 {
     Init(cairo_d2d_surface_create_for_handle(
         gfxWindowsPlatform::GetPlatform()->GetD2DDevice(),
         handle,
-	(cairo_content_t)aContent));
+	(cairo_content_t)(int)aContent));
 }
 
 gfxD2DSurface::gfxD2DSurface(ID3D10Texture2D *texture, gfxContentType aContent)
 {
     Init(cairo_d2d_surface_create_for_texture(
         gfxWindowsPlatform::GetPlatform()->GetD2DDevice(),
         texture,
-	(cairo_content_t)aContent));
+	(cairo_content_t)(int)aContent));
 }
 
 gfxD2DSurface::gfxD2DSurface(cairo_surface_t *csurf)
 {
     Init(csurf, true);
 }
 
 gfxD2DSurface::gfxD2DSurface(const gfxIntSize& size,
                              gfxImageFormat imageFormat)
 {
     Init(cairo_d2d_surface_create(
         gfxWindowsPlatform::GetPlatform()->GetD2DDevice(),
-        (cairo_format_t)imageFormat,
+        (cairo_format_t)(int)imageFormat,
         size.width, size.height));
 }
 
 gfxD2DSurface::~gfxD2DSurface()
 {
 }
 
 void
--- a/gfx/thebes/gfxD2DSurface.h
+++ b/gfx/thebes/gfxD2DSurface.h
@@ -16,17 +16,17 @@ struct nsIntRect;
 
 class gfxD2DSurface : public gfxASurface {
 public:
 
     gfxD2DSurface(HWND wnd,
                   gfxContentType aContent);
 
     gfxD2DSurface(const gfxIntSize& size,
-                  gfxImageFormat imageFormat = gfxImageFormatRGB24);
+                  gfxImageFormat imageFormat = gfxImageFormat::RGB24);
 
     gfxD2DSurface(HANDLE handle, gfxContentType aContent);
 
     gfxD2DSurface(ID3D10Texture2D *texture, gfxContentType aContent);
 
     gfxD2DSurface(cairo_surface_t *csurf);
 
     void MovePixels(const nsIntRect& aSourceRect,
--- a/gfx/thebes/gfxDrawable.cpp
+++ b/gfx/thebes/gfxDrawable.cpp
@@ -70,17 +70,17 @@ PreparePatternForUntiledDrawing(gfxPatte
     }
 
     // In theory we can handle this using cairo's EXTEND_PAD,
     // but implementation limitations mean we have to consult
     // the surface type.
     switch (currentTarget->GetType()) {
 
 #ifdef MOZ_X11
-        case gfxSurfaceTypeXlib:
+        case gfxSurfaceType::Xlib:
         {
             // See bugs 324698, 422179, and 468496.  This is a workaround for
             // XRender's RepeatPad not being implemented correctly on old X
             // servers.
             //
             // In this situation, cairo avoids XRender and instead reads back
             // to perform EXTEND_PAD with pixman.  This is too slow so we
             // avoid EXTEND_PAD and set the filter to CAIRO_FILTER_FAST ---
@@ -191,17 +191,17 @@ gfxCallbackDrawable::gfxCallbackDrawable
  , mCallback(aCallback)
 {
 }
 
 already_AddRefed<gfxSurfaceDrawable>
 gfxCallbackDrawable::MakeSurfaceDrawable(const GraphicsFilter aFilter)
 {
     nsRefPtr<gfxASurface> surface =
-        gfxPlatform::GetPlatform()->CreateOffscreenSurface(mSize, GFX_CONTENT_COLOR_ALPHA);
+        gfxPlatform::GetPlatform()->CreateOffscreenSurface(mSize, gfxContentType::COLOR_ALPHA);
     if (!surface || surface->CairoStatus() != 0)
         return nullptr;
 
     nsRefPtr<gfxContext> ctx = new gfxContext(surface);
     Draw(ctx, gfxRect(0, 0, mSize.width, mSize.height), false, aFilter);
     nsRefPtr<gfxSurfaceDrawable> drawable = new gfxSurfaceDrawable(surface, mSize);
     return drawable.forget();
 }
--- a/gfx/thebes/gfxFont.cpp
+++ b/gfx/thebes/gfxFont.cpp
@@ -6008,17 +6008,17 @@ struct BufferAlphaColor {
         mContext->Save();
         mContext->NewPath();
         mContext->Rectangle(gfxRect(aBounds.X() / appsPerDevUnit,
                     aBounds.Y() / appsPerDevUnit,
                     aBounds.Width() / appsPerDevUnit,
                     aBounds.Height() / appsPerDevUnit), true);
         mContext->Clip();
         mContext->SetColor(gfxRGBA(aAlphaColor.r, aAlphaColor.g, aAlphaColor.b));
-        mContext->PushGroup(GFX_CONTENT_COLOR_ALPHA);
+        mContext->PushGroup(gfxContentType::COLOR_ALPHA);
         mAlpha = aAlphaColor.a;
     }
 
     void PopAlpha()
     {
         // pop the text, using the color alpha as the opacity
         mContext->PopGroupToSource();
         mContext->SetOperator(gfxContext::OPERATOR_OVER);
@@ -6288,32 +6288,32 @@ gfxTextRun::BreakAndMeasureText(uint32_t
         // line: if the width is too small for even one character to fit, it 
         // could be the first and last break opportunity on the line, and that
         // would trigger an infinite loop.
         if (!aSuppressInitialBreak || i > aStart) {
             bool lineBreakHere = mCharacterGlyphs[i].CanBreakBefore() == 1;
             bool hyphenation = haveHyphenation && hyphenBuffer[i - bufferStart];
             bool wordWrapping =
                 aCanWordWrap && mCharacterGlyphs[i].IsClusterStart() &&
-                *aBreakPriority <= eWordWrapBreak;
+                *aBreakPriority <= gfxBreakPriority::eWordWrapBreak;
 
             if (lineBreakHere || hyphenation || wordWrapping) {
                 gfxFloat hyphenatedAdvance = advance;
                 if (!lineBreakHere && !wordWrapping) {
                     hyphenatedAdvance += aProvider->GetHyphenWidth();
                 }
             
                 if (lastBreak < 0 || width + hyphenatedAdvance - trimmableAdvance <= aWidth) {
                     // We can break here.
                     lastBreak = i;
                     lastBreakTrimmableChars = trimmableChars;
                     lastBreakTrimmableAdvance = trimmableAdvance;
                     lastBreakUsedHyphenation = !lineBreakHere && !wordWrapping;
                     *aBreakPriority = hyphenation || lineBreakHere ?
-                        eNormalBreak : eWordWrapBreak;
+                        gfxBreakPriority::eNormalBreak : gfxBreakPriority::eWordWrapBreak;
                 }
 
                 width += advance;
                 advance = 0;
                 if (width - trimmableAdvance > aWidth) {
                     // No more text fits. Abort
                     aborted = true;
                     break;
--- a/gfx/thebes/gfxImageSurface.cpp
+++ b/gfx/thebes/gfxImageSurface.cpp
@@ -15,17 +15,17 @@
 #include "gfx2DGlue.h"
 #include <algorithm>
 
 using namespace mozilla::gfx;
 
 gfxImageSurface::gfxImageSurface()
   : mSize(0, 0),
     mOwnsData(false),
-    mFormat(gfxImageFormatUnknown),
+    mFormat(gfxImageFormat::Unknown),
     mStride(0)
 {
 }
 
 void
 gfxImageSurface::InitFromSurface(cairo_surface_t *csurf)
 {
     mSize.width = cairo_image_surface_get_width(csurf);
@@ -62,17 +62,17 @@ gfxImageSurface::InitWithData(unsigned c
     mFormat = aFormat;
     mStride = aStride;
 
     if (!CheckSurfaceSize(aSize))
         MakeInvalid();
 
     cairo_surface_t *surface =
         cairo_image_surface_create_for_data((unsigned char*)mData,
-                                            (cairo_format_t)mFormat,
+                                            (cairo_format_t)(int)mFormat,
                                             mSize.width,
                                             mSize.height,
                                             mStride);
 
     // cairo_image_surface_create_for_data can return a 'null' surface
     // in out of memory conditions. The gfxASurface::Init call checks
     // the surface it receives to see if there is an error with the
     // surface and handles it appropriately. That is why there is
@@ -131,17 +131,17 @@ gfxImageSurface::AllocateAndInit(long aS
         if (aClear)
             memset(mData, 0, aMinimalAllocation);
     }
 
     mOwnsData = true;
 
     cairo_surface_t *surface =
         cairo_image_surface_create_for_data((unsigned char*)mData,
-                                            (cairo_format_t)mFormat,
+                                            (cairo_format_t)(int)mFormat,
                                             mSize.width,
                                             mSize.height,
                                             mStride);
 
     Init(surface);
 
     if (mSurfaceValid) {
         RecordMemoryUsed(mSize.height * ComputeStride() +
@@ -174,25 +174,25 @@ gfxImageSurface::~gfxImageSurface()
         free(mData);
 }
 
 /*static*/ long
 gfxImageSurface::ComputeStride(const gfxIntSize& aSize, gfxImageFormat aFormat)
 {
     long stride;
 
-    if (aFormat == gfxImageFormatARGB32)
+    if (aFormat == gfxImageFormat::ARGB32)
         stride = aSize.width * 4;
-    else if (aFormat == gfxImageFormatRGB24)
+    else if (aFormat == gfxImageFormat::RGB24)
         stride = aSize.width * 4;
-    else if (aFormat == gfxImageFormatRGB16_565)
+    else if (aFormat == gfxImageFormat::RGB16_565)
         stride = aSize.width * 2;
-    else if (aFormat == gfxImageFormatA8)
+    else if (aFormat == gfxImageFormat::A8)
         stride = aSize.width;
-    else if (aFormat == gfxImageFormatA1) {
+    else if (aFormat == gfxImageFormat::A1) {
         stride = (aSize.width + 7) / 8;
     } else {
         NS_WARNING("Unknown format specified to gfxImageSurface!");
         stride = aSize.width * 4;
     }
 
     stride = ((stride + 3) / 4) * 4;
 
@@ -238,20 +238,20 @@ CopyForStride(unsigned char* aDest, unsi
     }
 }
 
 // helper function for the CopyFrom methods
 static bool
 FormatsAreCompatible(gfxImageFormat a1, gfxImageFormat a2)
 {
     if (a1 != a2 &&
-        !(a1 == gfxImageFormatARGB32 &&
-          a2 == gfxImageFormatRGB24) &&
-        !(a1 == gfxImageFormatRGB24 &&
-          a2 == gfxImageFormatARGB32)) {
+        !(a1 == gfxImageFormat::ARGB32 &&
+          a2 == gfxImageFormat::RGB24) &&
+        !(a1 == gfxImageFormat::RGB24 &&
+          a2 == gfxImageFormat::ARGB32)) {
         return false;
     }
 
     return true;
 }
 
 bool
 gfxImageSurface::CopyFrom (SourceSurface *aSurface)
@@ -325,19 +325,19 @@ gfxImageSurface::GetSubimage(const gfxRe
     MOZ_ASSERT(gfxRect(0, 0, mSize.width, mSize.height).Contains(r));
 
     gfxImageFormat format = Format();
 
     unsigned char* subData = Data() +
         (Stride() * (int)r.Y()) +
         (int)r.X() * gfxASurface::BytePerPixelFromFormat(Format());
 
-    if (format == gfxImageFormatARGB32 &&
+    if (format == gfxImageFormat::ARGB32 &&
         GetOpaqueRect().Contains(aRect)) {
-        format = gfxImageFormatRGB24;
+        format = gfxImageFormat::RGB24;
     }
 
     nsRefPtr<gfxSubimageSurface> image =
         new gfxSubimageSurface(this, subData,
                                gfxIntSize((int)r.Width(), (int)r.Height()),
                                format);
 
     return image.forget();
--- a/gfx/thebes/gfxOS2Platform.cpp
+++ b/gfx/thebes/gfxOS2Platform.cpp
@@ -53,23 +53,23 @@ gfxOS2Platform::CreateOffscreenSurface(c
                                        gfxContentType contentType)
 {
 #ifdef DEBUG_thebes_2
     printf("gfxOS2Platform::CreateOffscreenSurface(%d/%d, %d)\n",
            aSize.width, aSize.height, aImageFormat);
 #endif
     gfxASurface *newSurface = nullptr;
 
-    // we only ever seem to get aImageFormat=0 or gfxImageFormatARGB32 but
+    // we only ever seem to get aImageFormat=0 or gfxImageFormat::ARGB32 but
     // I don't really know if we need to differ between ARGB32 and RGB24 here
-    if (contentType == GFX_CONTENT_COLOR_ALPHA ||
-        contentType == GFX_CONTENT_COLOR)
+    if (contentType == gfxContentType::COLOR_ALPHA ||
+        contentType == gfxContentType::COLOR)
     {
         newSurface = new gfxOS2Surface(aSize, OptimalFormatForContent(contentType));
-    } else if (contentType == GFX_CONTENT_ALPHA) {
+    } else if (contentType == gfxContentType::ALPHA) {
         newSurface = new gfxImageSurface(aSize, OptimalFormatForContent(contentType));
     } else {
         return nullptr;
     }
 
     NS_IF_ADDREF(newSurface);
     return newSurface;
 }
--- a/gfx/thebes/gfxPlatform.cpp
+++ b/gfx/thebes/gfxPlatform.cpp
@@ -432,17 +432,17 @@ gfxPlatform::Init()
     rv = gfxPlatformFontList::Init();
     if (NS_FAILED(rv)) {
         NS_RUNTIMEABORT("Could not initialize gfxPlatformFontList");
     }
 #endif
 
     gPlatform->mScreenReferenceSurface =
         gPlatform->CreateOffscreenSurface(gfxIntSize(1,1),
-                                          GFX_CONTENT_COLOR_ALPHA);
+                                          gfxContentType::COLOR_ALPHA);
     if (!gPlatform->mScreenReferenceSurface) {
         NS_RUNTIMEABORT("Could not initialize mScreenReferenceSurface");
     }
 
     if (gPlatform->SupportsAzureContent()) {
         gPlatform->mScreenReferenceDrawTarget =
             gPlatform->CreateOffscreenContentDrawTarget(IntSize(1, 1),
                                                         SurfaceFormat::B8G8R8A8);
@@ -663,17 +663,17 @@ gfxPlatform::CreateDrawTargetForSurface(
 // around the gfxASurface. This should eventually be replaced by plumbing
 // the DrawTarget through directly
 RefPtr<DrawTarget>
 gfxPlatform::CreateDrawTargetForUpdateSurface(gfxASurface *aSurface, const IntSize& aSize)
 {
 #ifdef XP_MACOSX
   // this is a bit of a hack that assumes that the buffer associated with the CGContext
   // will live around long enough that nothing bad will happen.
-  if (aSurface->GetType() == gfxSurfaceTypeQuartz) {
+  if (aSurface->GetType() == gfxSurfaceType::Quartz) {
     return Factory::CreateDrawTargetForCairoCGContext(static_cast<gfxQuartzSurface*>(aSurface)->GetCGContext(), aSize);
   }
 #endif
   MOZ_CRASH();
   return nullptr;
 }
 
 
@@ -742,28 +742,28 @@ gfxPlatform::GetSourceSurfaceForSurface(
     if (surf->mSrcSurface->IsValid() && surf->mBackendType == aTarget->GetType()) {
       return surf->mSrcSurface;
     }
     // We can just continue here as when setting new user data the destroy
     // function will be called for the old user data.
   }
 
   SurfaceFormat format;
-  if (aSurface->GetContentType() == GFX_CONTENT_ALPHA) {
+  if (aSurface->GetContentType() == gfxContentType::ALPHA) {
     format = SurfaceFormat::A8;
-  } else if (aSurface->GetContentType() == GFX_CONTENT_COLOR) {
+  } else if (aSurface->GetContentType() == gfxContentType::COLOR) {
     format = SurfaceFormat::B8G8R8X8;
   } else {
     format = SurfaceFormat::B8G8R8A8;
   }
 
   RefPtr<SourceSurface> srcBuffer;
 
 #ifdef XP_WIN
-  if (aSurface->GetType() == gfxSurfaceTypeD2D &&
+  if (aSurface->GetType() == gfxSurfaceType::D2D &&
       format != SurfaceFormat::A8) {
     NativeSurface surf;
     surf.mFormat = format;
     surf.mType = NativeSurfaceType::D3D10_TEXTURE;
     surf.mSurface = static_cast<gfxD2DSurface*>(aSurface)->GetTexture();
     mozilla::gfx::DrawTarget *dt = static_cast<mozilla::gfx::DrawTarget*>(aSurface->GetData(&kDrawTarget));
     if (dt) {
       dt->Flush();
@@ -786,38 +786,38 @@ gfxPlatform::GetSourceSurfaceForSurface(
       return srcBuffer;
     }
   }
 
   if (!srcBuffer) {
     nsRefPtr<gfxImageSurface> imgSurface = aSurface->GetAsImageSurface();
 
     bool isWin32ImageSurf = imgSurface &&
-                            aSurface->GetType() == gfxSurfaceTypeWin32;
+                            aSurface->GetType() == gfxSurfaceType::Win32;
 
     if (!imgSurface) {
       imgSurface = new gfxImageSurface(aSurface->GetSize(), OptimalFormatForContent(aSurface->GetContentType()));
       nsRefPtr<gfxContext> ctx = new gfxContext(imgSurface);
       ctx->SetSource(aSurface);
       ctx->SetOperator(gfxContext::OPERATOR_SOURCE);
       ctx->Paint();
     }
 
     gfxImageFormat cairoFormat = imgSurface->Format();
     switch(cairoFormat) {
-      case gfxImageFormatARGB32:
+      case gfxImageFormat::ARGB32:
         format = SurfaceFormat::B8G8R8A8;
         break;
-      case gfxImageFormatRGB24:
+      case gfxImageFormat::RGB24:
         format = SurfaceFormat::B8G8R8X8;
         break;
-      case gfxImageFormatA8:
+      case gfxImageFormat::A8:
         format = SurfaceFormat::A8;
         break;
-      case gfxImageFormatRGB16_565:
+      case gfxImageFormat::RGB16_565:
         format = SurfaceFormat::R5G6B5;
         break;
       default:
         NS_RUNTIMEABORT("Invalid surface format!");
     }
 
     IntSize size = IntSize(imgSurface->GetSize().width, imgSurface->GetSize().height);
     srcBuffer = aTarget->CreateSourceSurfaceFromData(imgSurface->Data(),
@@ -1996,51 +1996,51 @@ gfxPlatform::GetScreenDepth() const
     NS_WARNING("GetScreenDepth not implemented on this platform -- returning 0!");
     return 0;
 }
 
 mozilla::gfx::SurfaceFormat
 gfxPlatform::Optimal2DFormatForContent(gfxContentType aContent)
 {
   switch (aContent) {
-  case GFX_CONTENT_COLOR:
+  case gfxContentType::COLOR:
     switch (GetOffscreenFormat()) {
-    case gfxImageFormatARGB32:
+    case gfxImageFormat::ARGB32:
       return mozilla::gfx::SurfaceFormat::B8G8R8A8;
-    case gfxImageFormatRGB24:
+    case gfxImageFormat::RGB24:
       return mozilla::gfx::SurfaceFormat::B8G8R8X8;
-    case gfxImageFormatRGB16_565:
+    case gfxImageFormat::RGB16_565:
       return mozilla::gfx::SurfaceFormat::R5G6B5;
     default:
-      NS_NOTREACHED("unknown gfxImageFormat for GFX_CONTENT_COLOR");
+      NS_NOTREACHED("unknown gfxImageFormat for gfxContentType::COLOR");
       return mozilla::gfx::SurfaceFormat::B8G8R8A8;
     }
-  case GFX_CONTENT_ALPHA:
+  case gfxContentType::ALPHA:
     return mozilla::gfx::SurfaceFormat::A8;
-  case GFX_CONTENT_COLOR_ALPHA:
+  case gfxContentType::COLOR_ALPHA:
     return mozilla::gfx::SurfaceFormat::B8G8R8A8;
   default:
     NS_NOTREACHED("unknown gfxContentType");
     return mozilla::gfx::SurfaceFormat::B8G8R8A8;
   }
 }
 
 gfxImageFormat
 gfxPlatform::OptimalFormatForContent(gfxContentType aContent)
 {
   switch (aContent) {
-  case GFX_CONTENT_COLOR:
+  case gfxContentType::COLOR:
     return GetOffscreenFormat();
-  case GFX_CONTENT_ALPHA:
-    return gfxImageFormatA8;
-  case GFX_CONTENT_COLOR_ALPHA:
-    return gfxImageFormatARGB32;
+  case gfxContentType::ALPHA:
+    return gfxImageFormat::A8;
+  case gfxContentType::COLOR_ALPHA:
+    return gfxImageFormat::ARGB32;
   default:
     NS_NOTREACHED("unknown gfxContentType");
-    return gfxImageFormatARGB32;
+    return gfxImageFormat::ARGB32;
   }
 }
 
 void
 gfxPlatform::OrientationSyncPrefsObserverChanged()
 {
   mOrientationSyncMillis = Preferences::GetUint("layers.orientation.sync.timeout", (uint32_t)0);
 }
--- a/gfx/thebes/gfxPlatform.h
+++ b/gfx/thebes/gfxPlatform.h
@@ -590,17 +590,17 @@ public:
     gfxASurface* ScreenReferenceSurface() { return mScreenReferenceSurface; }
     mozilla::gfx::DrawTarget* ScreenReferenceDrawTarget() { return mScreenReferenceDrawTarget; }
 
     virtual mozilla::gfx::SurfaceFormat Optimal2DFormatForContent(gfxContentType aContent);
 
     virtual gfxImageFormat OptimalFormatForContent(gfxContentType aContent);
 
     virtual gfxImageFormat GetOffscreenFormat()
-    { return gfxImageFormatRGB24; }
+    { return gfxImageFormat::RGB24; }
 
     /**
      * Returns a logger if one is available and logging is enabled
      */
     static PRLogModuleInfo* GetLog(eGfxLog aWhichLog);
 
     bool WorkAroundDriverBugs() const { return mWorkAroundDriverBugs; }
 
--- a/gfx/thebes/gfxPlatformGtk.cpp
+++ b/gfx/thebes/gfxPlatformGtk.cpp
@@ -237,20 +237,20 @@ gfxPlatformGtk::GetDPI()
 }
 
 gfxImageFormat
 gfxPlatformGtk::GetOffscreenFormat()
 {
     // Make sure there is a screen
     GdkScreen *screen = gdk_screen_get_default();
     if (screen && gdk_visual_get_depth(gdk_visual_get_system()) == 16) {
-        return gfxImageFormatRGB16_565;
+        return gfxImageFormat::RGB16_565;
     }
 
-    return gfxImageFormatRGB24;
+    return gfxImageFormat::RGB24;
 }
 
 static int sDepth = 0;
 
 int
 gfxPlatformGtk::GetScreenDepth() const
 {
     if (!sDepth) {
--- a/gfx/thebes/gfxPlatformMac.cpp
+++ b/gfx/thebes/gfxPlatformMac.cpp
@@ -367,18 +367,18 @@ gfxPlatformMac::CreateThebesSurfaceAlias
 {
   if (aTarget->GetType() == BackendType::COREGRAPHICS) {
     CGContextRef cg = static_cast<CGContextRef>(aTarget->GetNativeSurface(NativeSurfaceType::CGCONTEXT));
     unsigned char* data = (unsigned char*)CGBitmapContextGetData(cg);
     size_t bpp = CGBitmapContextGetBitsPerPixel(cg);
     size_t stride = CGBitmapContextGetBytesPerRow(cg);
     gfxIntSize size(aTarget->GetSize().width, aTarget->GetSize().height);
     nsRefPtr<gfxImageSurface> imageSurface = new gfxImageSurface(data, size, stride, bpp == 2
-                                                                                     ? gfxImageFormatRGB16_565
-                                                                                     : gfxImageFormatARGB32);
+                                                                                     ? gfxImageFormat::RGB16_565
+                                                                                     : gfxImageFormat::ARGB32);
     // Here we should return a gfxQuartzImageSurface but quartz will assumes that image surfaces
     // don't change which wont create a proper alias to the draw target, therefore we have to
     // return a plain image surface.
     return imageSurface.forget();
   } else {
     return GetThebesSurfaceForDrawTarget(aTarget);
   }
 }
@@ -386,19 +386,19 @@ gfxPlatformMac::CreateThebesSurfaceAlias
 already_AddRefed<gfxASurface>
 gfxPlatformMac::GetThebesSurfaceForDrawTarget(DrawTarget *aTarget)
 {
   if (aTarget->GetType() == BackendType::COREGRAPHICS_ACCELERATED) {
     RefPtr<SourceSurface> source = aTarget->Snapshot();
     RefPtr<DataSourceSurface> sourceData = source->GetDataSurface();
     unsigned char* data = sourceData->GetData();
     nsRefPtr<gfxImageSurface> surf = new gfxImageSurface(data, ThebesIntSize(sourceData->GetSize()), sourceData->Stride(),
-                                                         gfxImageFormatARGB32);
+                                                         gfxImageFormat::ARGB32);
     // We could fix this by telling gfxImageSurface it owns data.
-    nsRefPtr<gfxImageSurface> cpy = new gfxImageSurface(ThebesIntSize(sourceData->GetSize()), gfxImageFormatARGB32);
+    nsRefPtr<gfxImageSurface> cpy = new gfxImageSurface(ThebesIntSize(sourceData->GetSize()), gfxImageFormat::ARGB32);
     cpy->CopyFrom(surf);
     return cpy.forget();
   } else if (aTarget->GetType() == BackendType::COREGRAPHICS) {
     CGContextRef cg = static_cast<CGContextRef>(aTarget->GetNativeSurface(NativeSurfaceType::CGCONTEXT));
 
     //XXX: it would be nice to have an implicit conversion from IntSize to gfxIntSize
     IntSize intSize = aTarget->GetSize();
     gfxIntSize size(intSize.width, intSize.height);
--- a/gfx/thebes/gfxQtPlatform.cpp
+++ b/gfx/thebes/gfxQtPlatform.cpp
@@ -59,17 +59,17 @@ static QPaintEngine::Type sDefaultQtPain
 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 = gfxImageFormatRGB24;
+static gfxImageFormat sOffscreenFormat = gfxImageFormat::RGB24;
 
 gfxQtPlatform::gfxQtPlatform()
 {
     mPrefFonts.Init(50);
 
     if (!sFontconfigUtils)
         sFontconfigUtils = gfxFontconfigUtils::GetFontconfigUtils();
 
@@ -97,17 +97,17 @@ gfxQtPlatform::gfxQtPlatform()
         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) {
-        sOffscreenFormat = gfxImageFormatRGB16_565;
+        sOffscreenFormat = gfxImageFormat::RGB16_565;
     }
     mScreenDepth = pixmap.depth();
 #if (QT_VERSION < QT_VERSION_CHECK(4,8,0))
     if (pixmap.paintEngine())
         sDefaultQtPaintEngineType = pixmap.paintEngine()->type();
 #endif
 }
 
--- a/gfx/thebes/gfxQuartzNativeDrawing.cpp
+++ b/gfx/thebes/gfxQuartzNativeDrawing.cpp
@@ -69,19 +69,19 @@ gfxQuartzNativeDrawing::BeginNativeDrawi
     }
     if (!surf || surf->CairoStatus())
         return nullptr;
 
     // if this is a native Quartz surface, we don't have to redirect
     // rendering to our own CGContextRef; in most cases, we are able to
     // use the CGContextRef from the surface directly.  we can extend
     // this to support offscreen drawing fairly easily in the future.
-    if (surf->GetType() == gfxSurfaceTypeQuartz &&
-        (surf->GetContentType() == GFX_CONTENT_COLOR ||
-         (surf->GetContentType() == GFX_CONTENT_COLOR_ALPHA))) {
+    if (surf->GetType() == gfxSurfaceType::Quartz &&
+        (surf->GetContentType() == gfxContentType::COLOR ||
+         (surf->GetContentType() == gfxContentType::COLOR_ALPHA))) {
         mQuartzSurface = static_cast<gfxQuartzSurface*>(surf.get());
         mSurfaceContext = mContext;
 
         // grab the CGContextRef
         mCGContext = cairo_quartz_get_cg_context_with_clip(mSurfaceContext->GetCairo());
         if (!mCGContext)
             return nullptr;
 
@@ -108,17 +108,17 @@ gfxQuartzNativeDrawing::BeginNativeDrawi
                                                              x0, y0));
 
         // bug 382049 - need to explicity set the composite operation to sourceOver
         CGContextSetCompositeOperation(mCGContext, kPrivateCGCompositeSourceOver);
     } else {
         nsIntSize backingSize(NSToIntFloor(mNativeRect.width * mBackingScale),
                               NSToIntFloor(mNativeRect.height * mBackingScale));
         mQuartzSurface = new gfxQuartzSurface(backingSize,
-                                              gfxImageFormatARGB32);
+                                              gfxImageFormat::ARGB32);
         if (mQuartzSurface->CairoStatus())
             return nullptr;
         mSurfaceContext = new gfxContext(mQuartzSurface);
 
         // grab the CGContextRef
         mCGContext = cairo_quartz_get_cg_context_with_clip(mSurfaceContext->GetCairo());
         CGContextScaleCTM(mCGContext, mBackingScale, mBackingScale);
         CGContextTranslateCTM(mCGContext, -mNativeRect.X(), -mNativeRect.Y());
--- a/gfx/thebes/gfxTypes.h
+++ b/gfx/thebes/gfxTypes.h
@@ -1,16 +1,19 @@
 /* -*- 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/. */
 
 #ifndef GFX_TYPES_H
 #define GFX_TYPES_H
 
+#include <stdint.h>
+#include "mozilla/TypedEnum.h"
+
 typedef struct _cairo_surface cairo_surface_t;
 typedef struct _cairo_user_data_key cairo_user_data_key_t;
 
 typedef void (*thebes_destroy_func_t) (void *data);
 
 /**
  * Currently needs to be 'double' for Cairo compatibility. Could
  * become 'float', perhaps, in some configurations.
@@ -31,75 +34,75 @@ typedef double gfxFloat;
  *                    punctuation break and whitespace break (bug 389710).
  *                   As and when we implement it, text-wrap: unrestricted will
  *                    mean that priorities are ignored and all line-break
  *                    opportunities are equal.
  *
  * @see gfxTextRun::BreakAndMeasureText
  * @see nsLineLayout::NotifyOptionalBreakPosition
  */
-enum gfxBreakPriority {
-    eNoBreak       = 0,
-    eWordWrapBreak,
-    eNormalBreak
-};
+MOZ_BEGIN_ENUM_CLASS(gfxBreakPriority)
+  eNoBreak       = 0,
+  eWordWrapBreak,
+  eNormalBreak
+MOZ_END_ENUM_CLASS(gfxBreakPriority)
 
-    /**
-     * The format for an image surface. For all formats with alpha data, 0
-     * means transparent, 1 or 255 means fully opaque.
-     */
-    enum gfxImageFormat {
-        gfxImageFormatARGB32, ///< ARGB data in native endianness, using premultiplied alpha
-        gfxImageFormatRGB24,  ///< xRGB data in native endianness
-        gfxImageFormatA8,     ///< Only an alpha channel
-        gfxImageFormatA1,     ///< Packed transparency information (one byte refers to 8 pixels)
-        gfxImageFormatRGB16_565,  ///< RGB_565 data in native endianness
-        gfxImageFormatUnknown
-    };
+/**
+  * The format for an image surface. For all formats with alpha data, 0
+  * means transparent, 1 or 255 means fully opaque.
+  */
+MOZ_BEGIN_ENUM_CLASS(gfxImageFormat)
+  ARGB32, ///< ARGB data in native endianness, using premultiplied alpha
+  RGB24,  ///< xRGB data in native endianness
+  A8,     ///< Only an alpha channel
+  A1,     ///< Packed transparency information (one byte refers to 8 pixels)
+  RGB16_565,  ///< RGB_565 data in native endianness
+  Unknown
+MOZ_END_ENUM_CLASS(gfxImageFormat)
 
-    enum gfxSurfaceType {
-        gfxSurfaceTypeImage,
-        gfxSurfaceTypePDF,
-        gfxSurfaceTypePS,
-        gfxSurfaceTypeXlib,
-        gfxSurfaceTypeXcb,
-        gfxSurfaceTypeGlitz,           // unused, but needed for cairo parity
-        gfxSurfaceTypeQuartz,
-        gfxSurfaceTypeWin32,
-        gfxSurfaceTypeBeOS,
-        gfxSurfaceTypeDirectFB,        // unused, but needed for cairo parity
-        gfxSurfaceTypeSVG,
-        gfxSurfaceTypeOS2,
-        gfxSurfaceTypeWin32Printing,
-        gfxSurfaceTypeQuartzImage,
-        gfxSurfaceTypeScript,
-        gfxSurfaceTypeQPainter,
-        gfxSurfaceTypeRecording,
-        gfxSurfaceTypeVG,
-        gfxSurfaceTypeGL,
-        gfxSurfaceTypeDRM,
-        gfxSurfaceTypeTee,
-        gfxSurfaceTypeXML,
-        gfxSurfaceTypeSkia,
-        gfxSurfaceTypeSubsurface,
-        gfxSurfaceTypeD2D,
-        gfxSurfaceTypeMax
-    };
+MOZ_BEGIN_ENUM_CLASS(gfxSurfaceType)
+  Image,
+  PDF,
+  PS,
+  Xlib,
+  Xcb,
+  Glitz,           // unused, but needed for cairo parity
+  Quartz,
+  Win32,
+  BeOS,
+  DirectFB,        // unused, but needed for cairo parity
+  SVG,
+  OS2,
+  Win32Printing,
+  QuartzImage,
+  Script,
+  QPainter,
+  Recording,
+  VG,
+  GL,
+  DRM,
+  Tee,
+  XML,
+  Skia,
+  Subsurface,
+  D2D,
+  Max
+MOZ_END_ENUM_CLASS(gfxSurfaceType)
 
-    enum gfxContentType {
-        GFX_CONTENT_COLOR       = 0x1000,
-        GFX_CONTENT_ALPHA       = 0x2000,
-        GFX_CONTENT_COLOR_ALPHA = 0x3000,
-        GFX_CONTENT_SENTINEL    = 0xffff
-    };
+MOZ_BEGIN_ENUM_CLASS(gfxContentType)
+  COLOR       = 0x1000,
+  ALPHA       = 0x2000,
+  COLOR_ALPHA = 0x3000,
+  SENTINEL    = 0xffff
+MOZ_END_ENUM_CLASS(gfxContentType)
 
-    /**
-     * The memory used by this surface (as reported by KnownMemoryUsed()) can
-     * either live in this process's heap, in this process but outside the
-     * heap, or in another process altogether.
-     */
-    enum gfxMemoryLocation {
-      GFX_MEMORY_IN_PROCESS_HEAP,
-      GFX_MEMORY_IN_PROCESS_NONHEAP,
-      GFX_MEMORY_OUT_OF_PROCESS
-    };
+/**
+  * The memory used by a gfxASurface (as reported by KnownMemoryUsed()) can
+  * either live in this process's heap, in this process but outside the
+  * heap, or in another process altogether.
+  */
+MOZ_BEGIN_ENUM_CLASS(gfxMemoryLocation)
+  IN_PROCESS_HEAP,
+  IN_PROCESS_NONHEAP,
+  OUT_OF_PROCESS
+MOZ_END_ENUM_CLASS(gfxMemoryLocation)
 
 #endif /* GFX_TYPES_H */
--- a/gfx/thebes/gfxUtils.cpp
+++ b/gfx/thebes/gfxUtils.cpp
@@ -44,17 +44,17 @@ gfxUtils::PremultiplyImageSurface(gfxIma
                aSourceSurface->Height() == aDestSurface->Height() &&
                aSourceSurface->Stride() == aDestSurface->Stride(),
                "Source and destination surfaces don't have identical characteristics");
 
     MOZ_ASSERT(aSourceSurface->Stride() == aSourceSurface->Width() * 4,
                "Source surface stride isn't tightly packed");
 
     // Only premultiply ARGB32
-    if (aSourceSurface->Format() != gfxImageFormatARGB32) {
+    if (aSourceSurface->Format() != gfxImageFormat::ARGB32) {
         if (aDestSurface != aSourceSurface) {
             memcpy(aDestSurface->Data(), aSourceSurface->Data(),
                    aSourceSurface->Stride() * aSourceSurface->Height());
         }
         return;
     }
 
     uint8_t *src = aSourceSurface->Data();
@@ -94,17 +94,17 @@ gfxUtils::UnpremultiplyImageSurface(gfxI
         aDestSurface = aSourceSurface;
 
     MOZ_ASSERT(aSourceSurface->Format() == aDestSurface->Format() &&
                aSourceSurface->Width()  == aDestSurface->Width() &&
                aSourceSurface->Height() == aDestSurface->Height(),
                "Source and destination surfaces don't have identical characteristics");
 
     // Only premultiply ARGB32
-    if (aSourceSurface->Format() != gfxImageFormatARGB32) {
+    if (aSourceSurface->Format() != gfxImageFormat::ARGB32) {
         if (aDestSurface != aSourceSurface) {
             aDestSurface->CopyFrom(aSourceSurface);
         }
         return;
     }
 
     uint8_t *src = aSourceSurface->Data();
     uint8_t *dst = aDestSurface->Data();
@@ -149,17 +149,17 @@ gfxUtils::ConvertBGRAtoRGBA(gfxImageSurf
                aSourceSurface->Width()  == aDestSurface->Width() &&
                aSourceSurface->Height() == aDestSurface->Height() &&
                aSourceSurface->Stride() == aDestSurface->Stride(),
                "Source and destination surfaces don't have identical characteristics");
 
     MOZ_ASSERT(aSourceSurface->Stride() == aSourceSurface->Width() * 4,
                "Source surface stride isn't tightly packed");
 
-    MOZ_ASSERT(aSourceSurface->Format() == gfxImageFormatARGB32 || aSourceSurface->Format() == gfxImageFormatRGB24,
+    MOZ_ASSERT(aSourceSurface->Format() == gfxImageFormat::ARGB32 || aSourceSurface->Format() == gfxImageFormat::RGB24,
                "Surfaces must be ARGB32 or RGB24");
 
     uint8_t *src = aSourceSurface->Data();
     uint8_t *dst = aDestSurface->Data();
 
     uint32_t dim = aSourceSurface->Width() * aSourceSurface->Height();
     uint8_t *srcEnd = src + 4*dim;
 
@@ -278,17 +278,17 @@ struct MOZ_STACK_CLASS AutoCairoPixmanBu
 {
     AutoCairoPixmanBugWorkaround(gfxContext*      aContext,
                                  const gfxMatrix& aDeviceSpaceToImageSpace,
                                  const gfxRect&   aFill,
                                  const gfxASurface* aSurface)
      : mContext(aContext), mSucceeded(true), mPushedGroup(false)
     {
         // Quartz's limits for matrix are much larger than pixman
-        if (!aSurface || aSurface->GetType() == gfxSurfaceTypeQuartz)
+        if (!aSurface || aSurface->GetType() == gfxSurfaceType::Quartz)
             return;
 
         if (!IsSafeImageTransformComponent(aDeviceSpaceToImageSpace.xx) ||
             !IsSafeImageTransformComponent(aDeviceSpaceToImageSpace.xy) ||
             !IsSafeImageTransformComponent(aDeviceSpaceToImageSpace.yx) ||
             !IsSafeImageTransformComponent(aDeviceSpaceToImageSpace.yy)) {
             NS_WARNING("Scaling up too much, bailing out");
             mSucceeded = false;
@@ -307,17 +307,17 @@ struct MOZ_STACK_CLASS AutoCairoPixmanBu
         // Clip the rounded-out-to-device-pixels bounds of the
         // transformed fill area. This is the area for the group we
         // want to push.
         mContext->IdentityMatrix();
         gfxRect bounds = currentMatrix.TransformBounds(aFill);
         bounds.RoundOut();
         mContext->Clip(bounds);
         mContext->SetMatrix(currentMatrix);
-        mContext->PushGroup(GFX_CONTENT_COLOR_ALPHA);
+        mContext->PushGroup(gfxContentType::COLOR_ALPHA);
         mContext->SetOperator(gfxContext::OPERATOR_OVER);
 
         mPushedGroup = true;
     }
 
     ~AutoCairoPixmanBugWorkaround()
     {
         if (mPushedGroup) {
@@ -486,21 +486,21 @@ gfxUtils::DrawPixelSnapped(gfxContext*  
 
     drawable->Draw(aContext, aFill, doTile, aFilter, userSpaceToImageSpace);
 }
 
 /* static */ int
 gfxUtils::ImageFormatToDepth(gfxImageFormat aFormat)
 {
     switch (aFormat) {
-        case gfxImageFormatARGB32:
+        case gfxImageFormat::ARGB32:
             return 32;
-        case gfxImageFormatRGB24:
+        case gfxImageFormat::RGB24:
             return 24;
-        case gfxImageFormatRGB16_565:
+        case gfxImageFormat::RGB16_565:
             return 16;
         default:
             break;
     }
     return 0;
 }
 
 static void
@@ -695,17 +695,17 @@ gfxUtils::GetYCbCrToRGBDestFormatAndSize
                       aData.mCbCrSize.width,
                       aData.mCbCrSize.height);
 
   // 'prescale' is true if the scaling is to be done as part of the
   // YCbCr to RGB conversion rather than on the RGB data when rendered.
   bool prescale = aSuggestedSize.width > 0 && aSuggestedSize.height > 0 &&
                     ToIntSize(aSuggestedSize) != aData.mPicSize;
 
-  if (aSuggestedFormat == gfxImageFormatRGB16_565) {
+  if (aSuggestedFormat == gfxImageFormat::RGB16_565) {
 #if defined(HAVE_YCBCR_TO_RGB565)
     if (prescale &&
         !IsScaleYCbCrToRGB565Fast(aData.mPicX,
                                        aData.mPicY,
                                        aData.mPicSize.width,
                                        aData.mPicSize.height,
                                        aSuggestedSize.width,
                                        aSuggestedSize.height,
@@ -715,24 +715,24 @@ gfxUtils::GetYCbCrToRGBDestFormatAndSize
                                         aData.mPicY,
                                         aData.mPicSize.width,
                                         aData.mPicSize.height,
                                         yuvtype)) {
       prescale = false;
     }
 #else
     // yuv2rgb16 function not available
-    aSuggestedFormat = gfxImageFormatRGB24;
+    aSuggestedFormat = gfxImageFormat::RGB24;
 #endif
   }
-  else if (aSuggestedFormat != gfxImageFormatRGB24) {
+  else if (aSuggestedFormat != gfxImageFormat::RGB24) {
     // No other formats are currently supported.
-    aSuggestedFormat = gfxImageFormatRGB24;
+    aSuggestedFormat = gfxImageFormat::RGB24;
   }
-  if (aSuggestedFormat == gfxImageFormatRGB24) {
+  if (aSuggestedFormat == gfxImageFormat::RGB24) {
     /* ScaleYCbCrToRGB32 does not support a picture offset, nor 4:4:4 data.
        See bugs 639415 and 640073. */
     if (aData.mPicX != 0 || aData.mPicY != 0 || yuvtype == YV24)
       prescale = false;
   }
   if (!prescale) {
     ToIntSize(aSuggestedSize) = aData.mPicSize;
   }
@@ -755,17 +755,17 @@ gfxUtils::ConvertYCbCrToRGB(const Planar
     TypeFromSize(aData.mYSize.width,
                       aData.mYSize.height,
                       aData.mCbCrSize.width,
                       aData.mCbCrSize.height);
 
   // Convert from YCbCr to RGB now, scaling the image if needed.
   if (ToIntSize(aDestSize) != aData.mPicSize) {
 #if defined(HAVE_YCBCR_TO_RGB565)
-    if (aDestFormat == gfxImageFormatRGB16_565) {
+    if (aDestFormat == gfxImageFormat::RGB16_565) {
       ScaleYCbCrToRGB565(aData.mYChannel,
                               aData.mCbChannel,
                               aData.mCrChannel,
                               aDestBuffer,
                               aData.mPicX,
                               aData.mPicY,
                               aData.mPicSize.width,
                               aData.mPicSize.height,
@@ -789,30 +789,30 @@ gfxUtils::ConvertYCbCrToRGB(const Planar
                              aData.mYStride,
                              aData.mCbCrStride,
                              aStride,
                              yuvtype,
                              ROTATE_0,
                              FILTER_BILINEAR);
   } else { // no prescale
 #if defined(HAVE_YCBCR_TO_RGB565)
-    if (aDestFormat == gfxImageFormatRGB16_565) {
+    if (aDestFormat == gfxImageFormat::RGB16_565) {
       ConvertYCbCrToRGB565(aData.mYChannel,
                                 aData.mCbChannel,
                                 aData.mCrChannel,
                                 aDestBuffer,
                                 aData.mPicX,
                                 aData.mPicY,
                                 aData.mPicSize.width,
                                 aData.mPicSize.height,
                                 aData.mYStride,
                                 aData.mCbCrStride,
                                 aStride,
                                 yuvtype);
-    } else // aDestFormat != gfxImageFormatRGB16_565
+    } else // aDestFormat != gfxImageFormat::RGB16_565
 #endif
       ConvertYCbCrToRGB32(aData.mYChannel,
                                aData.mCbChannel,
                                aData.mCrChannel,
                                aDestBuffer,
                                aData.mPicX,
                                aData.mPicY,
                                aData.mPicSize.width,
--- a/gfx/thebes/gfxUtils.h
+++ b/gfx/thebes/gfxUtils.h
@@ -24,17 +24,17 @@ class gfxUtils {
 public:
     /*
      * Premultiply or Unpremultiply aSourceSurface, writing the result
      * to aDestSurface or back into aSourceSurface if aDestSurface is null.
      *
      * If aDestSurface is given, it must have identical format, dimensions, and
      * stride as the source.
      *
-     * If the source is not gfxImageFormatARGB32, no operation is performed.  If
+     * If the source is not gfxImageFormat::ARGB32, no operation is performed.  If
      * aDestSurface is given, the data is copied over.
      */
     static void PremultiplyImageSurface(gfxImageSurface *aSourceSurface,
                                         gfxImageSurface *aDestSurface = nullptr);
     static void UnpremultiplyImageSurface(gfxImageSurface *aSurface,
                                           gfxImageSurface *aDestSurface = nullptr);
 
     static void ConvertBGRAtoRGBA(gfxImageSurface *aSourceSurface,
@@ -120,17 +120,17 @@ public:
      * Return the smallest power of kScaleResolution (2) greater than or equal to
      * aVal.
      */
     static gfxFloat ClampToScaleFactor(gfxFloat aVal);
 
     /**
      * Helper function for ConvertYCbCrToRGB that finds the
      * RGB buffer size and format for given YCbCrImage.
-     * @param aSuggestedFormat will be set to gfxImageFormatRGB24
+     * @param aSuggestedFormat will be set to gfxImageFormat::RGB24
      *   if the desired format is not supported.
      * @param aSuggestedSize will be set to the picture size from aData
      *   if either the suggested size was {0,0}
      *   or simultaneous scaling and conversion is not supported.
      */
     static void
     GetYCbCrToRGBDestFormatAndSize(const mozilla::layers::PlanarYCbCrData& aData,
                                    gfxImageFormat& aSuggestedFormat,
--- a/gfx/thebes/gfxWindowsNativeDrawing.cpp
+++ b/gfx/thebes/gfxWindowsNativeDrawing.cpp
@@ -54,20 +54,20 @@ gfxWindowsNativeDrawing::BeginNativeDraw
             mTransformType = COMPLEX;
         else
             mTransformType = AXIS_ALIGNED_SCALE;
 
         // if this is a native win32 surface, we don't have to
         // redirect rendering to our own HDC; in some cases,
         // we may be able to use the HDC from the surface directly.
         if (surf &&
-            ((surf->GetType() == gfxSurfaceTypeWin32 ||
-              surf->GetType() == gfxSurfaceTypeWin32Printing) &&
-              (surf->GetContentType() == GFX_CONTENT_COLOR ||
-               (surf->GetContentType() == GFX_CONTENT_COLOR_ALPHA &&
+            ((surf->GetType() == gfxSurfaceType::Win32 ||
+              surf->GetType() == gfxSurfaceType::Win32Printing) &&
+              (surf->GetContentType() == gfxContentType::COLOR ||
+               (surf->GetContentType() == gfxContentType::COLOR_ALPHA &&
                (mNativeDrawFlags & CAN_DRAW_TO_COLOR_ALPHA)))))
         {
             // grab the DC. This can fail if there is a complex clipping path,
             // in which case we'll have to fall back.
             mWinSurface = static_cast<gfxWindowsSurface*>(static_cast<gfxASurface*>(surf.get()));
             mDC = mWinSurface->GetDCWithClip(mContext);
 
             if (mDC) {
@@ -187,22 +187,22 @@ gfxWindowsNativeDrawing::IsDoublePass()
         (mContext->GetDrawTarget()->GetType() != mozilla::gfx::BackendType::CAIRO ||
          mContext->GetDrawTarget()->IsDualDrawTarget())) {
       return true;
     }
 
     nsRefPtr<gfxASurface> surf = mContext->CurrentSurface(&mDeviceOffset.x, &mDeviceOffset.y);
     if (!surf || surf->CairoStatus())
         return false;
-    if (surf->GetType() != gfxSurfaceTypeWin32 &&
-        surf->GetType() != gfxSurfaceTypeWin32Printing) {
+    if (surf->GetType() != gfxSurfaceType::Win32 &&
+        surf->GetType() != gfxSurfaceType::Win32Printing) {
 	return true;
     }
-    if ((surf->GetContentType() != GFX_CONTENT_COLOR ||
-         (surf->GetContentType() == GFX_CONTENT_COLOR_ALPHA &&
+    if ((surf->GetContentType() != gfxContentType::COLOR ||
+         (surf->GetContentType() == gfxContentType::COLOR_ALPHA &&
           !(mNativeDrawFlags & CAN_DRAW_TO_COLOR_ALPHA))))
         return true;
     return false;
 }
 
 bool
 gfxWindowsNativeDrawing::ShouldRenderAgain()
 {
@@ -264,17 +264,17 @@ gfxWindowsNativeDrawing::PaintToContext(
         nsRefPtr<gfxImageSurface> white = mWhiteSurface->GetAsImageSurface();
         if (!gfxAlphaRecovery::RecoverAlpha(black, white)) {
             NS_ERROR("Alpha recovery failure");
             return;
         }
         nsRefPtr<gfxImageSurface> alphaSurface =
             new gfxImageSurface(black->Data(), black->GetSize(),
                                 black->Stride(),
-                                gfxImageFormatARGB32);
+                                gfxImageFormat::ARGB32);
 
         mContext->Save();
         mContext->Translate(mNativeRect.TopLeft());
         mContext->NewPath();
         mContext->Rectangle(gfxRect(gfxPoint(0.0, 0.0), mNativeRect.Size()));
 
         nsRefPtr<gfxPattern> pat = new gfxPattern(alphaSurface);
 
--- a/gfx/thebes/gfxWindowsPlatform.h
+++ b/gfx/thebes/gfxWindowsPlatform.h
@@ -57,18 +57,18 @@ class nsIMemoryReporter;
 // Utility to get a Windows HDC from a thebes context,
 // used by both GDI and Uniscribe font shapers
 struct DCFromContext {
     DCFromContext(gfxContext *aContext) {
         dc = nullptr;
         nsRefPtr<gfxASurface> aSurface = aContext->CurrentSurface();
         NS_ASSERTION(aSurface || !aContext->IsCairo(), "DCFromContext: null surface");
         if (aSurface &&
-            (aSurface->GetType() == gfxSurfaceTypeWin32 ||
-             aSurface->GetType() == gfxSurfaceTypeWin32Printing))
+            (aSurface->GetType() == gfxSurfaceType::Win32 ||
+             aSurface->GetType() == gfxSurfaceType::Win32Printing))
         {
             dc = static_cast<gfxWindowsSurface*>(aSurface.get())->GetDC();
             needsRelease = false;
             SaveDC(dc);
             cairo_scaled_font_t* scaled =
                 cairo_get_scaled_font(aContext->GetCairo());
             cairo_win32_scaled_font_select_font(scaled, dc);
         }
--- a/gfx/thebes/gfxWindowsSurface.cpp
+++ b/gfx/thebes/gfxWindowsSurface.cpp
@@ -50,17 +50,17 @@ gfxWindowsSurface::MakeInvalid(gfxIntSiz
 
 gfxWindowsSurface::gfxWindowsSurface(const gfxIntSize& realSize, gfxImageFormat imageFormat) :
     mOwnsDC(false), mForPrinting(false), mWnd(nullptr)
 {
     gfxIntSize size(realSize);
     if (!CheckSurfaceSize(size))
         MakeInvalid(size);
 
-    cairo_surface_t *surf = cairo_win32_surface_create_with_dib((cairo_format_t)imageFormat,
+    cairo_surface_t *surf = cairo_win32_surface_create_with_dib((cairo_format_t)(int)imageFormat,
                                                                 size.width, size.height);
 
     Init(surf);
 
     if (CairoStatus() == CAIRO_STATUS_SUCCESS) {
         mDC = cairo_win32_surface_get_dc(CairoSurface());
         RecordMemoryUsed(size.width * size.height * 4 + sizeof(gfxWindowsSurface));
     } else {
@@ -70,24 +70,24 @@ gfxWindowsSurface::gfxWindowsSurface(con
 
 gfxWindowsSurface::gfxWindowsSurface(HDC dc, const gfxIntSize& realSize, gfxImageFormat imageFormat) :
     mOwnsDC(false), mForPrinting(false), mWnd(nullptr)
 {
     gfxIntSize size(realSize);
     if (!CheckSurfaceSize(size))
         MakeInvalid(size);
 
-    cairo_surface_t *surf = cairo_win32_surface_create_with_ddb(dc, (cairo_format_t)imageFormat,
+    cairo_surface_t *surf = cairo_win32_surface_create_with_ddb(dc, (cairo_format_t)(int)imageFormat,
                                                                 size.width, size.height);
 
     Init(surf);
 
     if (mSurfaceValid) {
         // DDBs will generally only use 3 bytes per pixel when RGB24
-        int bytesPerPixel = ((imageFormat == gfxImageFormatRGB24) ? 3 : 4);
+        int bytesPerPixel = ((imageFormat == gfxImageFormat::RGB24) ? 3 : 4);
         RecordMemoryUsed(size.width * size.height * bytesPerPixel + sizeof(gfxWindowsSurface));
     }
 
     if (CairoStatus() == 0)
         mDC = cairo_win32_surface_get_dc(CairoSurface());
     else
         mDC = nullptr;
 }
@@ -120,31 +120,31 @@ already_AddRefed<gfxASurface>
 gfxWindowsSurface::CreateSimilarSurface(gfxContentType aContent,
                                         const gfxIntSize& aSize)
 {
     if (!mSurface || !mSurfaceValid) {
         return nullptr;
     }
 
     cairo_surface_t *surface;
-    if (!mForPrinting && GetContentType() == GFX_CONTENT_COLOR_ALPHA) {
+    if (!mForPrinting && GetContentType() == gfxContentType::COLOR_ALPHA) {
         // When creating a similar surface to a transparent surface, ensure
         // the new surface uses a DIB. cairo_surface_create_similar won't
-        // use  a DIB for a GFX_CONTENT_COLOR surface if this surface doesn't
+        // use  a DIB for a gfxContentType::COLOR surface if this surface doesn't
         // have a DIB (e.g. if we're a transparent window surface). But
         // we need a DIB to perform well if the new surface is composited into
-        // a surface that's the result of create_similar(GFX_CONTENT_COLOR_ALPHA)
+        // a surface that's the result of create_similar(gfxContentType::COLOR_ALPHA)
         // (e.g. a backbuffer for the window) --- that new surface *would*
         // have a DIB.
         surface =
-          cairo_win32_surface_create_with_dib(cairo_format_t(gfxPlatform::GetPlatform()->OptimalFormatForContent(aContent)),
+          cairo_win32_surface_create_with_dib((cairo_format_t)(int)gfxPlatform::GetPlatform()->OptimalFormatForContent(aContent),
                                               aSize.width, aSize.height);
     } else {
         surface =
-          cairo_surface_create_similar(mSurface, cairo_content_t(aContent),
+          cairo_surface_create_similar(mSurface, (cairo_content_t)(int)aContent,
                                        aSize.width, aSize.height);
     }
 
     if (cairo_surface_status(surface)) {
         cairo_surface_destroy(surface);
         return nullptr;
     }
 
@@ -306,10 +306,10 @@ gfxWindowsSurface::GetSize() const
 
     return gfxIntSize(cairo_win32_surface_get_width(mSurface),
                       cairo_win32_surface_get_height(mSurface));
 }
 
 gfxMemoryLocation
 gfxWindowsSurface::GetMemoryLocation() const
 {
-    return GFX_MEMORY_IN_PROCESS_NONHEAP;
+    return gfxMemoryLocation::IN_PROCESS_NONHEAP;
 }
--- a/gfx/thebes/gfxWindowsSurface.h
+++ b/gfx/thebes/gfxWindowsSurface.h
@@ -30,22 +30,22 @@ public:
     gfxWindowsSurface(HWND wnd, uint32_t flags = 0);
     gfxWindowsSurface(HDC dc, uint32_t flags = 0);
 
     // Create from a shared d3d9surface
     gfxWindowsSurface(IDirect3DSurface9 *surface, uint32_t flags = 0);
 
     // Create a DIB surface
     gfxWindowsSurface(const gfxIntSize& size,
-                      gfxImageFormat imageFormat = gfxImageFormatRGB24);
+                      gfxImageFormat imageFormat = gfxImageFormat::RGB24);
 
     // Create a DDB surface; dc may be nullptr to use the screen DC
     gfxWindowsSurface(HDC dc,
                       const gfxIntSize& size,
-                      gfxImageFormat imageFormat = gfxImageFormatRGB24);
+                      gfxImageFormat imageFormat = gfxImageFormat::RGB24);
 
     gfxWindowsSurface(cairo_surface_t *csurf);
 
     virtual already_AddRefed<gfxASurface> CreateSimilarSurface(gfxContentType aType,
                                                                const gfxIntSize& aSize);
 
     void InitWithDC(uint32_t flags);
 
--- a/gfx/thebes/gfxXlibNativeRenderer.cpp
+++ b/gfx/thebes/gfxXlibNativeRenderer.cpp
@@ -388,27 +388,27 @@ CreateTempXlibSurface (cairo_surface_t* 
     if (supportsAlternateVisual && !drawIsOpaque &&
         (screen != target_screen ||
          !(doCopyBackground || VisualHasAlpha(screen, visual)))) {
         // Try to find a visual with an alpha channel.
         Screen *visualScreen =
             supportsAlternateScreen ? target_screen : screen;
         Visual *argbVisual =
             gfxXlibSurface::FindVisual(visualScreen,
-                                       gfxImageFormatARGB32);
+                                       gfxImageFormat::ARGB32);
         if (argbVisual) {
             visual = argbVisual;
             screen = visualScreen;
         } else if (!doCopyBackground &&
                    gfxXlibSurface::DepthOfVisual(screen, visual) != 24) {
             // Will need to do alpha extraction; prefer a 24-bit visual.
             // No advantage in using the target screen.
             Visual *rgb24Visual =
                 gfxXlibSurface::FindVisual(screen,
-                                           gfxImageFormatRGB24);
+                                           gfxImageFormat::RGB24);
             if (rgb24Visual) {
                 visual = rgb24Visual;
             }
         }
     }
 
     Drawable drawable =
         (screen == target_screen && cairoTargetType == CAIRO_SURFACE_TYPE_XLIB) ?
@@ -597,26 +597,26 @@ gfxXlibNativeRenderer::Draw(gfxContext* 
             ctx->SetSource(tmpSurf, offset);
             ctx->Paint();
         }
         cairo_surface_destroy(tempXlibSurface);
         return;
     }
     
     nsRefPtr<gfxImageSurface> blackImage =
-        CopyXlibSurfaceToImage(tempXlibSurface, size, gfxImageFormatARGB32);
+        CopyXlibSurfaceToImage(tempXlibSurface, size, gfxImageFormat::ARGB32);
     
     cairo_t* tmpCtx = cairo_create(tempXlibSurface);
     cairo_set_source_rgba(tmpCtx, 1.0, 1.0, 1.0, 1.0);
     cairo_set_operator(tmpCtx, CAIRO_OPERATOR_SOURCE);
     cairo_paint(tmpCtx);
     cairo_destroy(tmpCtx);
     DrawOntoTempSurface(tempXlibSurface, -drawingRect.TopLeft());
     nsRefPtr<gfxImageSurface> whiteImage =
-        CopyXlibSurfaceToImage(tempXlibSurface, size, gfxImageFormatRGB24);
+        CopyXlibSurfaceToImage(tempXlibSurface, size, gfxImageFormat::RGB24);
   
     if (blackImage->CairoStatus() == CAIRO_STATUS_SUCCESS &&
         whiteImage->CairoStatus() == CAIRO_STATUS_SUCCESS) {
         if (!gfxAlphaRecovery::RecoverAlpha(blackImage, whiteImage)) {
             cairo_surface_destroy(tempXlibSurface);
             return;
         }
 
--- a/gfx/thebes/gfxXlibSurface.cpp
+++ b/gfx/thebes/gfxXlibSurface.cpp
@@ -239,17 +239,17 @@ static bool GetForce24bppPref()
 already_AddRefed<gfxASurface>
 gfxXlibSurface::CreateSimilarSurface(gfxContentType aContent,
                                      const gfxIntSize& aSize)
 {
     if (!mSurface || !mSurfaceValid) {
       return nullptr;
     }
 
-    if (aContent == GFX_CONTENT_COLOR) {
+    if (aContent == gfxContentType::COLOR) {
         // cairo_surface_create_similar will use a matching visual if it can.
         // However, systems with 16-bit or indexed default visuals may benefit
         // from rendering with 24-bit formats.
         static bool force24bpp = GetForce24bppPref();
         if (force24bpp
             && cairo_xlib_surface_get_depth(CairoSurface()) != 24) {
             XRenderPictFormat* format =
                 XRenderFindStandardFormat(mDisplay, PictStandardRGB24);
@@ -496,36 +496,36 @@ gfxXlibSurface::DepthOfVisual(const Scre
     
 /* static */
 Visual*
 gfxXlibSurface::FindVisual(Screen *screen, gfxImageFormat format)
 {
     int depth;
     unsigned long red_mask, green_mask, blue_mask;
     switch (format) {
-        case gfxImageFormatARGB32:
+        case gfxImageFormat::ARGB32:
             depth = 32;
             red_mask = 0xff0000;
             green_mask = 0xff00;
             blue_mask = 0xff;
             break;
-        case gfxImageFormatRGB24:
+        case gfxImageFormat::RGB24:
             depth = 24;
             red_mask = 0xff0000;
             green_mask = 0xff00;
             blue_mask = 0xff;
             break;
-        case gfxImageFormatRGB16_565:
+        case gfxImageFormat::RGB16_565:
             depth = 16;
             red_mask = 0xf800;
             green_mask = 0x7e0;
             blue_mask = 0x1f;
             break;
-        case gfxImageFormatA8:
-        case gfxImageFormatA1:
+        case gfxImageFormat::A8:
+        case gfxImageFormat::A1:
         default:
             return nullptr;
     }
 
     for (int d = 0; d < screen->ndepths; d++) {
         const Depth& d_info = screen->depths[d];
         if (d_info.depth != depth)
             continue;
@@ -544,32 +544,32 @@ gfxXlibSurface::FindVisual(Screen *scree
     return nullptr;
 }
 
 /* static */
 XRenderPictFormat*
 gfxXlibSurface::FindRenderFormat(Display *dpy, gfxImageFormat format)
 {
     switch (format) {
-        case gfxImageFormatARGB32:
+        case gfxImageFormat::ARGB32:
             return XRenderFindStandardFormat (dpy, PictStandardARGB32);
-        case gfxImageFormatRGB24:
+        case gfxImageFormat::RGB24:
             return XRenderFindStandardFormat (dpy, PictStandardRGB24);
-        case gfxImageFormatRGB16_565: {
+        case gfxImageFormat::RGB16_565: {
             // PictStandardRGB16_565 is not standard Xrender format
             // we should try to find related visual
             // and find xrender format by visual
             Visual *visual = FindVisual(DefaultScreenOfDisplay(dpy), format);
             if (!visual)
                 return nullptr;
             return XRenderFindVisualFormat(dpy, visual);
         }
-        case gfxImageFormatA8:
+        case gfxImageFormat::A8:
             return XRenderFindStandardFormat (dpy, PictStandardA8);
-        case gfxImageFormatA1:
+        case gfxImageFormat::A1:
             return XRenderFindStandardFormat (dpy, PictStandardA1);
         default:
             break;
     }
 
     return nullptr;
 }
 
@@ -602,10 +602,10 @@ gfxXlibSurface::GetGLXPixmap()
     }
     return mGLXPixmap;
 }
 #endif
 
 gfxMemoryLocation
 gfxXlibSurface::GetMemoryLocation() const
 {
-    return GFX_MEMORY_OUT_OF_PROCESS;
+    return gfxMemoryLocation::OUT_OF_PROCESS;
 }
--- a/gfx/ycbcr/YCbCrUtils.cpp
+++ b/gfx/ycbcr/YCbCrUtils.cpp
@@ -130,17 +130,17 @@ ConvertYCbCrToRGB(const layers::PlanarYC
                            aData.mPicX,
                            aData.mPicY,
                            aData.mPicSize.width,
                            aData.mPicSize.height,
                            aData.mYStride,
                            aData.mCbCrStride,
                            aStride,
                            yuvtype);
-    } else // aDestFormat != gfxImageFormatRGB16_565
+    } else // aDestFormat != gfxImageFormat::RGB16_565
 #endif
       ConvertYCbCrToRGB32(aData.mYChannel, //
                           aData.mCbChannel,
                           aData.mCrChannel,
                           aDestBuffer,
                           aData.mPicX,
                           aData.mPicY,
                           aData.mPicSize.width,
--- a/image/decoders/nsGIFDecoder2.cpp
+++ b/image/decoders/nsGIFDecoder2.cpp
@@ -156,19 +156,19 @@ void nsGIFDecoder2::BeginGIF()
   PostSize(mGIFStruct.screen_width, mGIFStruct.screen_height);
 }
 
 //******************************************************************************
 void nsGIFDecoder2::BeginImageFrame(uint16_t aDepth)
 {
   gfxImageFormat format;
   if (mGIFStruct.is_transparent)
-    format = gfxImageFormatARGB32;
+    format = gfxImageFormat::ARGB32;
   else
-    format = gfxImageFormatRGB24;
+    format = gfxImageFormat::RGB24;
 
   MOZ_ASSERT(HasSize());
 
   // Use correct format, RGB for first frame, PAL for following frames
   // and include transparency to allow for optimization of opaque images
   if (mGIFStruct.images_decoded) {
     // Image data is stored with original depth and palette
     NeedNewFrame(mGIFStruct.images_decoded, mGIFStruct.x_offset,
@@ -183,17 +183,17 @@ void nsGIFDecoder2::BeginImageFrame(uint
                                                                 mGIFStruct.width,
                                                                 mGIFStruct.height))) {
     // Regardless of depth of input, image is decoded into 24bit RGB
     NeedNewFrame(mGIFStruct.images_decoded, mGIFStruct.x_offset,
                  mGIFStruct.y_offset, mGIFStruct.width, mGIFStruct.height,
                  format);
   } else {
     // Our preallocated frame matches up, with the possible exception of alpha.
-    if (format == gfxImageFormatRGB24) {
+    if (format == gfxImageFormat::RGB24) {
       GetCurrentFrame()->SetHasNoAlpha();
     }
   }
 
   mCurrentFrame = mGIFStruct.images_decoded;
 }
 
 
--- a/image/decoders/nsPNGDecoder.cpp
+++ b/image/decoders/nsPNGDecoder.cpp
@@ -143,17 +143,17 @@ void nsPNGDecoder::CreateFrame(png_uint_
   // Our first full frame is automatically created by the image decoding
   // infrastructure. Just use it as long as it matches up.
   MOZ_ASSERT(HasSize());
   if (mNumFrames != 0 ||
       !GetCurrentFrame()->GetRect().IsEqualEdges(nsIntRect(x_offset, y_offset, width, height))) {
     NeedNewFrame(mNumFrames, x_offset, y_offset, width, height, format);
   } else if (mNumFrames == 0) {
     // Our preallocated frame matches up, with the possible exception of alpha.
-    if (format == gfxImageFormatRGB24) {
+    if (format == gfxImageFormat::RGB24) {
       GetCurrentFrame()->SetHasNoAlpha();
     }
   }
 
   mFrameRect.x = x_offset;
   mFrameRect.y = y_offset;
   mFrameRect.width = width;
   mFrameRect.height = height;
@@ -622,19 +622,19 @@ nsPNGDecoder::info_callback(png_structp 
       }
     } else {
       alpha_bits = 8;
     }
   }
 #endif
 
   if (channels == 1 || channels == 3)
-    decoder->format = gfxImageFormatRGB24;
+    decoder->format = gfxImageFormat::RGB24;
   else if (channels == 2 || channels == 4)
-    decoder->format = gfxImageFormatARGB32;
+    decoder->format = gfxImageFormat::ARGB32;
 
 #ifdef PNG_APNG_SUPPORTED
   if (png_get_valid(png_ptr, info_ptr, PNG_INFO_acTL))
     png_set_progressive_frame_fn(png_ptr, nsPNGDecoder::frame_info_callback,
                                  nullptr);
 
   if (png_get_first_frame_is_hidden(png_ptr, info_ptr)) {
     decoder->mFrameIsHidden = true;
@@ -738,17 +738,17 @@ nsPNGDecoder::row_callback(png_structp p
         }
         line = decoder->mCMSLine;
       } else {
         qcms_transform_data(decoder->mTransform, line, line, iwidth);
        }
      }
 
     switch (decoder->format) {
-      case gfxImageFormatRGB24:
+      case gfxImageFormat::RGB24:
       {
         // counter for while() loops below
         uint32_t idx = iwidth;
 
         // copy as bytes until source pointer is 32-bit-aligned
         for (; (NS_PTR_TO_UINT32(line) & 0x3) && idx; --idx) {
           *cptr32++ = gfxPackedPixel(0xFF, line[0], line[1], line[2]);
           line += 3;
@@ -765,17 +765,17 @@ nsPNGDecoder::row_callback(png_structp p
         // copy remaining pixel(s)
         while (idx--) {
           // 32-bit read of final pixel will exceed buffer, so read bytes
           *cptr32++ = gfxPackedPixel(0xFF, line[0], line[1], line[2]);
           line += 3;
         }
       }
       break;
-      case gfxImageFormatARGB32:
+      case gfxImageFormat::ARGB32:
       {
         if (!decoder->mDisablePremultipliedAlpha) {
           for (uint32_t x=width; x>0; --x) {
             *cptr32++ = gfxPackedPixel(line[3], line[0], line[1], line[2]);
             if (line[3] != 0xff)
               rowHasNoAlpha = false;
             line += 4;
           }
--- a/image/src/ClippedImage.cpp
+++ b/image/src/ClippedImage.cpp
@@ -254,17 +254,17 @@ ClippedImage::GetFrameInternal(const nsI
       new DrawSingleTileCallback(this, mClip, aViewportSize, aSVGContext, aWhichFrame, aFlags);
     nsRefPtr<gfxDrawable> drawable =
       new gfxCallbackDrawable(drawTileCallback, mClip.Size());
 
     // Actually draw. The callback will end up invoking DrawSingleTile.
     gfxRect imageRect(0, 0, mClip.width, mClip.height);
     gfxUtils::DrawPixelSnapped(ctx, drawable, gfxMatrix(),
                                imageRect, imageRect, imageRect, imageRect,
-                               gfxImageFormatARGB32,
+                               gfxImageFormat::ARGB32,
                                GraphicsFilter::FILTER_FAST);
 
     // Cache the resulting surface.
     mCachedSurface = new ClippedImageCachedSurface(target,
                                                    aViewportSize,
                                                    aSVGContext,
                                                    frameToDraw,
                                                    aFlags);
@@ -339,17 +339,17 @@ ClippedImage::Draw(gfxContext* aContext,
     nsRefPtr<gfxSurfaceDrawable> drawable =
       new gfxSurfaceDrawable(surface, gfxIntSize(mClip.width, mClip.height));
 
     // Draw.
     gfxRect imageRect(0, 0, mClip.width, mClip.height);
     gfxRect subimage(aSubimage.x, aSubimage.y, aSubimage.width, aSubimage.height);
     gfxUtils::DrawPixelSnapped(aContext, drawable, aUserSpaceToImageSpace,
                                subimage, sourceRect, imageRect, aFill,
-                               gfxImageFormatARGB32, aFilter);
+                               gfxImageFormat::ARGB32, aFilter);
 
     return NS_OK;
   }
 
   // Determine the appropriate subimage for the inner image.
   nsIntRect innerSubimage(aSubimage);
   innerSubimage.MoveBy(mClip.x, mClip.y);
   innerSubimage.Intersect(mClip);
--- a/image/src/FrameBlender.cpp
+++ b/image/src/FrameBlender.cpp
@@ -256,17 +256,17 @@ FrameBlender::DoBlend(nsIntRect* aDirtyR
   }
 
   bool needToBlankComposite = false;
 
   // Create the Compositing Frame
   if (!mAnim->compositingFrame) {
     mAnim->compositingFrame.SetFrame(new imgFrame());
     nsresult rv = mAnim->compositingFrame->Init(0, 0, mSize.width, mSize.height,
-                                                gfxImageFormatARGB32);
+                                                gfxImageFormat::ARGB32);
     if (NS_FAILED(rv)) {
       mAnim->compositingFrame.SetFrame(nullptr);
       return false;
     }
     mAnim->compositingFrame.LockAndGetData();
     needToBlankComposite = true;
   } else if (int32_t(aNextFrameIndex) != mAnim->lastCompositedFrameIndex+1) {
 
@@ -386,17 +386,17 @@ FrameBlender::DoBlend(nsIntRect* aDirtyR
   if ((nextFrameDisposalMethod == FrameBlender::kDisposeRestorePrevious) &&
       (prevFrameDisposalMethod != FrameBlender::kDisposeRestorePrevious)) {
     // We are storing the whole image.
     // It would be better if we just stored the area that nextFrame is going to
     // overwrite.
     if (!mAnim->compositingPrevFrame) {
       mAnim->compositingPrevFrame.SetFrame(new imgFrame());
       nsresult rv = mAnim->compositingPrevFrame->Init(0, 0, mSize.width, mSize.height,
-                                                      gfxImageFormatARGB32);
+                                                      gfxImageFormat::ARGB32);
       if (NS_FAILED(rv)) {
         mAnim->compositingPrevFrame.SetFrame(nullptr);
         return false;
       }
 
       mAnim->compositingPrevFrame.LockAndGetData();
     }
 
--- a/image/src/OrientedImage.cpp
+++ b/image/src/OrientedImage.cpp
@@ -96,20 +96,20 @@ OrientedImage::GetFrame(uint32_t aWhichF
   }
   NS_ENSURE_SUCCESS(rv, nullptr);
 
   // Determine an appropriate format for the surface.
   gfx::SurfaceFormat surfaceFormat;
   gfxImageFormat imageFormat;
   if (InnerImage()->FrameIsOpaque(aWhichFrame)) {
     surfaceFormat = gfx::SurfaceFormat::B8G8R8X8;
-    imageFormat = gfxImageFormatARGB32;
+    imageFormat = gfxImageFormat::ARGB32;
   } else {
     surfaceFormat = gfx::SurfaceFormat::B8G8R8A8;
-    imageFormat = gfxImageFormatARGB32;
+    imageFormat = gfxImageFormat::ARGB32;
   }
 
   // Create a surface to draw into.
   mozilla::RefPtr<mozilla::gfx::DrawTarget> target;
   target = gfxPlatform::GetPlatform()->
     CreateOffscreenContentDrawTarget(gfx::IntSize(width, height), surfaceFormat);
 
   // Create our drawable.
--- a/image/src/RasterImage.cpp
+++ b/image/src/RasterImage.cpp
@@ -321,17 +321,17 @@ public:
   ScaleRunner(RasterImage* aImage, const gfx::Size& aScale, imgFrame* aSrcFrame)
   {
     nsAutoPtr<ScaleRequest> request(new ScaleRequest(aImage, aScale, aSrcFrame));
 
     // Destination is unconditionally ARGB32 because that's what the scaler
     // outputs.
     request->dstFrame = new imgFrame();
     nsresult rv = request->dstFrame->Init(0, 0, request->dstSize.width, request->dstSize.height,
-                                          gfxImageFormatARGB32);
+                                          gfxImageFormat::ARGB32);
 
     if (NS_FAILED(rv) || !request->GetSurfaces(aSrcFrame)) {
       return;
     }
 
     aImage->ScalingStart(request);
 
     mScaleRequest = request;
@@ -859,17 +859,17 @@ RasterImage::CopyFrame(uint32_t aWhichFr
   nsRefPtr<gfxPattern> pattern;
   frame->GetPattern(getter_AddRefs(pattern));
   nsIntRect intframerect = frame->GetRect();
   gfxRect framerect(intframerect.x, intframerect.y, intframerect.width, intframerect.height);
 
   // Create a 32-bit image surface of our size, but draw using the frame's
   // rect, implicitly padding the frame out to the image's size.
   nsRefPtr<gfxImageSurface> imgsurface = new gfxImageSurface(gfxIntSize(mSize.width, mSize.height),
-                                                             gfxImageFormatARGB32);
+                                                             gfxImageFormat::ARGB32);
   gfxContext ctx(imgsurface);
   ctx.SetOperator(gfxContext::OPERATOR_SOURCE);
   ctx.Rectangle(framerect);
   ctx.Translate(framerect.TopLeft());
   ctx.SetPattern(pattern);
   ctx.Fill();
 
   *_retval = imgsurface.forget().get();
@@ -1041,31 +1041,31 @@ RasterImage::SizeOfDecodedWithComputedFa
   }
 
   return n;
 }
 
 size_t
 RasterImage::HeapSizeOfDecodedWithComputedFallback(MallocSizeOf aMallocSizeOf) const
 {
-  return SizeOfDecodedWithComputedFallbackIfHeap(GFX_MEMORY_IN_PROCESS_HEAP,
+  return SizeOfDecodedWithComputedFallbackIfHeap(gfxMemoryLocation::IN_PROCESS_HEAP,
                                                  aMallocSizeOf);
 }
 
 size_t
 RasterImage::NonHeapSizeOfDecoded() const
 {
-  return SizeOfDecodedWithComputedFallbackIfHeap(GFX_MEMORY_IN_PROCESS_NONHEAP,
+  return SizeOfDecodedWithComputedFallbackIfHeap(gfxMemoryLocation::IN_PROCESS_NONHEAP,
                                                  nullptr);
 }
 
 size_t
 RasterImage::OutOfProcessSizeOfDecoded() const
 {
-  return SizeOfDecodedWithComputedFallbackIfHeap(GFX_MEMORY_OUT_OF_PROCESS,
+  return SizeOfDecodedWithComputedFallbackIfHeap(gfxMemoryLocation::OUT_OF_PROCESS,
                                                  nullptr);
 }
 
 void
 RasterImage::EnsureAnimExists()
 {
   if (!mAnim) {
 
@@ -2029,17 +2029,17 @@ RasterImage::InitDecoder(bool aDoSizeDec
   mDecoder->SetObserver(mDecodeRequest->mStatusTracker->GetDecoderObserver());
   mDecoder->SetSizeDecode(aDoSizeDecode);
   mDecoder->SetDecodeFlags(mFrameDecodeFlags);
   if (!aDoSizeDecode) {
     // We already have the size; tell the decoder so it can preallocate a
     // frame.  By default, we create an ARGB frame with no offset. If decoders
     // need a different type, they need to ask for it themselves.
     mDecoder->NeedNewFrame(0, 0, 0, mSize.width, mSize.height,
-                           gfxImageFormatARGB32);
+                           gfxImageFormat::ARGB32);
     mDecoder->AllocateFrame();
   }
   mDecoder->Init();
   CONTAINER_ENSURE_SUCCESS(mDecoder->GetDecoderError());
 
   if (!aDoSizeDecode) {
     Telemetry::GetHistogramById(Telemetry::IMAGE_DECODE_COUNT)->Subtract(mDecodeCount);
     mDecodeCount++;
--- a/image/src/VectorImage.cpp
+++ b/image/src/VectorImage.cpp
@@ -672,17 +672,17 @@ VectorImage::GetFrame(uint32_t aWhichFra
 
   // Create a surface that we'll ultimately return
   // ---------------------------------------------
   // Make our surface the size of what will ultimately be drawn to it.
   // (either the full image size, or the restricted region)
   gfxIntSize surfaceSize(imageIntSize.width, imageIntSize.height);
 
   nsRefPtr<gfxImageSurface> surface =
-    new gfxImageSurface(surfaceSize, gfxImageFormatARGB32);
+    new gfxImageSurface(surfaceSize, gfxImageFormat::ARGB32);
   nsRefPtr<gfxContext> context = new gfxContext(surface);
 
   // Draw to our surface!
   // --------------------
   nsresult rv = Draw(context, GraphicsFilter::FILTER_NEAREST, gfxMatrix(),
                      gfxRect(gfxPoint(0,0), gfxIntSize(imageIntSize.width,
                                                        imageIntSize.height)),
                      nsIntRect(nsIntPoint(0,0), imageIntSize),
@@ -860,17 +860,17 @@ VectorImage::CreateDrawableAndShow(const
     return Show(svgDrawable, aParams);
 
   nsRefPtr<gfxContext> ctx = new gfxContext(target);
 
   // Actually draw. (We use FILTER_NEAREST since we never scale here.)
   gfxUtils::DrawPixelSnapped(ctx, svgDrawable, gfxMatrix(),
                              aParams.imageRect, aParams.imageRect,
                              aParams.imageRect, aParams.imageRect,
-                             gfxImageFormatARGB32,
+                             gfxImageFormat::ARGB32,
                              GraphicsFilter::FILTER_NEAREST, aParams.flags);
 
   // Attempt to cache the resulting surface.
   SurfaceCache::Insert(target,
                        ImageKey(this),
                        SurfaceKey(aParams.imageRect.Size(), aParams.scale,
                                   aParams.svgContext, aParams.animationTime,
                                   aParams.flags));
@@ -886,17 +886,17 @@ VectorImage::CreateDrawableAndShow(const
 void
 VectorImage::Show(gfxDrawable* aDrawable, const SVGDrawingParameters& aParams)
 {
   MOZ_ASSERT(aDrawable, "Should have a gfxDrawable by now");
   gfxUtils::DrawPixelSnapped(aParams.context, aDrawable,
                              aParams.userSpaceToImageSpace,
                              aParams.subimage, aParams.sourceRect,
                              aParams.imageRect, aParams.fill,
-                             gfxImageFormatARGB32,
+                             gfxImageFormat::ARGB32,
                              aParams.filter, aParams.flags);
 
   MOZ_ASSERT(mRenderingObserver, "Should have a rendering observer by now");
   mRenderingObserver->ResumeHonoringInvalidations();
 }
 
 //******************************************************************************
 /* void requestDecode() */
--- a/image/src/imgFrame.cpp
+++ b/image/src/imgFrame.cpp
@@ -231,22 +231,22 @@ nsresult imgFrame::Optimize()
     uint32_t firstPixel = * (uint32_t*) imgData;
     uint32_t pixelCount = mSize.width * mSize.height + 1;
 
     while (--pixelCount && *imgData++ == firstPixel)
       ;
 
     if (pixelCount == 0) {
       // all pixels were the same
-      if (mFormat == gfxImageFormatARGB32 ||
-          mFormat == gfxImageFormatRGB24)
+      if (mFormat == gfxImageFormat::ARGB32 ||
+          mFormat == gfxImageFormat::RGB24)
       {
         // Should already be premult if desired.
         gfxRGBA::PackedColorType inputType = gfxRGBA::PACKED_XRGB;
-        if (mFormat == gfxImageFormatARGB32)
+        if (mFormat == gfxImageFormat::ARGB32)
           inputType = gfxRGBA::PACKED_ARGB_PREMULTIPLIED;
 
         mSinglePixelColor = gfxRGBA(firstPixel, inputType);
 
         mSinglePixel = true;
 
         // blow away the older surfaces (if they exist), to release their memory
         mImageSurface = nullptr;
@@ -351,17 +351,17 @@ imgFrame::SurfaceForDrawing(bool        
   }
 
   gfxRect available = gfxRect(mDecoded.x, mDecoded.y, mDecoded.width, mDecoded.height);
 
   if (aDoTile || mSinglePixel) {
     // Create a temporary surface.
     // Give this surface an alpha channel because there are
     // transparent pixels in the padding or undecoded area
-    gfxImageFormat format = gfxImageFormatARGB32;
+    gfxImageFormat format = gfxImageFormat::ARGB32;
     nsRefPtr<gfxASurface> surface =
       gfxPlatform::GetPlatform()->CreateOffscreenSurface(size, gfxImageSurface::ContentFromFormat(format));
     if (!surface || surface->CairoStatus())
       return SurfaceWithFormat();
 
     // Fill 'available' with whatever we've got
     gfxContext tmpCtx(surface);
     tmpCtx.SetOperator(gfxContext::OPERATOR_SOURCE);
@@ -469,17 +469,17 @@ nsIntRect imgFrame::GetRect() const
 gfxImageFormat imgFrame::GetFormat() const
 {
   return mFormat;
 }
 
 bool imgFrame::GetNeedsBackground() const
 {
   // We need a background painted if we have alpha or we're incomplete.
-  return (mFormat == gfxImageFormatARGB32 || !ImageComplete());
+  return (mFormat == gfxImageFormat::ARGB32 || !ImageComplete());
 }
 
 uint32_t imgFrame::GetImageBytesPerRow() const
 {
   if (mImageSurface)
     return mImageSurface->Stride();
 
   if (mPaletteDepth)
@@ -519,17 +519,17 @@ uint8_t* imgFrame::GetImageData() const
 
 bool imgFrame::GetIsPaletted() const
 {
   return mPalettedImageData != nullptr;
 }
 
 bool imgFrame::GetHasAlpha() const
 {
-  return mFormat == gfxImageFormatARGB32;
+  return mFormat == gfxImageFormat::ARGB32;
 }
 
 void imgFrame::GetPaletteData(uint32_t **aPalette, uint32_t *length) const
 {
   NS_ABORT_IF_FALSE(mLockCount != 0, "Can't GetPaletteData unless frame is locked");
 
   if (!mPalettedImageData) {
     *aPalette = nullptr;
@@ -566,17 +566,17 @@ nsresult imgFrame::LockImageData()
 
   // Paletted images don't have surfaces, so there's nothing to do.
   if (mPalettedImageData)
     return NS_OK;
 
   if ((mOptSurface || mSinglePixel) && !mImageSurface) {
     // Recover the pixels
     mImageSurface = new gfxImageSurface(gfxIntSize(mSize.width, mSize.height),
-                                        gfxImageFormatARGB32);
+                                        gfxImageFormat::ARGB32);
     if (!mImageSurface || mImageSurface->CairoStatus())
       return NS_ERROR_OUT_OF_MEMORY;
 
     gfxContext context(mImageSurface);
     context.SetOperator(gfxContext::OPERATOR_SOURCE);
     if (mSinglePixel)
       context.SetDeviceColor(mSinglePixelColor);
     else
@@ -737,18 +737,18 @@ bool imgFrame::ImageComplete() const
 // A hint from the image decoders that this image has no alpha, even
 // though we created is ARGB32.  This changes our format to RGB24,
 // which in turn will cause us to Optimize() to RGB24.  Has no effect
 // after Optimize() is called, though in all cases it will be just a
 // performance win -- the pixels are still correct and have the A byte
 // set to 0xff.
 void imgFrame::SetHasNoAlpha()
 {
-  if (mFormat == gfxImageFormatARGB32) {
-      mFormat = gfxImageFormatRGB24;
+  if (mFormat == gfxImageFormat::ARGB32) {
+      mFormat = gfxImageFormat::RGB24;
       mFormatChanged = true;
       ThebesSurface()->SetOpaqueRect(gfxRect(0, 0, mSize.width, mSize.height));
   }
 }
 
 void imgFrame::SetAsNonPremult(bool aIsNonPremult)
 {
   mNonPremult = aIsNonPremult;
@@ -765,57 +765,57 @@ void imgFrame::SetCompositingFailed(bool
 }
 
 // If |aLocation| indicates this is heap memory, we try to measure things with
 // |aMallocSizeOf|.  If that fails (because the platform doesn't support it) or
 // it's non-heap memory, we fall back to computing the size analytically.
 size_t
 imgFrame::SizeOfExcludingThisWithComputedFallbackIfHeap(gfxMemoryLocation aLocation, mozilla::MallocSizeOf aMallocSizeOf) const
 {
-  // aMallocSizeOf is only used if aLocation==GFX_MEMORY_IN_PROCESS_HEAP.  It
+  // aMallocSizeOf is only used if aLocation==gfxMemoryLocation::IN_PROCESS_HEAP.  It
   // should be nullptr otherwise.
   NS_ABORT_IF_FALSE(
-    (aLocation == GFX_MEMORY_IN_PROCESS_HEAP &&  aMallocSizeOf) ||
-    (aLocation != GFX_MEMORY_IN_PROCESS_HEAP && !aMallocSizeOf),
+    (aLocation == gfxMemoryLocation::IN_PROCESS_HEAP &&  aMallocSizeOf) ||
+    (aLocation != gfxMemoryLocation::IN_PROCESS_HEAP && !aMallocSizeOf),
     "mismatch between aLocation and aMallocSizeOf");
 
   size_t n = 0;
 
-  if (mPalettedImageData && aLocation == GFX_MEMORY_IN_PROCESS_HEAP) {
+  if (mPalettedImageData && aLocation == gfxMemoryLocation::IN_PROCESS_HEAP) {
     size_t n2 = aMallocSizeOf(mPalettedImageData);
     if (n2 == 0) {
       n2 = GetImageDataLength() + PaletteDataLength();
     }
     n += n2;
   }
 
 #ifdef USE_WIN_SURFACE
   if (mWinSurface && aLocation == mWinSurface->GetMemoryLocation()) {
     n += mWinSurface->KnownMemoryUsed();
   } else
 #endif
 #ifdef XP_MACOSX
-  if (mQuartzSurface && aLocation == GFX_MEMORY_IN_PROCESS_HEAP) {
+  if (mQuartzSurface && aLocation == gfxMemoryLocation::IN_PROCESS_HEAP) {
     n += mSize.width * mSize.height * 4;
   } else
 #endif
   if (mImageSurface && aLocation == mImageSurface->GetMemoryLocation()) {
     size_t n2 = 0;
-    if (aLocation == GFX_MEMORY_IN_PROCESS_HEAP) { // HEAP: measure
+    if (aLocation == gfxMemoryLocation::IN_PROCESS_HEAP) { // HEAP: measure
       n2 = mImageSurface->SizeOfIncludingThis(aMallocSizeOf);
     }
     if (n2 == 0) {  // non-HEAP or computed fallback for HEAP
       n2 = mImageSurface->KnownMemoryUsed();
     }
     n += n2;
   }
 
   if (mOptSurface && aLocation == mOptSurface->GetMemoryLocation()) {
     size_t n2 = 0;
-    if (aLocation == GFX_MEMORY_IN_PROCESS_HEAP &&
+    if (aLocation == gfxMemoryLocation::IN_PROCESS_HEAP &&
         mOptSurface->SizeOfIsMeasured()) {
       // HEAP: measure (but only if the sub-class is capable of measuring)
       n2 = mOptSurface->SizeOfIncludingThis(aMallocSizeOf);
     }
     if (n2 == 0) {  // non-HEAP or computed fallback for HEAP
       n2 = mOptSurface->KnownMemoryUsed();
     }
     n += n2;
--- a/image/src/imgTools.cpp
+++ b/image/src/imgTools.cpp
@@ -141,17 +141,17 @@ NS_IMETHODIMP imgTools::EncodeScaledImag
   if (aScaledWidth == 0) {
     aScaledWidth = frameWidth;
   } else if (aScaledHeight == 0) {
     aScaledHeight = frameHeight;
   }
 
   // Create a temporary image surface
   nsRefPtr<gfxImageSurface> dest = new gfxImageSurface(gfxIntSize(aScaledWidth, aScaledHeight),
-                                                       gfxImageFormatARGB32);
+                                                       gfxImageFormat::ARGB32);
   if (gfxPlatform::GetPlatform()->SupportsAzureContent()) {
     RefPtr<DrawTarget> dt =
       gfxPlatform::GetPlatform()->CreateDrawTargetForSurface(dest, IntSize(aScaledWidth, aScaledHeight));
     RefPtr<SourceSurface> source = gfxPlatform::GetPlatform()->GetSourceSurfaceForSurface(dt, frame);
 
     dt->DrawSurface(source,
                     Rect(0, 0, aScaledWidth, aScaledHeight),
                     Rect(0, 0, frameWidth, frameHeight),
@@ -215,17 +215,17 @@ NS_IMETHODIMP imgTools::EncodeCroppedIma
   }
 
   // Check that the given crop rectangle is within image bounds.
   NS_ENSURE_ARG(frameWidth >= aOffsetX + aWidth &&
                 frameHeight >= aOffsetY + aHeight);
 
   // Create a temporary image surface
   nsRefPtr<gfxImageSurface> dest = new gfxImageSurface(gfxIntSize(aWidth, aHeight),
-                                                       gfxImageFormatARGB32);
+                                                       gfxImageFormat::ARGB32);
   gfxContext ctx(dest);
 
   // Set translate
   ctx.Translate(gfxPoint(-aOffsetX, -aOffsetY));
 
   // Paint a scaled image
   ctx.SetOperator(gfxContext::OPERATOR_SOURCE);
   ctx.SetSource(frame);
--- a/js/src/ctypes/CTypes.cpp
+++ b/js/src/ctypes/CTypes.cpp
@@ -572,17 +572,17 @@ static const JSPropertySpec sCTypeProps[
          (Property<CType::IsCType, CType::SizeGetter>::Fun),
          CTYPESACC_FLAGS),
   JS_PSG("ptr",
          (Property<CType::IsCType, CType::PtrGetter>::Fun),
          CTYPESACC_FLAGS),
   JS_PSG("prototype",
          (Property<CType::IsCTypeOrProto, CType::PrototypeGetter>::Fun),
          CTYPESACC_FLAGS),
-  { 0, 0, 0, JSOP_NULLWRAPPER, JSOP_NULLWRAPPER }
+  JS_PS_END
 };
 
 static const JSFunctionSpec sCTypeFunctions[] = {
   JS_FN("array", CType::CreateArray, 0, CTYPESFN_FLAGS),
   JS_FN("toString", CType::ToString, 0, CTYPESFN_FLAGS),
   JS_FN("toSource", CType::ToSource, 0, CTYPESFN_FLAGS),
   JS_FS_END
 };
@@ -605,20 +605,16 @@ static const JSFunctionSpec sCDataFuncti
   JS_FN("address", CData::Address, 0, CDATAFN_FLAGS),
   JS_FN("readString", CData::ReadString, 0, CDATAFN_FLAGS),
   JS_FN("readStringReplaceMalformed", CData::ReadStringReplaceMalformed, 0, CDATAFN_FLAGS),
   JS_FN("toSource", CData::ToSource, 0, CDATAFN_FLAGS),
   JS_FN("toString", CData::ToSource, 0, CDATAFN_FLAGS),
   JS_FS_END
 };
 
-static const JSPropertySpec sCDataFinalizerProps[] = {
-  { 0, 0, 0, JSOP_NULLWRAPPER, JSOP_NULLWRAPPER }
-};
-
 static const JSFunctionSpec sCDataFinalizerFunctions[] = {
   JS_FN("dispose",  CDataFinalizer::Methods::Dispose,  0, CDATAFINALIZERFN_FLAGS),
   JS_FN("forget",   CDataFinalizer::Methods::Forget,   0, CDATAFINALIZERFN_FLAGS),
   JS_FN("readString",CData::ReadString, 0, CDATAFINALIZERFN_FLAGS),
   JS_FN("toString", CDataFinalizer::Methods::ToString, 0, CDATAFINALIZERFN_FLAGS),
   JS_FN("toSource", CDataFinalizer::Methods::ToSource, 0, CDATAFINALIZERFN_FLAGS),
   JS_FS_END
 };
@@ -1348,18 +1344,17 @@ JS_InitCTypesClass(JSContext* cx, JSObje
   RootedObject ctor(cx);
   if (!GetObjectProperty(cx, ctypes, "CDataFinalizer", &ctor))
     return false;
 
   RootedObject prototype(cx, JS_NewObject(cx, &sCDataFinalizerProtoClass, NullPtr(), ctypes));
   if (!prototype)
     return false;
 
-  if (!JS_DefineProperties(cx, prototype, sCDataFinalizerProps) ||
-      !JS_DefineFunctions(cx, prototype, sCDataFinalizerFunctions))
+  if (!JS_DefineFunctions(cx, prototype, sCDataFinalizerFunctions))
     return false;
 
   if (!JS_DefineProperty(cx, ctor, "prototype", OBJECT_TO_JSVAL(prototype),
                          nullptr, nullptr, JSPROP_ENUMERATE | JSPROP_READONLY | JSPROP_PERMANENT))
     return false;
 
   if (!JS_DefineProperty(cx, prototype, "constructor", OBJECT_TO_JSVAL(ctor),
                          nullptr, nullptr, JSPROP_ENUMERATE | JSPROP_READONLY | JSPROP_PERMANENT))
--- a/js/src/jit/Ion.cpp
+++ b/js/src/jit/Ion.cpp
@@ -2,16 +2,17 @@
  * vim: set ts=8 sts=4 et sw=4 tw=99:
  * 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 "jit/Ion.h"
 
 #include "mozilla/MemoryReporting.h"
+#include "mozilla/ThreadLocal.h"
 
 #include "jscompartment.h"
 #include "jsworkers.h"
 #if JS_TRACE_LOGGING
 #include "TraceLogging.h"
 #endif
 
 #include "gc/Marking.h"
@@ -46,58 +47,41 @@
 #include "jsgcinlines.h"
 #include "jsinferinlines.h"
 #include "jsobjinlines.h"
 
 using namespace js;
 using namespace js::jit;
 
 using mozilla::Maybe;
+using mozilla::ThreadLocal;
 
 // Assert that JitCode is gc::Cell aligned.
 JS_STATIC_ASSERT(sizeof(JitCode) % gc::CellSize == 0);
 
-#ifdef JS_THREADSAFE
-static bool IonTLSInitialized = false;
-static unsigned IonTLSIndex;
-
-static inline IonContext *
+static ThreadLocal<IonContext*> TlsIonContext;
+
+static IonContext *
 CurrentIonContext()
 {
-    return (IonContext *)PR_GetThreadPrivate(IonTLSIndex);
+    if (!TlsIonContext.initialized())
+        return nullptr;
+    return TlsIonContext.get();
 }
 
-bool
+void
 jit::SetIonContext(IonContext *ctx)
 {
-    return PR_SetThreadPrivate(IonTLSIndex, ctx) == PR_SUCCESS;
+    TlsIonContext.set(ctx);
 }
 
-#else
-
-static IonContext *GlobalIonContext;
-
-static inline IonContext *
-CurrentIonContext()
-{
-    return GlobalIonContext;
-}
-
-bool
-jit::SetIonContext(IonContext *ctx)
-{
-    GlobalIonContext = ctx;
-    return true;
-}
-#endif
-
 IonContext *
 jit::GetIonContext()
 {
-    JS_ASSERT(CurrentIonContext());
+    MOZ_ASSERT(CurrentIonContext());
     return CurrentIonContext();
 }
 
 IonContext *
 jit::MaybeGetIonContext()
 {
     return CurrentIonContext();
 }
@@ -149,25 +133,18 @@ IonContext::IonContext(CompileRuntime *r
 IonContext::~IonContext()
 {
     SetIonContext(prev_);
 }
 
 bool
 jit::InitializeIon()
 {
-#ifdef JS_THREADSAFE
-    if (!IonTLSInitialized) {
-        PRStatus status = PR_NewThreadPrivateIndex(&IonTLSIndex, nullptr);
-        if (status != PR_SUCCESS)
-            return false;
-
-        IonTLSInitialized = true;
-    }
-#endif
+    if (!TlsIonContext.initialized() && !TlsIonContext.init())
+        return false;
     CheckLogging();
     CheckPerf();
     return true;
 }
 
 JitRuntime::JitRuntime()
   : execAlloc_(nullptr),
     ionAlloc_(nullptr),
--- a/js/src/jit/Ion.h
+++ b/js/src/jit/Ion.h
@@ -75,17 +75,17 @@ class IonContext
 
 // Initialize Ion statically for all JSRuntimes.
 bool InitializeIon();
 
 // Get and set the current Ion context.
 IonContext *GetIonContext();
 IonContext *MaybeGetIonContext();
 
-bool SetIonContext(IonContext *ctx);
+void SetIonContext(IonContext *ctx);
 
 bool CanIonCompileScript(JSContext *cx, HandleScript script, bool osr);
 
 MethodStatus CanEnterAtBranch(JSContext *cx, JSScript *script,
                               BaselineFrame *frame, jsbytecode *pc, bool isConstructing);
 MethodStatus CanEnter(JSContext *cx, RunState &state);
 MethodStatus CompileFunctionForBaseline(JSContext *cx, HandleScript script, BaselineFrame *frame,
                                         bool isConstructing);
--- a/js/src/jit/MIRGenerator.h
+++ b/js/src/jit/MIRGenerator.h
@@ -5,16 +5,18 @@
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #ifndef jit_MIRGenerator_h
 #define jit_MIRGenerator_h
 
 // This file declares the data structures used to build a control-flow graph
 // containing MIR.
 
+#include "mozilla/Atomics.h"
+
 #include <stdarg.h>
 
 #include "jscntxt.h"
 #include "jscompartment.h"
 
 #include "jit/CompileInfo.h"
 #include "jit/IonAllocPolicy.h"
 #include "jit/JitCompartment.h"
@@ -140,17 +142,17 @@ class MIRGenerator
   protected:
     CompileInfo *info_;
     const OptimizationInfo *optimizationInfo_;
     TempAllocator *alloc_;
     JSFunction *fun_;
     uint32_t nslots_;
     MIRGraph *graph_;
     bool error_;
-    size_t cancelBuild_;
+    mozilla::Atomic<uint32_t, mozilla::Relaxed> cancelBuild_;
 
     uint32_t maxAsmJSStackArgBytes_;
     bool performsAsmJSCall_;
     AsmJSHeapAccessVector asmJSHeapAccesses_;
     AsmJSGlobalAccessVector asmJSGlobalAccesses_;
     uint32_t minAsmJSHeapLength_;
 
     // Keep track of whether frame arguments are modified during execution.
--- a/js/src/shell/js.cpp
+++ b/js/src/shell/js.cpp
@@ -4912,17 +4912,17 @@ static const JSJitInfo doFoo_methodinfo 
 };
 
 static const JSPropertySpec dom_props[] = {
     {"x", 0,
      JSPROP_SHARED | JSPROP_ENUMERATE | JSPROP_NATIVE_ACCESSORS,
      { (JSPropertyOp)dom_genericGetter, &dom_x_getterinfo },
      { (JSStrictPropertyOp)dom_genericSetter, &dom_x_setterinfo }
     },
-    {nullptr,0,0,JSOP_NULLWRAPPER, JSOP_NULLWRAPPER}
+    JS_PS_END
 };
 
 static const JSFunctionSpec dom_methods[] = {
     JS_FNINFO("doFoo", dom_genericMethod, &doFoo_methodinfo, 3, JSPROP_ENUMERATE),
     JS_FS_END
 };
 
 static const JSClass dom_class = {
--- a/layout/base/FrameLayerBuilder.cpp
+++ b/layout/base/FrameLayerBuilder.cpp
@@ -2165,17 +2165,17 @@ PaintInactiveLayer(nsDisplayListBuilder*
 #ifdef MOZ_DUMP_PAINTING
   int32_t appUnitsPerDevPixel = AppUnitsPerDevPixel(aItem);
   nsIntRect itemVisibleRect =
     aItem->GetVisibleRect().ToOutsidePixels(appUnitsPerDevPixel);
 
   nsRefPtr<gfxASurface> surf;
   if (gfxUtils::sDumpPainting) {
     surf = gfxPlatform::GetPlatform()->CreateOffscreenSurface(itemVisibleRect.Size(),
-                                                              GFX_CONTENT_COLOR_ALPHA);
+                                                              gfxContentType::COLOR_ALPHA);
     surf->SetDeviceOffset(-itemVisibleRect.TopLeft());
     context = new gfxContext(surf);
   }
 #endif
   basic->BeginTransaction();
   basic->SetTarget(context);
 
   if (aItem->GetType() == nsDisplayItem::TYPE_SVG_EFFECTS) {
@@ -3339,17 +3339,17 @@ static void DebugPaintItem(nsRenderingCo
 {
   bool snap;
   nsRect appUnitBounds = aItem->GetBounds(aBuilder, &snap);
   gfxRect bounds(appUnitBounds.x, appUnitBounds.y, appUnitBounds.width, appUnitBounds.height);
   bounds.ScaleInverse(aDest->AppUnitsPerDevPixel());
 
   nsRefPtr<gfxASurface> surf =
     gfxPlatform::GetPlatform()->CreateOffscreenSurface(gfxIntSize(bounds.width, bounds.height),
-                                                       GFX_CONTENT_COLOR_ALPHA);
+                                                       gfxContentType::COLOR_ALPHA);
   surf->SetDeviceOffset(-bounds.TopLeft());
   nsRefPtr<gfxContext> context = new gfxContext(surf);
   nsRefPtr<nsRenderingContext> ctx = new nsRenderingContext();
   ctx->Init(aDest->DeviceContext(), context);
 
   aItem->Paint(aBuilder, ctx);
   DumpPaintedImage(aItem, surf);
   aItem->SetPainted();
@@ -3508,17 +3508,17 @@ static bool ShouldDrawRectsSeparately(gf
   static bool sPaintRectsSeparatelyPrefCached = false;
   if (!sPaintRectsSeparatelyPrefCached) {
     mozilla::Preferences::AddBoolVarCache(&sPaintRectsSeparately, "layout.paint_rects_separately", false);
     sPaintRectsSeparatelyPrefCached = true;
   }
 
   if (!sPaintRectsSeparately ||
       aContext->IsCairo() ||
-      aClip == CLIP_NONE) {
+      aClip == DrawRegionClip::CLIP_NONE) {
     return false;
   }
 
   DrawTarget *dt = aContext->GetDrawTarget();
   return dt->GetType() == BackendType::DIRECT2D;
 }
 
 static void DrawForcedBackgroundColor(gfxContext* aContext, Layer* aLayer, nscolor aBackgroundColor)
@@ -3589,19 +3589,19 @@ FrameLayerBuilder::DrawThebesLayer(Thebe
   ThebesDisplayItemLayerUserData* userData =
     static_cast<ThebesDisplayItemLayerUserData*>
       (aLayer->GetUserData(&gThebesDisplayItemLayerUserData));
   NS_ASSERTION(userData, "where did our user data go?");
 
   bool shouldDrawRectsSeparately = ShouldDrawRectsSeparately(aContext, aClip);
 
   if (!shouldDrawRectsSeparately) {
-    if (aClip == CLIP_DRAW_SNAPPED) {
+    if (aClip == DrawRegionClip::DRAW_SNAPPED) {
       gfxUtils::ClipToRegionSnapped(aContext, aRegionToDraw);
-    } else if (aClip == CLIP_DRAW) {
+    } else if (aClip == DrawRegionClip::DRAW) {
       gfxUtils::ClipToRegion(aContext, aRegionToDraw);
     }
 
     DrawForcedBackgroundColor(aContext, aLayer, userData->mForcedBackgroundColor);
   }
 
   // make the origin of the context coincide with the origin of the
   // ThebesLayer
@@ -3618,17 +3618,17 @@ FrameLayerBuilder::DrawThebesLayer(Thebe
   nsRefPtr<nsRenderingContext> rc = new nsRenderingContext();
   rc->Init(presContext->DeviceContext(), aContext);
 
   if (shouldDrawRectsSeparately) {
     nsIntRegionRectIterator it(aRegionToDraw);
     while (const nsIntRect* iterRect = it.Next()) {
       gfxContextAutoSaveRestore save(aContext);
       aContext->NewPath();
-      aContext->Rectangle(*iterRect, aClip == CLIP_DRAW_SNAPPED);
+      aContext->Rectangle(*iterRect, aClip == DrawRegionClip::DRAW_SNAPPED);
       aContext->Clip();
 
       DrawForcedBackgroundColor(aContext, aLayer, userData->mForcedBackgroundColor);
 
       // Apply the residual transform if it has been enabled, to ensure that
       // snapping when we draw into aContext exactly matches the ideal transform.
       // See above for why this is OK.
       aContext->Translate(aLayer->GetResidualTranslation() - gfxPoint(offset.x, offset.y));
--- a/layout/base/nsCSSRenderingBorders.cpp
+++ b/layout/base/nsCSSRenderingBorders.cpp
@@ -1068,18 +1068,18 @@ nsCSSBorderRenderer::CreateCornerGradien
   pat2.x = cornerOrigin.x -
     mBorderWidths[cornerHeight[aCorner]] * gradientCoeff[aCorner].a;
   pat2.y = cornerOrigin.y -
     mBorderWidths[cornerWidth[aCorner]]  * gradientCoeff[aCorner].b;
 
   float gradientOffset;
   
   if (mContext->IsCairo() &&
-      (mContext->OriginalSurface()->GetType() == gfxSurfaceTypeD2D ||
-       mContext->OriginalSurface()->GetType() == gfxSurfaceTypeQuartz))
+      (mContext->OriginalSurface()->GetType() == gfxSurfaceType::D2D ||
+       mContext->OriginalSurface()->GetType() == gfxSurfaceType::Quartz))
   {
     // On quarz this doesn't do exactly the right thing, but it does do what
     // most other browsers do and doing the 'right' thing seems to be
     // hard with the quartz cairo backend.
     gradientOffset = 0;
   } else {
     // When cairo/Azure does the gradient drawing this gives us pretty nice behavior!
     gradientOffset = 0.25 / sqrt(pow(mBorderWidths[cornerHeight[aCorner]], 2) +
--- a/layout/base/nsLayoutUtils.cpp
+++ b/layout/base/nsLayoutUtils.cpp
@@ -4341,17 +4341,17 @@ nsLayoutUtils::DrawPixelSnapped(nsRender
                    drawingParams.mSubimage.width, drawingParams.mSubimage.height);
 
   NS_ASSERTION(!sourceRect.Intersect(subimage).IsEmpty(),
                "We must be allowed to sample *some* source pixels!");
 
   gfxUtils::DrawPixelSnapped(ctx, aDrawable,
                              drawingParams.mUserSpaceToImageSpace, subimage,
                              sourceRect, imageRect, drawingParams.mFillRect,