Merge m-c to inbound. a=merge
authorRyan VanderMeulen <ryanvm@gmail.com>
Fri, 03 Oct 2014 16:26:37 -0400
changeset 231998 df6a28be0934211d82f539b1b42ae4e446b39a41
parent 231997 9d063480262717f3909e9d0212124b799c1d66d8 (current diff)
parent 231944 229801d17f7e24e2cb5ad368b553994f1482d4bb (diff)
child 231999 88258156ffef434a46ecacf2ea09f47f8862e958
push id4187
push userbhearsum@mozilla.com
push dateFri, 28 Nov 2014 15:29:12 +0000
treeherdermozilla-beta@f23cc6a30c11 [default view] [failures only]
perfherder[talos] [build metrics] [platform microbench] (compared to previous push)
reviewersmerge
milestone35.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 m-c to inbound. a=merge
dom/media/nsIDOMMediaStream.idl
dom/tests/mochitest/general/test_interfaces.html
dom/webidl/moz.build
mobile/android/base/resources/color-large-v11/new_tablet_tab_strip_item_title.xml
mobile/android/base/resources/drawable-hdpi-v11/ic_menu_back.png
mobile/android/base/resources/drawable-large-hdpi-v11/new_tablet_default_favicon.png
mobile/android/base/resources/drawable-large-hdpi-v11/new_tablet_ic_menu_back.png
mobile/android/base/resources/drawable-large-hdpi-v11/new_tablet_ic_menu_forward.png
mobile/android/base/resources/drawable-large-hdpi-v11/new_tablet_ic_menu_reload.png
mobile/android/base/resources/drawable-large-hdpi-v11/new_tablet_menu.png
mobile/android/base/resources/drawable-large-hdpi-v11/new_tablet_tabs_count.png
mobile/android/base/resources/drawable-large-hdpi-v11/new_tablet_tabs_count_foreground.png
mobile/android/base/resources/drawable-large-mdpi-v11/new_tablet_default_favicon.png
mobile/android/base/resources/drawable-large-mdpi-v11/new_tablet_ic_menu_back.png
mobile/android/base/resources/drawable-large-mdpi-v11/new_tablet_ic_menu_forward.png
mobile/android/base/resources/drawable-large-mdpi-v11/new_tablet_ic_menu_reload.png
mobile/android/base/resources/drawable-large-mdpi-v11/new_tablet_menu.png
mobile/android/base/resources/drawable-large-mdpi-v11/new_tablet_tabs_count.png
mobile/android/base/resources/drawable-large-mdpi-v11/new_tablet_tabs_count_foreground.png
mobile/android/base/resources/drawable-large-v11/new_tablet_tab_strip_divider.xml
mobile/android/base/resources/drawable-large-v11/new_tablet_tab_strip_item_bg.xml
mobile/android/base/resources/drawable-large-xhdpi-v11/new_tablet_default_favicon.png
mobile/android/base/resources/drawable-large-xhdpi-v11/new_tablet_ic_menu_back.png
mobile/android/base/resources/drawable-large-xhdpi-v11/new_tablet_ic_menu_forward.png
mobile/android/base/resources/drawable-large-xhdpi-v11/new_tablet_ic_menu_reload.png
mobile/android/base/resources/drawable-large-xhdpi-v11/new_tablet_menu.png
mobile/android/base/resources/drawable-large-xhdpi-v11/new_tablet_tabs_count.png
mobile/android/base/resources/drawable-large-xhdpi-v11/new_tablet_tabs_count_foreground.png
mobile/android/base/resources/drawable-large-xxhdpi-v11/new_tablet_default_favicon.png
mobile/android/base/resources/drawable-large-xxhdpi-v11/new_tablet_ic_menu_back.png
mobile/android/base/resources/drawable-large-xxhdpi-v11/new_tablet_ic_menu_forward.png
mobile/android/base/resources/drawable-large-xxhdpi-v11/new_tablet_ic_menu_reload.png
mobile/android/base/resources/drawable-large-xxhdpi-v11/new_tablet_menu.png
mobile/android/base/resources/drawable-large-xxhdpi-v11/new_tablet_tabs_count.png
mobile/android/base/resources/drawable-large-xxhdpi-v11/new_tablet_tabs_count_foreground.png
mobile/android/base/resources/drawable-mdpi-v11/ic_menu_back.png
mobile/android/base/resources/drawable-xhdpi-v11/ic_menu_back.png
mobile/android/base/resources/layout-large-land-v11/tabs_panel.xml
mobile/android/base/resources/layout-large-land-v11/tabs_panel_footer.xml
mobile/android/base/resources/layout-large-land-v11/tabs_panel_header.xml
mobile/android/base/resources/layout-large-v11/new_tablet_browser_toolbar.xml
mobile/android/base/resources/layout-large-v11/new_tablet_tab_strip.xml
mobile/android/base/resources/layout-large-v11/new_tablet_tabs_counter.xml
mobile/android/base/resources/layout-large-v11/tab_strip.xml
mobile/android/base/resources/layout-large-v11/tab_strip_item.xml
mobile/android/base/resources/layout-large-v11/tab_strip_item_view.xml
mobile/android/base/resources/layout/tabs_panel.xml
mobile/android/base/resources/layout/tabs_panel_header.xml
--- a/b2g/config/dolphin/sources.xml
+++ b/b2g/config/dolphin/sources.xml
@@ -10,25 +10,25 @@
   <!--original fetch url was git://codeaurora.org/-->
   <remote fetch="https://git.mozilla.org/external/caf" name="caf"/>
   <!--original fetch url was https://git.mozilla.org/releases-->
   <remote fetch="https://git.mozilla.org/releases" name="mozillaorg"/>
   <!-- B2G specific things. -->
   <project name="platform_build" path="build" remote="b2g" revision="3a2947df41a480de1457a6dcdbf46ad0af70d8e0">
     <copyfile dest="Makefile" src="core/root.mk"/>
   </project>
-  <project name="gaia" path="gaia" remote="mozillaorg" revision="a8a6eed2ba9d66239aac789b9ee4900f911c73cb"/>
+  <project name="gaia" path="gaia" remote="mozillaorg" revision="83f495a1c12687970f7f2840c2729795c4b88177"/>
   <project name="fake-libdvm" path="dalvik" remote="b2g" revision="d50ae982b19f42f0b66d08b9eb306be81687869f"/>
   <project name="gonk-misc" path="gonk-misc" remote="b2g" revision="5883a99b6528ced9dafaed8d3ca2405fb285537e"/>
   <project name="librecovery" path="librecovery" remote="b2g" revision="891e5069c0ad330d8191bf8c7b879c814258c89f"/>
   <project name="moztt" path="external/moztt" remote="b2g" revision="562d357b72279a9e35d4af5aeecc8e1ffa2f44f1"/>
   <project name="rilproxy" path="rilproxy" remote="b2g" revision="827214fcf38d6569aeb5c6d6f31cb296d1f09272"/>
   <project name="valgrind" path="external/valgrind" remote="b2g" revision="daa61633c32b9606f58799a3186395fd2bbb8d8c"/>
   <project name="vex" path="external/VEX" remote="b2g" revision="47f031c320888fe9f3e656602588565b52d43010"/>
-  <project name="apitrace" path="external/apitrace" remote="apitrace" revision="4bc3cfde42118081268690217172d7b577867c65"/>
+  <project name="apitrace" path="external/apitrace" remote="apitrace" revision="693382a5630079f9debfe55c59f8197d432f47ff"/>
   <!-- Stock Android things -->
   <project groups="linux" name="platform/prebuilts/gcc/linux-x86/host/i686-linux-glibc2.7-4.6" path="prebuilts/gcc/linux-x86/host/i686-linux-glibc2.7-4.6" revision="95bb5b66b3ec5769c3de8d3f25d681787418e7d2"/>
   <project groups="linux" name="platform/prebuilts/gcc/linux-x86/host/x86_64-linux-glibc2.7-4.6" path="prebuilts/gcc/linux-x86/host/x86_64-linux-glibc2.7-4.6" revision="ebdad82e61c16772f6cd47e9f11936bf6ebe9aa0"/>
   <project groups="linux,arm" name="platform/prebuilts/gcc/linux-x86/arm/arm-eabi-4.7" path="prebuilts/gcc/linux-x86/arm/arm-eabi-4.7" revision="8b880805d454664b3eed11d0f053cdeafa1ff06e"/>
   <project groups="linux,arm" name="platform/prebuilts/gcc/linux-x86/arm/arm-linux-androideabi-4.7" path="prebuilts/gcc/linux-x86/arm/arm-linux-androideabi-4.7" revision="a1e239a0bb5cd1d69680bf1075883aa9a7bf2429"/>
   <project groups="linux,x86" name="platform/prebuilts/gcc/linux-x86/x86/i686-linux-android-4.7" path="prebuilts/gcc/linux-x86/x86/i686-linux-android-4.7" revision="c7931763d41be602407ed9d71e2c0292c6597e00"/>
   <project groups="linux,x86" name="platform/prebuilts/python/linux-x86/2.7.5" path="prebuilts/python/linux-x86/2.7.5" revision="83760d213fb3bec7b4117d266fcfbf6fe2ba14ab"/>
   <project name="device/common" path="device/common" revision="6a2995683de147791e516aae2ccb31fdfbe2ad30"/>
--- a/b2g/config/emulator-ics/sources.xml
+++ b/b2g/config/emulator-ics/sources.xml
@@ -14,23 +14,23 @@
   <!--original fetch url was git://github.com/apitrace/-->
   <remote fetch="https://git.mozilla.org/external/apitrace" name="apitrace"/>
   <default remote="caf" revision="refs/tags/android-4.0.4_r2.1" sync-j="4"/>
   <!-- Gonk specific things and forks -->
   <project name="platform_build" path="build" remote="b2g" revision="84923f1940625c47ff4c1fdf01b10fde3b7d909e">
     <copyfile dest="Makefile" src="core/root.mk"/>
   </project>
   <project name="fake-dalvik" path="dalvik" remote="b2g" revision="ca1f327d5acc198bb4be62fa51db2c039032c9ce"/>
-  <project name="gaia.git" path="gaia" remote="mozillaorg" revision="a8a6eed2ba9d66239aac789b9ee4900f911c73cb"/>
+  <project name="gaia.git" path="gaia" remote="mozillaorg" revision="83f495a1c12687970f7f2840c2729795c4b88177"/>
   <project name="gonk-misc" path="gonk-misc" remote="b2g" revision="5883a99b6528ced9dafaed8d3ca2405fb285537e"/>
   <project name="rilproxy" path="rilproxy" remote="b2g" revision="827214fcf38d6569aeb5c6d6f31cb296d1f09272"/>
   <project name="platform_hardware_ril" path="hardware/ril" remote="b2g" revision="cd88d860656c31c7da7bb310d6a160d0011b0961"/>
   <project name="platform_external_qemu" path="external/qemu" remote="b2g" revision="c058843242068d0df7c107e09da31b53d2e08fa6"/>
   <project name="moztt" path="external/moztt" remote="b2g" revision="562d357b72279a9e35d4af5aeecc8e1ffa2f44f1"/>
-  <project name="apitrace" path="external/apitrace" remote="apitrace" revision="4bc3cfde42118081268690217172d7b577867c65"/>
+  <project name="apitrace" path="external/apitrace" remote="apitrace" revision="693382a5630079f9debfe55c59f8197d432f47ff"/>
   <!-- Stock Android things -->
   <project name="platform/abi/cpp" path="abi/cpp" revision="dd924f92906085b831bf1cbbc7484d3c043d613c"/>
   <project name="platform/bionic" path="bionic" revision="c72b8f6359de7ed17c11ddc9dfdde3f615d188a9"/>
   <project name="platform/bootable/recovery" path="bootable/recovery" revision="425f8b5fadf5889834c5acd27d23c9e0b2129c28"/>
   <project name="device/common" path="device/common" revision="42b808b7e93d0619286ae8e59110b176b7732389"/>
   <project name="device/sample" path="device/sample" revision="237bd668d0f114d801a8d6455ef5e02cc3577587"/>
   <project name="platform_external_apriori" path="external/apriori" remote="b2g" revision="11816ad0406744f963537b23d68ed9c2afb412bd"/>
   <project name="platform/external/bluetooth/bluez" path="external/bluetooth/bluez" revision="52a1a862a8bac319652b8f82d9541ba40bfa45ce"/>
--- a/b2g/config/emulator-jb/sources.xml
+++ b/b2g/config/emulator-jb/sources.xml
@@ -12,20 +12,20 @@
   <!--original fetch url was https://git.mozilla.org/releases-->
   <remote fetch="https://git.mozilla.org/releases" name="mozillaorg"/>
   <!-- B2G specific things. -->
   <project name="platform_build" path="build" remote="b2g" revision="8986df0f82e15ac2798df0b6c2ee3435400677ac">
     <copyfile dest="Makefile" src="core/root.mk"/>
   </project>
   <project name="rilproxy" path="rilproxy" remote="b2g" revision="827214fcf38d6569aeb5c6d6f31cb296d1f09272"/>
   <project name="fake-libdvm" path="dalvik" remote="b2g" revision="d50ae982b19f42f0b66d08b9eb306be81687869f"/>
-  <project name="gaia" path="gaia" remote="mozillaorg" revision="a8a6eed2ba9d66239aac789b9ee4900f911c73cb"/>
+  <project name="gaia" path="gaia" remote="mozillaorg" revision="83f495a1c12687970f7f2840c2729795c4b88177"/>
   <project name="gonk-misc" path="gonk-misc" remote="b2g" revision="5883a99b6528ced9dafaed8d3ca2405fb285537e"/>
   <project name="moztt" path="external/moztt" remote="b2g" revision="562d357b72279a9e35d4af5aeecc8e1ffa2f44f1"/>
-  <project name="apitrace" path="external/apitrace" remote="apitrace" revision="4bc3cfde42118081268690217172d7b577867c65"/>
+  <project name="apitrace" path="external/apitrace" remote="apitrace" revision="693382a5630079f9debfe55c59f8197d432f47ff"/>
   <project name="valgrind" path="external/valgrind" remote="b2g" revision="daa61633c32b9606f58799a3186395fd2bbb8d8c"/>
   <project name="vex" path="external/VEX" remote="b2g" revision="47f031c320888fe9f3e656602588565b52d43010"/>
   <!-- Stock Android things -->
   <project groups="linux" name="platform/prebuilts/clang/linux-x86/3.1" path="prebuilts/clang/linux-x86/3.1" revision="5c45f43419d5582949284eee9cef0c43d866e03b"/>
   <project groups="linux" name="platform/prebuilts/clang/linux-x86/3.2" path="prebuilts/clang/linux-x86/3.2" revision="3748b4168e7bd8d46457d4b6786003bc6a5223ce"/>
   <project groups="linux" name="platform/prebuilts/gcc/linux-x86/host/i686-linux-glibc2.7-4.6" path="prebuilts/gcc/linux-x86/host/i686-linux-glibc2.7-4.6" revision="9025e50b9d29b3cabbbb21e1dd94d0d13121a17e"/>
   <project groups="linux" name="platform/prebuilts/gcc/linux-x86/host/x86_64-linux-glibc2.7-4.6" path="prebuilts/gcc/linux-x86/host/x86_64-linux-glibc2.7-4.6" revision="b89fda71fcd0fa0cf969310e75be3ea33e048b44"/>
   <project groups="linux,arm" name="platform/prebuilts/gcc/linux-x86/arm/arm-eabi-4.7" path="prebuilts/gcc/linux-x86/arm/arm-eabi-4.7" revision="2e7d5348f35575870b3c7e567a9a9f6d66f8d6c5"/>
--- a/b2g/config/emulator-kk/sources.xml
+++ b/b2g/config/emulator-kk/sources.xml
@@ -10,25 +10,25 @@
   <!--original fetch url was git://codeaurora.org/-->
   <remote fetch="https://git.mozilla.org/external/caf" name="caf"/>
   <!--original fetch url was https://git.mozilla.org/releases-->
   <remote fetch="https://git.mozilla.org/releases" name="mozillaorg"/>
   <!-- B2G specific things. -->
   <project name="platform_build" path="build" remote="b2g" revision="3a2947df41a480de1457a6dcdbf46ad0af70d8e0">
     <copyfile dest="Makefile" src="core/root.mk"/>
   </project>
-  <project name="gaia" path="gaia" remote="mozillaorg" revision="a8a6eed2ba9d66239aac789b9ee4900f911c73cb"/>
+  <project name="gaia" path="gaia" remote="mozillaorg" revision="83f495a1c12687970f7f2840c2729795c4b88177"/>
   <project name="fake-libdvm" path="dalvik" remote="b2g" revision="d50ae982b19f42f0b66d08b9eb306be81687869f"/>
   <project name="gonk-misc" path="gonk-misc" remote="b2g" revision="5883a99b6528ced9dafaed8d3ca2405fb285537e"/>
   <project name="librecovery" path="librecovery" remote="b2g" revision="891e5069c0ad330d8191bf8c7b879c814258c89f"/>
   <project name="moztt" path="external/moztt" remote="b2g" revision="562d357b72279a9e35d4af5aeecc8e1ffa2f44f1"/>
   <project name="rilproxy" path="rilproxy" remote="b2g" revision="827214fcf38d6569aeb5c6d6f31cb296d1f09272"/>
   <project name="valgrind" path="external/valgrind" remote="b2g" revision="daa61633c32b9606f58799a3186395fd2bbb8d8c"/>
   <project name="vex" path="external/VEX" remote="b2g" revision="47f031c320888fe9f3e656602588565b52d43010"/>
-  <project name="apitrace" path="external/apitrace" remote="apitrace" revision="4bc3cfde42118081268690217172d7b577867c65"/>
+  <project name="apitrace" path="external/apitrace" remote="apitrace" revision="693382a5630079f9debfe55c59f8197d432f47ff"/>
   <!-- Stock Android things -->
   <project groups="linux" name="platform/prebuilts/gcc/linux-x86/host/i686-linux-glibc2.7-4.6" path="prebuilts/gcc/linux-x86/host/i686-linux-glibc2.7-4.6" revision="f92a936f2aa97526d4593386754bdbf02db07a12"/>
   <project groups="linux" name="platform/prebuilts/gcc/linux-x86/host/x86_64-linux-glibc2.7-4.6" path="prebuilts/gcc/linux-x86/host/x86_64-linux-glibc2.7-4.6" revision="6e47ff2790f5656b5b074407829ceecf3e6188c4"/>
   <project groups="linux,arm" name="platform/prebuilts/gcc/linux-x86/arm/arm-eabi-4.7" path="prebuilts/gcc/linux-x86/arm/arm-eabi-4.7" revision="1950e4760fa14688b83cdbb5acaa1af9f82ef434"/>
   <project groups="linux,arm" name="platform/prebuilts/gcc/linux-x86/arm/arm-linux-androideabi-4.7" path="prebuilts/gcc/linux-x86/arm/arm-linux-androideabi-4.7" revision="ac6eb97a37035c09fb5ede0852f0881e9aadf9ad"/>
   <project groups="linux,x86" name="platform/prebuilts/gcc/linux-x86/x86/i686-linux-android-4.7" path="prebuilts/gcc/linux-x86/x86/i686-linux-android-4.7" revision="737f591c5f95477148d26602c7be56cbea0cdeb9"/>
   <project groups="linux,x86" name="platform/prebuilts/python/linux-x86/2.7.5" path="prebuilts/python/linux-x86/2.7.5" revision="51da9b1981be481b92a59a826d4d78dc73d0989a"/>
   <project name="device/common" path="device/common" revision="798a3664597e6041985feab9aef42e98d458bc3d"/>
--- a/b2g/config/emulator/sources.xml
+++ b/b2g/config/emulator/sources.xml
@@ -14,23 +14,23 @@
   <!--original fetch url was git://github.com/apitrace/-->
   <remote fetch="https://git.mozilla.org/external/apitrace" name="apitrace"/>
   <default remote="caf" revision="refs/tags/android-4.0.4_r2.1" sync-j="4"/>
   <!-- Gonk specific things and forks -->
   <project name="platform_build" path="build" remote="b2g" revision="84923f1940625c47ff4c1fdf01b10fde3b7d909e">
     <copyfile dest="Makefile" src="core/root.mk"/>
   </project>
   <project name="fake-dalvik" path="dalvik" remote="b2g" revision="ca1f327d5acc198bb4be62fa51db2c039032c9ce"/>
-  <project name="gaia.git" path="gaia" remote="mozillaorg" revision="a8a6eed2ba9d66239aac789b9ee4900f911c73cb"/>
+  <project name="gaia.git" path="gaia" remote="mozillaorg" revision="83f495a1c12687970f7f2840c2729795c4b88177"/>
   <project name="gonk-misc" path="gonk-misc" remote="b2g" revision="5883a99b6528ced9dafaed8d3ca2405fb285537e"/>
   <project name="rilproxy" path="rilproxy" remote="b2g" revision="827214fcf38d6569aeb5c6d6f31cb296d1f09272"/>
   <project name="platform_hardware_ril" path="hardware/ril" remote="b2g" revision="cd88d860656c31c7da7bb310d6a160d0011b0961"/>
   <project name="platform_external_qemu" path="external/qemu" remote="b2g" revision="c058843242068d0df7c107e09da31b53d2e08fa6"/>
   <project name="moztt" path="external/moztt" remote="b2g" revision="562d357b72279a9e35d4af5aeecc8e1ffa2f44f1"/>
-  <project name="apitrace" path="external/apitrace" remote="apitrace" revision="4bc3cfde42118081268690217172d7b577867c65"/>
+  <project name="apitrace" path="external/apitrace" remote="apitrace" revision="693382a5630079f9debfe55c59f8197d432f47ff"/>
   <!-- Stock Android things -->
   <project name="platform/abi/cpp" path="abi/cpp" revision="dd924f92906085b831bf1cbbc7484d3c043d613c"/>
   <project name="platform/bionic" path="bionic" revision="c72b8f6359de7ed17c11ddc9dfdde3f615d188a9"/>
   <project name="platform/bootable/recovery" path="bootable/recovery" revision="425f8b5fadf5889834c5acd27d23c9e0b2129c28"/>
   <project name="device/common" path="device/common" revision="42b808b7e93d0619286ae8e59110b176b7732389"/>
   <project name="device/sample" path="device/sample" revision="237bd668d0f114d801a8d6455ef5e02cc3577587"/>
   <project name="platform_external_apriori" path="external/apriori" remote="b2g" revision="11816ad0406744f963537b23d68ed9c2afb412bd"/>
   <project name="platform/external/bluetooth/bluez" path="external/bluetooth/bluez" revision="52a1a862a8bac319652b8f82d9541ba40bfa45ce"/>
--- a/b2g/config/flame-kk/sources.xml
+++ b/b2g/config/flame-kk/sources.xml
@@ -10,25 +10,25 @@
   <!--original fetch url was git://codeaurora.org/-->
   <remote fetch="https://git.mozilla.org/external/caf" name="caf"/>
   <!--original fetch url was https://git.mozilla.org/releases-->
   <remote fetch="https://git.mozilla.org/releases" name="mozillaorg"/>
   <!-- B2G specific things. -->
   <project name="platform_build" path="build" remote="b2g" revision="3a2947df41a480de1457a6dcdbf46ad0af70d8e0">
     <copyfile dest="Makefile" src="core/root.mk"/>
   </project>
-  <project name="gaia" path="gaia" remote="mozillaorg" revision="a8a6eed2ba9d66239aac789b9ee4900f911c73cb"/>
+  <project name="gaia" path="gaia" remote="mozillaorg" revision="83f495a1c12687970f7f2840c2729795c4b88177"/>
   <project name="fake-libdvm" path="dalvik" remote="b2g" revision="d50ae982b19f42f0b66d08b9eb306be81687869f"/>
   <project name="gonk-misc" path="gonk-misc" remote="b2g" revision="5883a99b6528ced9dafaed8d3ca2405fb285537e"/>
   <project name="librecovery" path="librecovery" remote="b2g" revision="891e5069c0ad330d8191bf8c7b879c814258c89f"/>
   <project name="moztt" path="external/moztt" remote="b2g" revision="562d357b72279a9e35d4af5aeecc8e1ffa2f44f1"/>
   <project name="rilproxy" path="rilproxy" remote="b2g" revision="827214fcf38d6569aeb5c6d6f31cb296d1f09272"/>
   <project name="valgrind" path="external/valgrind" remote="b2g" revision="daa61633c32b9606f58799a3186395fd2bbb8d8c"/>
   <project name="vex" path="external/VEX" remote="b2g" revision="47f031c320888fe9f3e656602588565b52d43010"/>
-  <project name="apitrace" path="external/apitrace" remote="apitrace" revision="4bc3cfde42118081268690217172d7b577867c65"/>
+  <project name="apitrace" path="external/apitrace" remote="apitrace" revision="693382a5630079f9debfe55c59f8197d432f47ff"/>
   <!-- Stock Android things -->
   <project groups="linux" name="platform/prebuilts/gcc/linux-x86/host/i686-linux-glibc2.7-4.6" path="prebuilts/gcc/linux-x86/host/i686-linux-glibc2.7-4.6" revision="95bb5b66b3ec5769c3de8d3f25d681787418e7d2"/>
   <project groups="linux" name="platform/prebuilts/gcc/linux-x86/host/x86_64-linux-glibc2.7-4.6" path="prebuilts/gcc/linux-x86/host/x86_64-linux-glibc2.7-4.6" revision="ebdad82e61c16772f6cd47e9f11936bf6ebe9aa0"/>
   <project groups="linux,arm" name="platform/prebuilts/gcc/linux-x86/arm/arm-eabi-4.7" path="prebuilts/gcc/linux-x86/arm/arm-eabi-4.7" revision="8b880805d454664b3eed11d0f053cdeafa1ff06e"/>
   <project groups="linux,arm" name="platform/prebuilts/gcc/linux-x86/arm/arm-linux-androideabi-4.7" path="prebuilts/gcc/linux-x86/arm/arm-linux-androideabi-4.7" revision="a1e239a0bb5cd1d69680bf1075883aa9a7bf2429"/>
   <project groups="linux,x86" name="platform/prebuilts/gcc/linux-x86/x86/i686-linux-android-4.7" path="prebuilts/gcc/linux-x86/x86/i686-linux-android-4.7" revision="c7931763d41be602407ed9d71e2c0292c6597e00"/>
   <project groups="linux,x86" name="platform/prebuilts/python/linux-x86/2.7.5" path="prebuilts/python/linux-x86/2.7.5" revision="a32003194f707f66a2d8cdb913ed1869f1926c5d"/>
   <project name="device/common" path="device/common" revision="96d4d2006c4fcb2f19a3fa47ab10cb409faa017b"/>
--- a/b2g/config/flame/sources.xml
+++ b/b2g/config/flame/sources.xml
@@ -12,20 +12,20 @@
   <!--original fetch url was https://git.mozilla.org/releases-->
   <remote fetch="https://git.mozilla.org/releases" name="mozillaorg"/>
   <!-- B2G specific things. -->
   <project name="platform_build" path="build" remote="b2g" revision="8986df0f82e15ac2798df0b6c2ee3435400677ac">
     <copyfile dest="Makefile" src="core/root.mk"/>
   </project>
   <project name="librecovery" path="librecovery" remote="b2g" revision="891e5069c0ad330d8191bf8c7b879c814258c89f"/>
   <project name="fake-libdvm" path="dalvik" remote="b2g" revision="d50ae982b19f42f0b66d08b9eb306be81687869f"/>
-  <project name="gaia" path="gaia" remote="mozillaorg" revision="a8a6eed2ba9d66239aac789b9ee4900f911c73cb"/>
+  <project name="gaia" path="gaia" remote="mozillaorg" revision="83f495a1c12687970f7f2840c2729795c4b88177"/>
   <project name="gonk-misc" path="gonk-misc" remote="b2g" revision="5883a99b6528ced9dafaed8d3ca2405fb285537e"/>
   <project name="moztt" path="external/moztt" remote="b2g" revision="562d357b72279a9e35d4af5aeecc8e1ffa2f44f1"/>
-  <project name="apitrace" path="external/apitrace" remote="apitrace" revision="4bc3cfde42118081268690217172d7b577867c65"/>
+  <project name="apitrace" path="external/apitrace" remote="apitrace" revision="693382a5630079f9debfe55c59f8197d432f47ff"/>
   <project name="valgrind" path="external/valgrind" remote="b2g" revision="daa61633c32b9606f58799a3186395fd2bbb8d8c"/>
   <project name="vex" path="external/VEX" remote="b2g" revision="47f031c320888fe9f3e656602588565b52d43010"/>
   <!-- Stock Android things -->
   <project groups="linux" name="platform/prebuilts/clang/linux-x86/3.1" path="prebuilts/clang/linux-x86/3.1" revision="e95b4ce22c825da44d14299e1190ea39a5260bde"/>
   <project groups="linux" name="platform/prebuilts/clang/linux-x86/3.2" path="prebuilts/clang/linux-x86/3.2" revision="471afab478649078ad7c75ec6b252481a59e19b8"/>
   <project groups="linux" name="platform/prebuilts/gcc/linux-x86/host/i686-linux-glibc2.7-4.6" path="prebuilts/gcc/linux-x86/host/i686-linux-glibc2.7-4.6" revision="95bb5b66b3ec5769c3de8d3f25d681787418e7d2"/>
   <project groups="linux" name="platform/prebuilts/gcc/linux-x86/host/x86_64-linux-glibc2.7-4.6" path="prebuilts/gcc/linux-x86/host/x86_64-linux-glibc2.7-4.6" revision="ebdad82e61c16772f6cd47e9f11936bf6ebe9aa0"/>
   <project groups="linux,arm" name="platform/prebuilts/gcc/linux-x86/arm/arm-eabi-4.7" path="prebuilts/gcc/linux-x86/arm/arm-eabi-4.7" revision="8b880805d454664b3eed11d0f053cdeafa1ff06e"/>
--- a/b2g/config/gaia.json
+++ b/b2g/config/gaia.json
@@ -1,9 +1,9 @@
 {
     "git": {
         "git_revision": "", 
         "remote": "", 
         "branch": ""
     }, 
-    "revision": "736a08de0dd46c283137a289a484a6b404cb0dd1", 
+    "revision": "665042c75b7d6b0a1f4b8f07f79cd998abce68b0", 
     "repo_path": "/integration/gaia-central"
 }
--- a/b2g/config/hamachi/sources.xml
+++ b/b2g/config/hamachi/sources.xml
@@ -12,22 +12,22 @@
   <!--original fetch url was git://github.com/apitrace/-->
   <remote fetch="https://git.mozilla.org/external/apitrace" name="apitrace"/>
   <default remote="caf" revision="b2g/ics_strawberry" sync-j="4"/>
   <!-- Gonk specific things and forks -->
   <project name="platform_build" path="build" remote="b2g" revision="84923f1940625c47ff4c1fdf01b10fde3b7d909e">
     <copyfile dest="Makefile" src="core/root.mk"/>
   </project>
   <project name="fake-dalvik" path="dalvik" remote="b2g" revision="ca1f327d5acc198bb4be62fa51db2c039032c9ce"/>
-  <project name="gaia.git" path="gaia" remote="mozillaorg" revision="a8a6eed2ba9d66239aac789b9ee4900f911c73cb"/>
+  <project name="gaia.git" path="gaia" remote="mozillaorg" revision="83f495a1c12687970f7f2840c2729795c4b88177"/>
   <project name="gonk-misc" path="gonk-misc" remote="b2g" revision="5883a99b6528ced9dafaed8d3ca2405fb285537e"/>
   <project name="rilproxy" path="rilproxy" remote="b2g" revision="827214fcf38d6569aeb5c6d6f31cb296d1f09272"/>
   <project name="librecovery" path="librecovery" remote="b2g" revision="891e5069c0ad330d8191bf8c7b879c814258c89f"/>
   <project name="moztt" path="external/moztt" remote="b2g" revision="562d357b72279a9e35d4af5aeecc8e1ffa2f44f1"/>
-  <project name="apitrace" path="external/apitrace" remote="apitrace" revision="4bc3cfde42118081268690217172d7b577867c65"/>
+  <project name="apitrace" path="external/apitrace" remote="apitrace" revision="693382a5630079f9debfe55c59f8197d432f47ff"/>
   <!-- Stock Android things -->
   <project name="platform/abi/cpp" path="abi/cpp" revision="6426040f1be4a844082c9769171ce7f5341a5528"/>
   <project name="platform/bionic" path="bionic" revision="d2eb6c7b6e1bc7643c17df2d9d9bcb1704d0b9ab"/>
   <project name="platform/bootable/recovery" path="bootable/recovery" revision="746bc48f34f5060f90801925dcdd964030c1ab6d"/>
   <project name="platform/development" path="development" revision="2460485184bc8535440bb63876d4e63ec1b4770c"/>
   <project name="device/common" path="device/common" revision="0dcc1e03659db33b77392529466f9eb685cdd3c7"/>
   <project name="device/sample" path="device/sample" revision="68b1cb978a20806176123b959cb05d4fa8adaea4"/>
   <project name="platform_external_apriori" path="external/apriori" remote="b2g" revision="11816ad0406744f963537b23d68ed9c2afb412bd"/>
--- a/b2g/config/helix/sources.xml
+++ b/b2g/config/helix/sources.xml
@@ -10,17 +10,17 @@
   <!--original fetch url was https://git.mozilla.org/releases-->
   <remote fetch="https://git.mozilla.org/releases" name="mozillaorg"/>
   <default remote="caf" revision="b2g/ics_strawberry" sync-j="4"/>
   <!-- Gonk specific things and forks -->
   <project name="platform_build" path="build" remote="b2g" revision="84923f1940625c47ff4c1fdf01b10fde3b7d909e">
     <copyfile dest="Makefile" src="core/root.mk"/>
   </project>
   <project name="fake-dalvik" path="dalvik" remote="b2g" revision="ca1f327d5acc198bb4be62fa51db2c039032c9ce"/>
-  <project name="gaia.git" path="gaia" remote="mozillaorg" revision="a8a6eed2ba9d66239aac789b9ee4900f911c73cb"/>
+  <project name="gaia.git" path="gaia" remote="mozillaorg" revision="83f495a1c12687970f7f2840c2729795c4b88177"/>
   <project name="gonk-misc" path="gonk-misc" remote="b2g" revision="5883a99b6528ced9dafaed8d3ca2405fb285537e"/>
   <project name="rilproxy" path="rilproxy" remote="b2g" revision="827214fcf38d6569aeb5c6d6f31cb296d1f09272"/>
   <project name="librecovery" path="librecovery" remote="b2g" revision="891e5069c0ad330d8191bf8c7b879c814258c89f"/>
   <project name="moztt" path="external/moztt" remote="b2g" revision="562d357b72279a9e35d4af5aeecc8e1ffa2f44f1"/>
   <project name="gonk-patches" path="patches" remote="b2g" revision="223a2421006e8f5da33f516f6891c87cae86b0f6"/>
   <!-- Stock Android things -->
   <project name="platform/abi/cpp" path="abi/cpp" revision="6426040f1be4a844082c9769171ce7f5341a5528"/>
   <project name="platform/bionic" path="bionic" revision="d2eb6c7b6e1bc7643c17df2d9d9bcb1704d0b9ab"/>
--- a/b2g/config/nexus-4/sources.xml
+++ b/b2g/config/nexus-4/sources.xml
@@ -12,20 +12,20 @@
   <!--original fetch url was https://git.mozilla.org/releases-->
   <remote fetch="https://git.mozilla.org/releases" name="mozillaorg"/>
   <!-- B2G specific things. -->
   <project name="platform_build" path="build" remote="b2g" revision="8986df0f82e15ac2798df0b6c2ee3435400677ac">
     <copyfile dest="Makefile" src="core/root.mk"/>
   </project>
   <project name="rilproxy" path="rilproxy" remote="b2g" revision="827214fcf38d6569aeb5c6d6f31cb296d1f09272"/>
   <project name="fake-libdvm" path="dalvik" remote="b2g" revision="d50ae982b19f42f0b66d08b9eb306be81687869f"/>
-  <project name="gaia" path="gaia" remote="mozillaorg" revision="a8a6eed2ba9d66239aac789b9ee4900f911c73cb"/>
+  <project name="gaia" path="gaia" remote="mozillaorg" revision="83f495a1c12687970f7f2840c2729795c4b88177"/>
   <project name="gonk-misc" path="gonk-misc" remote="b2g" revision="5883a99b6528ced9dafaed8d3ca2405fb285537e"/>
   <project name="moztt" path="external/moztt" remote="b2g" revision="562d357b72279a9e35d4af5aeecc8e1ffa2f44f1"/>
-  <project name="apitrace" path="external/apitrace" remote="apitrace" revision="4bc3cfde42118081268690217172d7b577867c65"/>
+  <project name="apitrace" path="external/apitrace" remote="apitrace" revision="693382a5630079f9debfe55c59f8197d432f47ff"/>
   <project name="valgrind" path="external/valgrind" remote="b2g" revision="daa61633c32b9606f58799a3186395fd2bbb8d8c"/>
   <project name="vex" path="external/VEX" remote="b2g" revision="47f031c320888fe9f3e656602588565b52d43010"/>
   <!-- Stock Android things -->
   <project groups="linux" name="platform/prebuilts/clang/linux-x86/3.1" path="prebuilts/clang/linux-x86/3.1" revision="5c45f43419d5582949284eee9cef0c43d866e03b"/>
   <project groups="linux" name="platform/prebuilts/clang/linux-x86/3.2" path="prebuilts/clang/linux-x86/3.2" revision="3748b4168e7bd8d46457d4b6786003bc6a5223ce"/>
   <project groups="linux" name="platform/prebuilts/gcc/linux-x86/host/i686-linux-glibc2.7-4.6" path="prebuilts/gcc/linux-x86/host/i686-linux-glibc2.7-4.6" revision="9025e50b9d29b3cabbbb21e1dd94d0d13121a17e"/>
   <project groups="linux" name="platform/prebuilts/gcc/linux-x86/host/x86_64-linux-glibc2.7-4.6" path="prebuilts/gcc/linux-x86/host/x86_64-linux-glibc2.7-4.6" revision="b89fda71fcd0fa0cf969310e75be3ea33e048b44"/>
   <project groups="linux,arm" name="platform/prebuilts/gcc/linux-x86/arm/arm-eabi-4.7" path="prebuilts/gcc/linux-x86/arm/arm-eabi-4.7" revision="2e7d5348f35575870b3c7e567a9a9f6d66f8d6c5"/>
--- a/b2g/config/wasabi/sources.xml
+++ b/b2g/config/wasabi/sources.xml
@@ -12,22 +12,22 @@
   <!--original fetch url was git://github.com/apitrace/-->
   <remote fetch="https://git.mozilla.org/external/apitrace" name="apitrace"/>
   <default remote="caf" revision="ics_chocolate_rb4.2" sync-j="4"/>
   <!-- Gonk specific things and forks -->
   <project name="platform_build" path="build" remote="b2g" revision="84923f1940625c47ff4c1fdf01b10fde3b7d909e">
     <copyfile dest="Makefile" src="core/root.mk"/>
   </project>
   <project name="fake-dalvik" path="dalvik" remote="b2g" revision="ca1f327d5acc198bb4be62fa51db2c039032c9ce"/>
-  <project name="gaia.git" path="gaia" remote="mozillaorg" revision="a8a6eed2ba9d66239aac789b9ee4900f911c73cb"/>
+  <project name="gaia.git" path="gaia" remote="mozillaorg" revision="83f495a1c12687970f7f2840c2729795c4b88177"/>
   <project name="gonk-misc" path="gonk-misc" remote="b2g" revision="5883a99b6528ced9dafaed8d3ca2405fb285537e"/>
   <project name="rilproxy" path="rilproxy" remote="b2g" revision="827214fcf38d6569aeb5c6d6f31cb296d1f09272"/>
   <project name="librecovery" path="librecovery" remote="b2g" revision="891e5069c0ad330d8191bf8c7b879c814258c89f"/>
   <project name="moztt" path="external/moztt" remote="b2g" revision="562d357b72279a9e35d4af5aeecc8e1ffa2f44f1"/>
-  <project name="apitrace" path="external/apitrace" remote="apitrace" revision="4bc3cfde42118081268690217172d7b577867c65"/>
+  <project name="apitrace" path="external/apitrace" remote="apitrace" revision="693382a5630079f9debfe55c59f8197d432f47ff"/>
   <project name="gonk-patches" path="patches" remote="b2g" revision="223a2421006e8f5da33f516f6891c87cae86b0f6"/>
   <!-- Stock Android things -->
   <project name="platform/abi/cpp" path="abi/cpp" revision="6426040f1be4a844082c9769171ce7f5341a5528"/>
   <project name="platform/bionic" path="bionic" revision="cd5dfce80bc3f0139a56b58aca633202ccaee7f8"/>
   <project name="platform/bootable/recovery" path="bootable/recovery" revision="e0a9ac010df3afaa47ba107192c05ac8b5516435"/>
   <project name="platform/development" path="development" revision="a384622f5fcb1d2bebb9102591ff7ae91fe8ed2d"/>
   <project name="device/common" path="device/common" revision="7c65ea240157763b8ded6154a17d3c033167afb7"/>
   <project name="device/sample" path="device/sample" revision="c328f3d4409db801628861baa8d279fb8855892f"/>
--- a/browser/base/content/browser.css
+++ b/browser/base/content/browser.css
@@ -247,16 +247,21 @@ toolbar[customizing] > .overflow-button 
 %ifdef XP_WIN
 #main-window[sizemode="maximized"] #titlebar-buttonbox {
   -moz-appearance: -moz-window-button-box-maximized;
 }
 %endif
 
 %endif
 
+#main-window[inFullscreen] #global-notificationbox,
+#main-window[inFullscreen] #high-priority-global-notificationbox {
+  visibility: collapse;
+}
+
 /* Rules to help integrate SDK widgets */
 toolbaritem[sdkstylewidget="true"] > toolbarbutton,
 toolbarpaletteitem > toolbaritem[sdkstylewidget="true"] > iframe,
 toolbarpaletteitem > toolbaritem[sdkstylewidget="true"] > .toolbarbutton-text {
   display: none;
 }
 
 toolbarpaletteitem:-moz-any([place="palette"], [place="panel"]) > toolbaritem[sdkstylewidget="true"] > toolbarbutton {
@@ -819,33 +824,25 @@ html|*#gcli-output-frame,
 .browserStack[responsivemode] {
   transition-property: min-width, max-width, min-height, max-height;
 }
 
 .browserStack[responsivemode][notransition] {
   transition: none;
 }
 
-.toolbarbutton-badge[badge]:not([badge=""])::after {
-  content: attr(badge);
-}
-
-toolbarbutton[type="badged"] {
-  -moz-binding: url("chrome://browser/content/urlbarBindings.xml#toolbarbutton-badged");
-}
-
 toolbarbutton[type="socialmark"] {
   -moz-binding: url("chrome://browser/content/socialmarks.xml#toolbarbutton-marks");
 }
 
-toolbarbutton[type="badged"] > .toolbarbutton-badge-container > .toolbarbutton-icon,
+toolbarbutton.badged-button > .toolbarbutton-badge-container > .toolbarbutton-icon,
 toolbarbutton[type="socialmark"] > .toolbarbutton-icon {
   max-width: 16px;
 }
-toolbarpaletteitem[place="palette"] > toolbarbutton[type="badged"] > .toolbarbutton-badge-container > .toolbarbutton-icon {
+toolbarpaletteitem[place="palette"] > toolbarbutton.badged-button > .toolbarbutton-badge-container > .toolbarbutton-icon {
   max-width: 32px;
 }
 
 panelview > .social-panel-frame {
   width: auto;
   height: auto;
 }
 
--- a/browser/base/content/newtab/newTab.xul
+++ b/browser/base/content/newtab/newTab.xul
@@ -91,12 +91,12 @@
     </div>
 
     <div id="newtab-intro-what">&newtab.customize.what;</div>
 
     <input id="newtab-customize-button" type="button" title="&newtab.customize.title;"/>
   </div>
 
   <xul:script type="text/javascript;version=1.8"
-              src="chrome://browser/content/newtab/newTab.js"/>
+              src="chrome://browser/content/searchSuggestionUI.js"/>
   <xul:script type="text/javascript;version=1.8"
-              src="chrome://browser/content/searchSuggestionUI.js"/>
+              src="chrome://browser/content/newtab/newTab.js"/>
 </xul:window>
--- a/browser/base/content/urlbarBindings.xml
+++ b/browser/base/content/urlbarBindings.xml
@@ -2576,25 +2576,9 @@
               this._promomessage.firstChild.textContent = this._notificationMessage;
               this._promomessage.height = this._promomessage.getBoundingClientRect().height;
             }.bind(this), true);
           }
         ]]></body>
       </method>
     </implementation>
   </binding>
-
-  <binding id="toolbarbutton-badged" display="xul:button"
-           extends="chrome://global/content/bindings/toolbarbutton.xml#toolbarbutton">
-    <content>
-      <children includes="observes|template|menupopup|panel|tooltip"/>
-      <xul:hbox class="toolbarbutton-badge-container" align="start" pack="end">
-        <xul:hbox class="toolbarbutton-badge" xbl:inherits="badge"/>
-        <xul:image class="toolbarbutton-icon" xbl:inherits="validate,src=image,label"/>
-      </xul:hbox>
-      <xul:label class="toolbarbutton-text" crop="right" flex="1"
-                 xbl:inherits="value=label,accesskey,crop,wrap"/>
-      <xul:label class="toolbarbutton-multiline-text" flex="1"
-                 xbl:inherits="xbl:text=label,accesskey,wrap"/>
-    </content>
-  </binding>
-
 </bindings>
--- a/browser/components/customizableui/CustomizableWidgets.jsm
+++ b/browser/components/customizableui/CustomizableWidgets.jsm
@@ -910,17 +910,17 @@ const CustomizableWidgets = [
     tooltiptext: "loop-call-button.tooltiptext",
     defaultArea: CustomizableUI.AREA_NAVBAR,
     introducedInVersion: 1,
     onBuild: function(aDocument) {
       let node = aDocument.createElementNS(kNSXUL, "toolbarbutton");
       node.setAttribute("id", this.id);
       node.classList.add("toolbarbutton-1");
       node.classList.add("chromeclass-toolbar-additional");
-      node.setAttribute("type", "badged");
+      node.classList.add("badged-button");
       node.setAttribute("label", CustomizableUI.getLocalizedProperty(this, "label"));
       node.setAttribute("tooltiptext", CustomizableUI.getLocalizedProperty(this, "tooltiptext"));
       node.setAttribute("removable", "true");
       node.addEventListener("command", function(event) {
         aDocument.defaultView.LoopUI.openCallPanel(event);
       });
       return node;
     }
--- a/browser/components/customizableui/test/browser.ini
+++ b/browser/components/customizableui/test/browser.ini
@@ -108,16 +108,17 @@ skip-if = e10s # Bug ?????? - test uses 
 [browser_967000_button_tabView.js]
 [browser_968447_bookmarks_toolbar_items_in_panel.js]
 skip-if = os == "linux" # Intemittent failures - bug 979207
 [browser_968565_insert_before_hidden_items.js]
 [browser_969427_recreate_destroyed_widget_after_reset.js]
 [browser_969661_character_encoding_navbar_disabled.js]
 [browser_970511_undo_restore_default.js]
 [browser_972267_customizationchange_events.js]
+[browser_973641_button_addon.js]
 [browser_973932_addonbar_currentset.js]
 [browser_975719_customtoolbars_behaviour.js]
 
 [browser_976792_insertNodeInWindow.js]
 skip-if = os == "linux"
 
 [browser_978084_dragEnd_after_move.js]
 [browser_980155_add_overflow_toolbar.js]
new file mode 100755
--- /dev/null
+++ b/browser/components/customizableui/test/browser_973641_button_addon.js
@@ -0,0 +1,72 @@
+/* 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/. */
+
+"use strict";
+
+const kButton = "test_button_for_addon";
+let initialLocation = gBrowser.currentURI.spec;
+
+add_task(function() {
+  info("Check addon button functionality");
+
+  // create mocked addon button on the navigation bar
+  let widgetSpec = {
+    id: kButton,
+    type: 'button',
+    onClick: function() {
+      gBrowser.selectedTab = gBrowser.addTab("about:addons");
+    }
+  };
+  CustomizableUI.createWidget(widgetSpec);
+  CustomizableUI.addWidgetToArea(kButton, CustomizableUI.AREA_NAVBAR);
+
+  // check the button's functionality in navigation bar
+  let addonButton = document.getElementById(kButton);
+  let navBar = document.getElementById("nav-bar");
+  ok(addonButton, "Addon button exists");
+  ok(navBar.contains(addonButton), "Addon button is in the navbar");
+  yield checkButtonFunctionality(addonButton);
+
+  resetTabs();
+
+  //move the add-on button in the Panel Menu
+  CustomizableUI.addWidgetToArea(kButton, CustomizableUI.AREA_PANEL);
+  let addonButtonInNavbar = navBar.getElementsByAttribute("id", kButton);
+  ok(!navBar.contains(addonButton), "Addon button was removed from the browser bar");
+
+  // check the addon button's functionality in the Panel Menu
+  yield PanelUI.show();
+  var panelMenu = document.getElementById("PanelUI-mainView");
+  let addonButtonInPanel = panelMenu.getElementsByAttribute("id", kButton);
+  ok(panelMenu.contains(addonButton), "Addon button was added to the Panel Menu");
+  yield checkButtonFunctionality(addonButtonInPanel[0]);
+});
+
+add_task(function asyncCleanup() {
+  resetTabs();
+
+  // reset the UI to the default state
+  yield resetCustomization();
+  ok(CustomizableUI.inDefaultState, "The UI is in default state again.");
+
+  // destroy the widget
+  CustomizableUI.destroyWidget(kButton);
+});
+
+function resetTabs() {
+  //close all opened tabs
+  while(gBrowser.tabs.length > 1) {
+    gBrowser.removeTab(gBrowser.selectedTab);
+  }
+
+  //restore the initial tab
+  gBrowser.addTab(initialLocation);
+  gBrowser.removeTab(gBrowser.selectedTab);
+}
+
+function checkButtonFunctionality(aButton) {
+  aButton.click();
+  yield waitForCondition(() => gBrowser.currentURI &&
+                               gBrowser.currentURI.spec == "about:addons");
+}
--- a/browser/devtools/app-manager/content/index.js
+++ b/browser/devtools/app-manager/content/index.js
@@ -1,20 +1,21 @@
 /* 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/. */
 
-const Cu = Components.utils;
+const {utils: Cu, interfaces: Ci} = Components;
 Cu.import("resource:///modules/devtools/gDevTools.jsm");
 const {devtools} = Cu.import("resource://gre/modules/devtools/Loader.jsm", {});
 const {require} = devtools;
 const {ConnectionManager, Connection} = require("devtools/client/connection-manager");
 const promise = require("devtools/toolkit/deprecated-sync-thenables");
-const prefs = require('sdk/preferences/service');
-
+const prefs = require("sdk/preferences/service");
+const Services = require("Services");
+const Strings = Services.strings.createBundle("chrome://browser/locale/devtools/app-manager.properties");
 
 let UI = {
   _toolboxTabCursor: 0,
   _handledTargets: new Map(),
 
   connection: null,
 
   init: function() {
@@ -29,16 +30,17 @@ let UI = {
     window.addEventListener("message", this.onMessage);
   },
 
   onLoad: function() {
     window.removeEventListener("load", this.onLoad);
     let defaultPanel = prefs.get("devtools.appmanager.lastTab");
     let panelExists = !!document.querySelector("." + defaultPanel  + "-panel");
     this.selectTab(panelExists ? defaultPanel : "projects");
+    this.showDeprecationNotice();
   },
 
   onUnload: function() {
     for (let [target, toolbox] of this._handledTargets) {
       toolbox.destroy();
     }
 
     window.removeEventListener("unload", this.onUnload);
@@ -173,12 +175,38 @@ let UI = {
         this._handledTargets.set(target, toolbox);
         toolbox.once("destroyed", () => {
           this._handledTargets.delete(target)
         });
       });
     } else {
       return gDevTools.showToolbox(target, null, host);
     }
+  },
+
+  showDeprecationNotice: function() {
+    let message = Strings.GetStringFromName("index.deprecationNotice");
+
+    let buttons = [
+      {
+        label: Strings.GetStringFromName("index.launchWebIDE"),
+        callback: gDevToolsBrowser.openWebIDE
+      },
+      {
+        label: Strings.GetStringFromName("index.readMoreAboutWebIDE"),
+        callback: () => {
+          window.open("https://developer.mozilla.org/docs/Tools/WebIDE");
+        }
+      }
+    ];
+
+    let docShell = window.QueryInterface(Ci.nsIInterfaceRequestor)
+                   .getInterface(Ci.nsIWebNavigation)
+                   .QueryInterface(Ci.nsIDocShell);
+    let browser = docShell.chromeEventHandler;
+    let nbox = browser.ownerDocument.defaultView.gBrowser
+               .getNotificationBox(browser);
+    nbox.appendNotification(message, "app-manager-deprecation", null,
+                            nbox.PRIORITY_WARNING_LOW, buttons);
   }
-}
+};
 
 UI.init();
--- a/browser/devtools/netmonitor/netmonitor-view.js
+++ b/browser/devtools/netmonitor/netmonitor-view.js
@@ -365,30 +365,33 @@ RequestsMenuView.prototype = Heritage.ex
     this.requestsMenuSortEvent = getKeyWithEvent(this.sortBy.bind(this));
     this.requestsMenuFilterEvent = getKeyWithEvent(this.filterOn.bind(this));
     this.reqeustsMenuClearEvent = this.clear.bind(this);
     this._onContextShowing = this._onContextShowing.bind(this);
     this._onContextNewTabCommand = this.openRequestInTab.bind(this);
     this._onContextCopyUrlCommand = this.copyUrl.bind(this);
     this._onContextCopyImageAsDataUriCommand = this.copyImageAsDataUri.bind(this);
     this._onContextResendCommand = this.cloneSelectedRequest.bind(this);
+    this._onContextToggleRawHeadersCommand = this.toggleRawHeaders.bind(this);
     this._onContextPerfCommand = () => NetMonitorView.toggleFrontendMode();
     this._onReloadCommand = () => NetMonitorView.reloadPage();
 
     this.sendCustomRequestEvent = this.sendCustomRequest.bind(this);
     this.closeCustomRequestEvent = this.closeCustomRequest.bind(this);
     this.cloneSelectedRequestEvent = this.cloneSelectedRequest.bind(this);
+    this.toggleRawHeadersEvent = this.toggleRawHeaders.bind(this);
 
     $("#toolbar-labels").addEventListener("click", this.requestsMenuSortEvent, false);
     $("#requests-menu-footer").addEventListener("click", this.requestsMenuFilterEvent, false);
     $("#requests-menu-clear-button").addEventListener("click", this.reqeustsMenuClearEvent, false);
     $("#network-request-popup").addEventListener("popupshowing", this._onContextShowing, false);
     $("#request-menu-context-newtab").addEventListener("command", this._onContextNewTabCommand, false);
     $("#request-menu-context-copy-url").addEventListener("command", this._onContextCopyUrlCommand, false);
     $("#request-menu-context-copy-image-as-data-uri").addEventListener("command", this._onContextCopyImageAsDataUriCommand, false);
+    $("#toggle-raw-headers").addEventListener("click", this.toggleRawHeadersEvent, false);
 
     window.once("connected", this._onConnect.bind(this));
   },
 
   _onConnect: function() {
     $("#requests-menu-reload-notice-button").addEventListener("command", this._onReloadCommand, false);
 
     if (NetMonitorController.supportsCustomRequest) {
@@ -442,16 +445,17 @@ RequestsMenuView.prototype = Heritage.ex
     $("#requests-menu-perf-notice-button").removeEventListener("command", this._onContextPerfCommand, false);
     $("#requests-menu-network-summary-button").removeEventListener("command", this._onContextPerfCommand, false);
     $("#requests-menu-network-summary-label").removeEventListener("click", this._onContextPerfCommand, false);
     $("#network-statistics-back-button").removeEventListener("command", this._onContextPerfCommand, false);
 
     $("#custom-request-send-button").removeEventListener("click", this.sendCustomRequestEvent, false);
     $("#custom-request-close-button").removeEventListener("click", this.closeCustomRequestEvent, false);
     $("#headers-summary-resend").removeEventListener("click", this.cloneSelectedRequestEvent, false);
+    $("#toggle-raw-headers").removeEventListener("click", this.toggleRawHeadersEvent, false);
   },
 
   /**
    * Resets this container (removes all the networking information).
    */
   reset: function() {
     this.empty();
     this._firstRequestStartedMillis = -1;
@@ -634,16 +638,38 @@ RequestsMenuView.prototype = Heritage.ex
    * Remove the currently selected custom request.
    */
   closeCustomRequest: function() {
     this.remove(this.selectedItem);
     NetMonitorView.Sidebar.toggle(false);
   },
 
   /**
+   * Shows raw request/response headers in textboxes.
+   */
+  toggleRawHeaders: function() {
+    let requestTextarea = $("#raw-request-headers-textarea");
+    let responseTextare = $("#raw-response-headers-textarea");
+    let rawHeadersHidden = $("#raw-headers").getAttribute("hidden");
+
+    if (rawHeadersHidden) {
+      let selected = this.selectedItem.attachment;
+      let selectedRequestHeaders = selected.requestHeaders.headers;
+      let selectedResponseHeaders = selected.responseHeaders.headers;
+      requestTextarea.value = writeHeaderText(selectedRequestHeaders);
+      responseTextare.value = writeHeaderText(selectedResponseHeaders);
+      $("#raw-headers").hidden = false;
+    } else {
+      requestTextarea.value = null;
+      responseTextare.value = null;
+      $("#raw-headers").hidden = true;
+    }
+  },
+
+  /**
    * Filters all network requests in this container by a specified type.
    *
    * @param string aType
    *        Either "all", "html", "css", "js", "xhr", "fonts", "images", "media"
    *        "flash" or "other".
    */
   filterOn: function(aType = "all") {
     if (aType === "all") {
@@ -2008,16 +2034,17 @@ NetworkDetailsView.prototype = {
    */
   populate: function(aData) {
     $("#request-params-box").setAttribute("flex", "1");
     $("#request-params-box").hidden = false;
     $("#request-post-data-textarea-box").hidden = true;
     $("#response-content-info-header").hidden = true;
     $("#response-content-json-box").hidden = true;
     $("#response-content-textarea-box").hidden = true;
+    $("#raw-headers").hidden = true;
     $("#response-content-image-box").hidden = true;
 
     let isHtml = RequestsMenuView.prototype.isHtml({ attachment: aData });
 
     // Show the "Preview" tabpanel only for plain HTML responses.
     $("#preview-tab").hidden = !isHtml;
     $("#preview-tabpanel").hidden = !isHtml;
 
--- a/browser/devtools/netmonitor/netmonitor.xul
+++ b/browser/devtools/netmonitor/netmonitor.xul
@@ -302,27 +302,49 @@
                          class="requests-menu-status"/>
                     <label id="headers-summary-status-value"
                            class="plain tabpanel-summary-value devtools-monospace"
                            crop="end"
                            flex="1"/>
                     <button id="headers-summary-resend"
                             class="devtools-toolbarbutton"
                             label="&netmonitorUI.summary.editAndResend;"/>
+                    <button id="toggle-raw-headers"
+                            class="devtools-toolbarbutton"
+                            label="&netmonitorUI.summary.rawHeaders;"/>
                   </hbox>
                   <hbox id="headers-summary-version"
                         class="tabpanel-summary-container"
                         align="center">
                     <label class="plain tabpanel-summary-label"
                            value="&netmonitorUI.summary.version;"/>
                     <label id="headers-summary-version-value"
                            class="plain tabpanel-summary-value devtools-monospace"
                            crop="end"
                            flex="1"/>
                   </hbox>
+                  <hbox id="raw-headers"
+                        class="tabpanel-summary-container"
+                        align="center"
+                        hidden="true">
+                    <vbox id="raw-request-headers-textarea-box" flex="1" hidden="false">
+                      <label class="plain tabpanel-summary-label"
+                        value="&netmonitorUI.summary.rawHeaders.requestHeaders;"/>
+                      <textbox id="raw-request-headers-textarea"
+                        class="raw-response-textarea"
+                        flex="1" multiline="true" readonly="true"/>
+                    </vbox>
+                    <vbox id="raw-response-headers-textarea-box" flex="1" hidden="false">
+                      <label class="plain tabpanel-summary-label"
+                        value="&netmonitorUI.summary.rawHeaders.responseHeaders;"/>
+                      <textbox id="raw-response-headers-textarea"
+                        class="raw-response-textarea"
+                        flex="1" multiline="true" readonly="true"/>
+                    </vbox>
+                  </hbox>
                   <vbox id="all-headers" flex="1"/>
                 </vbox>
               </tabpanel>
               <tabpanel id="cookies-tabpanel"
                         class="tabpanel-content">
                 <vbox flex="1">
                   <vbox id="all-cookies" flex="1"/>
                 </vbox>
--- a/browser/devtools/netmonitor/test/browser.ini
+++ b/browser/devtools/netmonitor/test/browser.ini
@@ -72,16 +72,17 @@ skip-if= buildapp == 'mulet'
 [browser_net_page-nav.js]
 [browser_net_pane-collapse.js]
 [browser_net_pane-toggle.js]
 [browser_net_post-data-01.js]
 [browser_net_post-data-02.js]
 [browser_net_post-data-03.js]
 [browser_net_prefs-and-l10n.js]
 [browser_net_prefs-reload.js]
+[browser_net_raw_headers.js]
 [browser_net_reload-button.js]
 [browser_net_req-resp-bodies.js]
 [browser_net_resend.js]
 [browser_net_simple-init.js]
 [browser_net_simple-request-data.js]
 [browser_net_simple-request-details.js]
 [browser_net_simple-request.js]
 [browser_net_sort-01.js]
new file mode 100644
--- /dev/null
+++ b/browser/devtools/netmonitor/test/browser_net_raw_headers.js
@@ -0,0 +1,72 @@
+/* Any copyright is dedicated to the Public Domain.
+   http://creativecommons.org/publicdomain/zero/1.0/ */
+
+let gPanelWin;
+let gPanelDoc;
+
+/**
+ * Tests if showing raw headers works.
+ */
+
+function test() {
+  initNetMonitor(POST_DATA_URL).then(([aTab, aDebuggee, aMonitor]) => {
+    info("Starting test... ");
+
+    gPanelWin = aMonitor.panelWin;
+    gPanelDoc = gPanelWin.document;
+
+    let { document, Editor, NetMonitorView } = gPanelWin;
+    let { RequestsMenu } = NetMonitorView;
+    let TAB_UPDATED = gPanelWin.EVENTS.TAB_UPDATED;
+
+    RequestsMenu.lazyUpdate = false;
+
+    waitForNetworkEvents(aMonitor, 0, 2).then(() => {
+      let origItem = RequestsMenu.getItemAtIndex(0);
+      RequestsMenu.selectedItem = origItem;
+
+      waitFor(aMonitor.panelWin, TAB_UPDATED).then(() => {
+        EventUtils.sendMouseEvent({ type: "click" }, document.getElementById("toggle-raw-headers"));
+        testShowRawHeaders(origItem.attachment);
+        EventUtils.sendMouseEvent({ type: "click" }, document.getElementById("toggle-raw-headers"));
+        testHideRawHeaders(document);
+        finishUp(aMonitor);
+      });
+    });
+
+    aDebuggee.performRequests();
+  });
+}
+
+/*
+ * Tests that raw headers were displayed correctly
+ */
+function testShowRawHeaders(aData) {
+  let requestHeaders = gPanelDoc.getElementById("raw-request-headers-textarea").value;
+  for (let header of aData.requestHeaders.headers) {
+    ok(requestHeaders.indexOf(header.name + ": " + header.value) >= 0, "textarea contains request headers");
+  }
+  let responseHeaders = gPanelDoc.getElementById("raw-response-headers-textarea").value;
+  for (let header of aData.responseHeaders.headers) {
+    ok(responseHeaders.indexOf(header.name + ": " + header.value) >= 0, "textarea contains response headers");
+  }
+}
+
+/*
+ * Tests that raw headers textareas are hidden and empty
+ */
+function testHideRawHeaders(document) {
+  let rawHeadersHidden = document.getElementById("raw-headers").getAttribute("hidden");
+  let requestTextarea = document.getElementById("raw-request-headers-textarea");
+  let responseTextare = document.getElementById("raw-response-headers-textarea");
+  ok(rawHeadersHidden, "raw headers textareas are hidden");
+  ok(requestTextarea.value == '', "raw request headers textarea is empty");
+  ok(responseTextare.value == '', "raw response headers textarea is empty");
+}
+
+function finishUp(aMonitor) {
+  gPanelWin = null;
+  gPanelDoc = null;
+
+  teardown(aMonitor).then(finish);
+}
--- a/browser/devtools/profiler/profiler.xul
+++ b/browser/devtools/profiler/profiler.xul
@@ -102,21 +102,29 @@
     <tabpanel id="profile-content-tabpanel-template">
       <vbox class="framerate"/>
       <vbox class="categories"/>
       <vbox class="call-tree" flex="1">
         <hbox class="call-tree-headers-container">
           <label class="plain call-tree-header"
                  type="duration"
                  crop="end"
-                 value="&profilerUI.table.duration;"/>
+                 value="&profilerUI.table.totalDuration;"/>
+          <label class="plain call-tree-header"
+                 type="self-duration"
+                 crop="end"
+                 value="&profilerUI.table.selfDuration;"/>
           <label class="plain call-tree-header"
                  type="percentage"
                  crop="end"
-                 value="&profilerUI.table.percentage;"/>
+                 value="&profilerUI.table.totalPercentage;"/>
+          <label class="plain call-tree-header"
+                 type="self-percentage"
+                 crop="end"
+                 value="&profilerUI.table.selfPercentage;"/>
           <label class="plain call-tree-header"
                  type="samples"
                  crop="end"
                  value="&profilerUI.table.samples;"/>
           <label class="plain call-tree-header"
                  type="function"
                  crop="end"
                  value="&profilerUI.table.function;"/>
--- a/browser/devtools/profiler/test/browser_profiler_tree-view-01.js
+++ b/browser/devtools/profiler/test/browser_profiler_tree-view-01.js
@@ -17,39 +17,49 @@ function test() {
   treeRoot.autoExpandDepth = 0;
   treeRoot.attachTo(container);
 
   is(container.childNodes.length, 1,
     "The container node should have one child available.");
   is(container.childNodes[0].className, "call-tree-item",
     "The root node in the tree has the correct class name.");
 
-  is(container.childNodes[0].childNodes.length, 4,
+  is(container.childNodes[0].childNodes.length, 6,
     "The root node in the tree has the correct number of children.");
-  is(container.childNodes[0].querySelectorAll(".call-tree-cell").length, 4,
+  is(container.childNodes[0].querySelectorAll(".call-tree-cell").length, 6,
     "The root node in the tree has only 'call-tree-cell' children.");
 
   is(container.childNodes[0].childNodes[0].getAttribute("type"), "duration",
     "The root node in the tree has a duration cell.");
   is(container.childNodes[0].childNodes[0].getAttribute("value"), "18",
     "The root node in the tree has the correct duration cell value.");
 
-  is(container.childNodes[0].childNodes[1].getAttribute("type"), "percentage",
+  is(container.childNodes[0].childNodes[1].getAttribute("type"), "self-duration",
+    "The root node in the tree has a self-duration cell.");
+  is(container.childNodes[0].childNodes[1].getAttribute("value"), "0",
+    "The root node in the tree has the correct self-duration cell value.");
+
+  is(container.childNodes[0].childNodes[2].getAttribute("type"), "percentage",
     "The root node in the tree has a percentage cell.");
-  is(container.childNodes[0].childNodes[1].getAttribute("value"), "100%",
+  is(container.childNodes[0].childNodes[2].getAttribute("value"), "100%",
     "The root node in the tree has the correct percentage cell value.");
 
-  is(container.childNodes[0].childNodes[2].getAttribute("type"), "samples",
+  is(container.childNodes[0].childNodes[3].getAttribute("type"), "self-percentage",
+    "The root node in the tree has a self-percentage cell.");
+  is(container.childNodes[0].childNodes[3].getAttribute("value"), "0%",
+    "The root node in the tree has the correct self-percentage cell value.");
+
+  is(container.childNodes[0].childNodes[4].getAttribute("type"), "samples",
     "The root node in the tree has an samples cell.");
-  is(container.childNodes[0].childNodes[2].getAttribute("value"), "3",
+  is(container.childNodes[0].childNodes[4].getAttribute("value"), "3",
     "The root node in the tree has the correct samples cell value.");
 
-  is(container.childNodes[0].childNodes[3].getAttribute("type"), "function",
+  is(container.childNodes[0].childNodes[5].getAttribute("type"), "function",
     "The root node in the tree has a function cell.");
-  is(container.childNodes[0].childNodes[3].style.MozMarginStart, "0px",
+  is(container.childNodes[0].childNodes[5].style.MozMarginStart, "0px",
     "The root node in the tree has the correct indentation.");
 
   finish();
 }
 
 let gSamples = [{
   time: 5,
   frames: [
--- a/browser/devtools/profiler/test/browser_profiler_tree-view-04.js
+++ b/browser/devtools/profiler/test/browser_profiler_tree-view-04.js
@@ -37,28 +37,32 @@ function test() {
     "The .A.B.C node's 'category' attribute is correct.");
   is(C.target.getAttribute("tooltiptext"), "D (http://foo/bar/baz:78)",
     "The .A.B.C node's 'tooltiptext' attribute is correct.");
   ok(!A.target.querySelector(".call-tree-zoom").hidden,
     "The .A.B.C node's zoom button cell should not be hidden.");
   ok(!A.target.querySelector(".call-tree-category").hidden,
     "The .A.B.C node's category label cell should not be hidden.");
 
-  is(C.target.childNodes.length, 4,
+  is(C.target.childNodes.length, 6,
     "The number of columns displayed for tree items is correct.");
   is(C.target.childNodes[0].getAttribute("type"), "duration",
     "The first column displayed for tree items is correct.");
-  is(C.target.childNodes[1].getAttribute("type"), "percentage",
+  is(C.target.childNodes[1].getAttribute("type"), "self-duration",
     "The second column displayed for tree items is correct.");
-  is(C.target.childNodes[2].getAttribute("type"), "samples",
+  is(C.target.childNodes[2].getAttribute("type"), "percentage",
     "The third column displayed for tree items is correct.");
-  is(C.target.childNodes[3].getAttribute("type"), "function",
+  is(C.target.childNodes[3].getAttribute("type"), "self-percentage",
     "The fourth column displayed for tree items is correct.");
+  is(C.target.childNodes[4].getAttribute("type"), "samples",
+    "The fifth column displayed for tree items is correct.");
+  is(C.target.childNodes[5].getAttribute("type"), "function",
+    "The sixth column displayed for tree items is correct.");
 
-  let functionCell = C.target.childNodes[3];
+  let functionCell = C.target.childNodes[5];
 
   is(functionCell.childNodes.length, 8,
     "The number of columns displayed for function cells is correct.");
   is(functionCell.childNodes[0].className, "arrow theme-twisty",
     "The first node displayed for function cells is correct.");
   is(functionCell.childNodes[1].className, "plain call-tree-name",
     "The second node displayed for function cells is correct.");
   is(functionCell.childNodes[2].className, "plain call-tree-url",
--- a/browser/devtools/profiler/utils/tree-view.js
+++ b/browser/devtools/profiler/utils/tree-view.js
@@ -13,16 +13,19 @@ loader.lazyImporter(this, "Heritage",
 loader.lazyImporter(this, "AbstractTreeItem",
   "resource:///modules/devtools/AbstractTreeItem.jsm");
 
 const URL_LABEL_TOOLTIP = L10N.getStr("table.url.tooltiptext");
 const ZOOM_BUTTON_TOOLTIP = L10N.getStr("table.zoom.tooltiptext");
 const CALL_TREE_INDENTATION = 16; // px
 const CALL_TREE_AUTO_EXPAND = 3; // depth
 
+const clamp = (val, min, max) => Math.max(min, Math.min(max, val));
+const sum = vals => vals.reduce((a, b) => a + b, 0);
+
 exports.CallView = CallView;
 
 /**
  * An item in a call tree view, which looks like this:
  *
  *   Time (ms)  |   Cost   | Calls | Function
  * ============================================================================
  *     1,000.00 |  100.00% |       | â–¼ (root)
@@ -58,79 +61,102 @@ CallView.prototype = Heritage.extend(Abs
    * @param nsIDOMNode document
    * @param nsIDOMNode arrowNode
    * @return nsIDOMNode
    */
   _displaySelf: function(document, arrowNode) {
     this.document = document;
 
     let frameInfo = this.frame.getInfo();
-    let framePercentage = this.frame.samples / this.root.frame.samples * 100;
+    let framePercentage = this._getPercentage(this.frame.samples);
+    let childrenPercentage = sum([this._getPercentage(c.samples)
+                                  for (c of this._getChildCalls())]);
+    let selfPercentage = clamp(framePercentage - childrenPercentage, 0, 100);
+    let selfDuration = this.frame.duration - sum([c.duration
+                                                  for (c of this._getChildCalls())]);
 
     let durationCell = this._createTimeCell(this.frame.duration);
+    let selfDurationCell = this._createTimeCell(selfDuration, true);
     let percentageCell = this._createExecutionCell(framePercentage);
+    let selfPercentageCell = this._createExecutionCell(selfPercentage, true);
     let samplesCell = this._createSamplesCell(this.frame.samples);
     let functionCell = this._createFunctionCell(arrowNode, frameInfo, this.level);
 
     let targetNode = document.createElement("hbox");
     targetNode.className = "call-tree-item";
     targetNode.setAttribute("origin", frameInfo.isContent ? "content" : "chrome");
     targetNode.setAttribute("category", frameInfo.categoryData.abbrev || "");
     targetNode.setAttribute("tooltiptext", this.frame.location || "");
 
     let isRoot = frameInfo.nodeType == "Thread";
     if (isRoot) {
       functionCell.querySelector(".call-tree-zoom").hidden = true;
       functionCell.querySelector(".call-tree-category").hidden = true;
     }
 
     targetNode.appendChild(durationCell);
+    targetNode.appendChild(selfDurationCell);
     targetNode.appendChild(percentageCell);
+    targetNode.appendChild(selfPercentageCell);
     targetNode.appendChild(samplesCell);
     targetNode.appendChild(functionCell);
 
     return targetNode;
   },
 
   /**
+   * Calculate what percentage of all samples the given number of samples is.
+   */
+  _getPercentage: function (samples) {
+    return samples / this.root.frame.samples * 100;
+  },
+
+  /**
+   * Return an array of this frame's child calls.
+   */
+  _getChildCalls: function () {
+    return Object.keys(this.frame.calls).map(k => this.frame.calls[k]);
+  },
+
+  /**
    * Populates this node in the call tree with the corresponding "callees".
    * These are defined in the `frame` data source for this call view.
    * @param array:AbstractTreeItem children
    */
   _populateSelf: function(children) {
     let newLevel = this.level + 1;
 
-    for (let [, newFrame] of _Iterator(this.frame.calls)) {
+    for (let newFrame of this._getChildCalls()) {
       children.push(new CallView({
         caller: this,
         frame: newFrame,
         level: newLevel
       }));
     }
 
     // Sort the "callees" asc. by duration, before inserting them in the tree.
     children.sort((a, b) => a.frame.duration < b.frame.duration ? 1 : -1);
   },
 
   /**
    * Functions creating each cell in this call view.
    * Invoked by `_displaySelf`.
    */
-  _createTimeCell: function(duration) {
+  _createTimeCell: function(duration, isSelf = false) {
     let cell = this.document.createElement("label");
     cell.className = "plain call-tree-cell";
-    cell.setAttribute("type", "duration");
+    cell.setAttribute("type", isSelf ? "self-duration" : "duration");
     cell.setAttribute("crop", "end");
     cell.setAttribute("value", L10N.numberWithDecimals(duration, 2));
     return cell;
   },
-  _createExecutionCell: function(percentage) {
+  _createExecutionCell: function(percentage, isSelf = false) {
     let cell = this.document.createElement("label");
     cell.className = "plain call-tree-cell";
-    cell.setAttribute("type", "percentage");
+    cell.setAttribute("type", isSelf ? "self-percentage" : "percentage");
     cell.setAttribute("crop", "end");
     cell.setAttribute("value", L10N.numberWithDecimals(percentage, 2) + "%");
     return cell;
   },
   _createSamplesCell: function(count) {
     let cell = this.document.createElement("label");
     cell.className = "plain call-tree-cell";
     cell.setAttribute("type", "samples");
--- a/browser/devtools/webide/content/webide.js
+++ b/browser/devtools/webide/content/webide.js
@@ -747,27 +747,30 @@ let UI = {
     document.querySelector("#cmd_importHostedApp").removeAttribute("disabled");
     document.querySelector("#cmd_showProjectPanel").removeAttribute("disabled");
     document.querySelector("#cmd_showRuntimePanel").removeAttribute("disabled");
 
     // Action commands
     let playCmd = document.querySelector("#cmd_play");
     let stopCmd = document.querySelector("#cmd_stop");
     let debugCmd = document.querySelector("#cmd_toggleToolbox");
+    let playButton = document.querySelector('#action-button-play');
 
     if (!AppManager.selectedProject || AppManager.connection.status != Connection.Status.CONNECTED) {
       playCmd.setAttribute("disabled", "true");
       stopCmd.setAttribute("disabled", "true");
       debugCmd.setAttribute("disabled", "true");
     } else {
       let isProjectRunning = AppManager.isProjectRunning();
       if (isProjectRunning) {
+        playButton.classList.add("reload");
         stopCmd.removeAttribute("disabled");
         debugCmd.removeAttribute("disabled");
       } else {
+        playButton.classList.remove("reload");
         stopCmd.setAttribute("disabled", "true");
         debugCmd.setAttribute("disabled", "true");
       }
 
       // If connected and a project is selected
       if (AppManager.selectedProject.type == "runtimeApp") {
         playCmd.removeAttribute("disabled");
       } else if (AppManager.selectedProject.type == "tab") {
index 3ef9c16d899d40a732606bf2bf745480922c4e0c..d09c7b5deece58f3f7ad90135b6da8d07b8e267c
GIT binary patch
literal 29618
zc${qf1yodD^gn<KBGRdJr$~4AkRu==NOw0#mxOe8igbg((8x$icgT<q3?0%9Z@};G
z_x``P-h#F6+~M4P_TFdb`J79{du2IHG!n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es/webide.css
@@ -49,23 +49,23 @@ window.busy-determined #action-busy-unde
   -moz-appearance: none;
   -moz-box-align: center;
   border-width: 0;
   background: none;
 }
 
 .panel-button-anchor {
   list-style-image: url('icons.png');
-  -moz-image-region: rect(0px,391px,16px,364px);
+  -moz-image-region: rect(0px,491px,16px,464px);
   width: 12px;
   height: 7px;
 }
 
 .panel-button:hover > .panel-button-anchor {
-  -moz-image-region: rect(0px,445px,16px,418px);
+  -moz-image-region: rect(0px,545px,16px,518px);
 }
 
 /* Panel buttons - projects */
 
 #project-panel-button {
   -moz-box-pack: start;
   max-width: calc(50vw - 100px);
 }
@@ -78,34 +78,34 @@ window.busy-determined #action-busy-unde
 #project-panel-button > .panel-button-image[src] {
   /* with app icon */
   width: 20px;
   height: 20px;
 }
 
 #project-panel-button.no-project > .panel-button-image {
   list-style-image: url("icons.png");
-  -moz-image-region: rect(260px,338px,286px,312px);
+  -moz-image-region: rect(260px,438px,286px,412px);
 }
 
 #project-panel-button > .panel-button-label {
   -moz-box-flex: 1;
 }
 
 /* Panel buttons - runtime */
 
 #runtime-panel-button > .panel-button-image {
   list-style-image: url('icons.png');
-  -moz-image-region: rect(78px,338px,104px,312px);
+  -moz-image-region: rect(78px,438px,104px,412px);
   width: 13px;
   height: 13px;
 }
 
 #runtime-panel-button[active="true"] > .panel-button-image {
-  -moz-image-region: rect(78px,364px,104px,338px);
+  -moz-image-region: rect(78px,464px,104px,438px);
 }
 
 /* Action buttons */
 
 .action-button {
   -moz-appearance: none;
   border-width: 0;
   margin: 0;
@@ -129,16 +129,19 @@ window.busy-determined #action-busy-unde
 #action-button-play  { -moz-image-region: rect(0,100px,100px,0) }
 #action-button-stop  { -moz-image-region: rect(0,200px,100px,100px) }
 #action-button-debug { -moz-image-region: rect(0,300px,100px,200px) }
 
 #action-button-play:not([disabled="true"]):hover  { -moz-image-region: rect(200px,100px,300px,0) }
 #action-button-stop:not([disabled="true"]):hover  { -moz-image-region: rect(200px,200px,300px,100px) }
 #action-button-debug:not([disabled="true"]):not([active="true"]):hover { -moz-image-region: rect(200px,300px,300px,200px) }
 
+#action-button-play.reload { -moz-image-region: rect(0,400px,100px,303px) }
+#action-button-play.reload:hover { -moz-image-region: rect(200px,400px,300px,303px) }
+
 #action-button-debug[active="true"] { -moz-image-region: rect(100px,300px,200px,200px) }
 
 /* Panels */
 
 panel > vbox {
   overflow-x: hidden;
 }
 
@@ -191,19 +194,19 @@ panel > .panel-arrowcontainer > .panel-a
 /* project panel */
 
 .project-panel-item-newapp,
 .project-panel-item-openpackaged,
 .project-panel-item-openhosted {
   list-style-image: url("icons.png");
 }
 
-.project-panel-item-newapp       { -moz-image-region: rect(234px,338px,260px,312px) }
-.project-panel-item-openpackaged { -moz-image-region: rect(260px,338px,286px,312px) }
-.project-panel-item-openhosted   { -moz-image-region: rect(208px,338px,234px,312px) }
+.project-panel-item-newapp       { -moz-image-region: rect(234px,438px,260px,412px) }
+.project-panel-item-openpackaged { -moz-image-region: rect(260px,438px,286px,412px) }
+.project-panel-item-openhosted   { -moz-image-region: rect(208px,438px,234px,412px) }
 
 /* runtime panel */
 
 #runtime-panel .panel-arrowcontent {
   padding: 12px 0 0;
 }
 
 #runtime-panel-custom {
@@ -219,27 +222,27 @@ panel > .panel-arrowcontainer > .panel-a
 #runtime-panel-installsimulator,
 .runtime-panel-item-usb,
 .runtime-panel-item-wifi,
 .runtime-panel-item-custom,
 .runtime-panel-item-simulator {
   list-style-image: url("icons.png");
 }
 
-#runtime-details                { -moz-image-region: rect(156px,338px,182px,312px) }
-#runtime-screenshot             { -moz-image-region: rect(130px,338px,156px,312px) }
-#runtime-permissions            { -moz-image-region: rect(104px,338px,130px,312px) }
-#runtime-disconnect             { -moz-image-region: rect(52px,338px,78px,312px) }
-#runtime-panel-nousbdevice      { -moz-image-region: rect(156px,338px,182px,312px) }
-#runtime-panel-noadbhelper      { -moz-image-region: rect(234px,338px,260px,312px) }
-#runtime-panel-installsimulator { -moz-image-region: rect(0px,338px,26px,312px) }
-.runtime-panel-item-usb         { -moz-image-region: rect(52px,338px,78px,312px) }
-.runtime-panel-item-wifi        { -moz-image-region: rect(208px,338px,234px,312px) }
-.runtime-panel-item-custom      { -moz-image-region: rect(26px,338px,52px,312px) }
-.runtime-panel-item-simulator   { -moz-image-region: rect(0px,338px,26px,312px) }
+#runtime-details                { -moz-image-region: rect(156px,438px,182px,412px) }
+#runtime-screenshot             { -moz-image-region: rect(130px,438px,156px,412px) }
+#runtime-permissions            { -moz-image-region: rect(104px,438px,130px,412px) }
+#runtime-disconnect             { -moz-image-region: rect(52px,438px,78px,412px) }
+#runtime-panel-nousbdevice      { -moz-image-region: rect(156px,438px,182px,412px) }
+#runtime-panel-noadbhelper      { -moz-image-region: rect(234px,438px,260px,412px) }
+#runtime-panel-installsimulator { -moz-image-region: rect(0px,438px,26px,412px) }
+.runtime-panel-item-usb         { -moz-image-region: rect(52px,438px,78px,412px) }
+.runtime-panel-item-wifi        { -moz-image-region: rect(208px,438px,234px,412px) }
+.runtime-panel-item-custom      { -moz-image-region: rect(26px,438px,52px,412px) }
+.runtime-panel-item-simulator   { -moz-image-region: rect(0px,438px,26px,412px) }
 
 #runtime-actions {
   border-top: 1px solid rgba(221,221,221,1);
 }
 
 
 #runtime-actions > toolbarbutton {
   border-top: 1px solid rgba(221,221,221,1);
--- a/browser/locales/en-US/chrome/browser/devtools/app-manager.properties
+++ b/browser/locales/en-US/chrome/browser/devtools/app-manager.properties
@@ -1,12 +1,15 @@
 # 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/.
 
+index.deprecationNotice=The App Manager will be removed in a future release.  Your projects have been migrated to WebIDE.
+index.launchWebIDE=Launch WebIDE
+index.readMoreAboutWebIDE=Read More
 # LOCALIZATION NOTE (device.deviceSize): %1$S is the device's width, %2$S is
 # the device's height, %3$S is the device's pixel density.
 # Example: 800x480 (86 DPI).
 device.deviceSize=Device size: %1$Sx%2$S (%3$S DPI)
 # LOCALIZATION NOTE (connection.connectedToDevice, connection.connectTo):
 # %1$S is the host name, %2$S is the port number.
 connection.connectedToDevice=Connected to %1$S
 connection.connectTo=Connect to %1$S:%2$S
--- a/browser/locales/en-US/chrome/browser/devtools/netmonitor.dtd
+++ b/browser/locales/en-US/chrome/browser/devtools/netmonitor.dtd
@@ -226,16 +226,29 @@
   -  on the button in the headers tab that opens a form to edit and resend the currently
      displayed request -->
 <!ENTITY netmonitorUI.summary.editAndResend "Edit and Resend">
 
 <!-- LOCALIZATION NOTE (debuggerUI.summary.editAndResend.accesskey): This is the access key
   -  for the "Edit and Resend" menu item displayed in the context menu for a request -->
 <!ENTITY netmonitorUI.summary.editAndResend.accesskey "R">
 
+<!-- LOCALIZATION NOTE (debuggerUI.summary.rawHeaders): This is the label displayed
+  -  on the button in the headers tab that toggle view for raw request/response headers
+     from the currently displayed request -->
+<!ENTITY netmonitorUI.summary.rawHeaders "Raw headers">
+
+<!-- LOCALIZATION NOTE (debuggerUI.summary.rawHeaders.requestHeaders): This is the label displayed
+  -  in the network details headers tab identifying the raw request headers textarea -->
+<!ENTITY netmonitorUI.summary.rawHeaders.requestHeaders "Request headers:">
+
+<!-- LOCALIZATION NOTE (debuggerUI.summary.rawHeaders.responseHeaders): This is the label displayed
+  -  in the network details headers tab identifying the raw response headers textarea -->
+<!ENTITY netmonitorUI.summary.rawHeaders.responseHeaders "Response headers:">
+
 <!-- LOCALIZATION NOTE (netmonitorUI.context.newTab):  This is the label
   -  for the Open in New Tab menu item displayed in the context menu of the
   -  network container  -->
 <!ENTITY netmonitorUI.context.newTab      "Open in New Tab">
 
 <!-- LOCALIZATION NOTE (netmonitorUI.context.newTab.accesskey): This is the access key
   -  for the Open in New Tab menu item displayed in the context menu of the
   -  network container -->
--- a/browser/locales/en-US/chrome/browser/devtools/profiler.dtd
+++ b/browser/locales/en-US/chrome/browser/devtools/profiler.dtd
@@ -34,16 +34,18 @@
 <!ENTITY profilerUI.importButton "Import…">
 
 <!-- LOCALIZATION NOTE (profilerUI.clearButton): This string is displayed
   -  on a button that remvoes all the recordings. -->
 <!ENTITY profilerUI.clearButton "Clear">
 
 <!-- LOCALIZATION NOTE (profilerUI.table.*): These strings are displayed
   -  in the call tree headers for a recording. -->
-<!ENTITY profilerUI.table.duration    "Time (ms)">
-<!ENTITY profilerUI.table.percentage  "Cost">
-<!ENTITY profilerUI.table.samples     "Samples">
-<!ENTITY profilerUI.table.function    "Function">
+<!ENTITY profilerUI.table.totalDuration   "Total Time (ms)">
+<!ENTITY profilerUI.table.selfDuration    "Self Time (ms)">
+<!ENTITY profilerUI.table.totalPercentage "Total Cost">
+<!ENTITY profilerUI.table.selfPercentage  "Self Cost">
+<!ENTITY profilerUI.table.samples         "Samples">
+<!ENTITY profilerUI.table.function        "Function">
 
 <!-- LOCALIZATION NOTE (profilerUI.newtab.tooltiptext): The tooltiptext shown
   -  on the "+" (new tab) button for a profile when a selection is available. -->
 <!ENTITY profilerUI.newtab.tooltiptext "Add new tab from selection">
--- a/browser/modules/Social.jsm
+++ b/browser/modules/Social.jsm
@@ -266,18 +266,17 @@ function CreateSocialStatusWidget(aId, a
   CustomizableUI.createWidget({
     id: aId,
     type: 'custom',
     removable: true,
     defaultArea: CustomizableUI.AREA_NAVBAR,
     onBuild: function(aDocument) {
       let node = aDocument.createElement('toolbarbutton');
       node.id = this.id;
-      node.setAttribute('class', 'toolbarbutton-1 chromeclass-toolbar-additional social-status-button');
-      node.setAttribute('type', "badged");
+      node.setAttribute('class', 'toolbarbutton-1 chromeclass-toolbar-additional social-status-button badged-button');
       node.style.listStyleImage = "url(" + (aProvider.icon32URL || aProvider.iconURL) + ")";
       node.setAttribute("origin", aProvider.origin);
       node.setAttribute("label", aProvider.name);
       node.setAttribute("tooltiptext", aProvider.name);
       node.setAttribute("oncommand", "SocialStatus.showPopup(this);");
 
       if (PrivateBrowsingUtils.isWindowPrivate(aDocument.defaultView))
         node.setAttribute("disabled", "true");
--- a/browser/themes/linux/browser.css
+++ b/browser/themes/linux/browser.css
@@ -560,17 +560,17 @@ menuitem:not([type]):not(.menuitem-toolt
 }
 
 :-moz-any(#TabsToolbar, #nav-bar) .toolbarbutton-1:not(:-moz-any(@primaryToolbarButtons@)) > .toolbarbutton-icon,
 :-moz-any(#TabsToolbar, #nav-bar) .toolbarbutton-1:not(:-moz-any(@primaryToolbarButtons@)) > .toolbarbutton-badge-container > .toolbarbutton-icon,
 :-moz-any(#TabsToolbar, #nav-bar) .toolbarbutton-1:not(:-moz-any(@primaryToolbarButtons@)) > .toolbarbutton-menubutton-button > .toolbarbutton-icon {
   padding: 3px 7px;
 }
 
-toolbarbutton[type="badged"] > .toolbarbutton-badge-container > .toolbarbutton-icon,
+toolbarbutton.badged-button > .toolbarbutton-badge-container > .toolbarbutton-icon,
 toolbarbutton[type="socialmark"] > .toolbarbutton-icon {
   max-width: 32px !important;
 }
 
 /* Help SDK icons fit: */
 toolbarbutton[sdk-button="true"][cui-areatype="toolbar"] > .toolbarbutton-icon {
   width: 16px;
 }
@@ -2072,45 +2072,16 @@ toolbarbutton.chevron > .toolbarbutton-i
   -moz-image-region: rect(0, 16px, 16px, 0);
   list-style-image: url(chrome://browser/skin/social/services-16.png);
 }
 
 #social-provider-button > .toolbarbutton-menu-dropmarker {
   display: none;
 }
 
-.toolbarbutton-badge-container {
-  margin: 5px 3px;
-  position: relative;
-}
-
-toolbar[iconsize="small"] .toolbarbutton-badge-container {
-  margin: 0;
-}
-
-.toolbarbutton-badge[badge]:not([badge=""])::after {
-  /* The |content| property is set in the content stylesheet. */
-  font-size: 9px;
-  font-weight: bold;
-  padding: 0 1px;
-  color: #fff;
-  background-color: rgb(240,61,37);
-  border: 1px solid rgb(216,55,34);
-  border-radius: 2px;
-  box-shadow: 0 1px 0 rgba(0,39,121,0.77);
-  position: absolute;
-  top: 0;
-  right: 0;
-}
-
-.toolbarbutton-badge[badge]:not([badge=""]):-moz-locale-dir(rtl)::after {
-  left: 2px;
-  right: auto;
-}
-
 .popup-notification-icon[popupid="servicesInstall"] {
   list-style-image: url(chrome://browser/skin/social/services-64.png);
 }
 #servicesInstall-notification-icon {
   list-style-image: url(chrome://browser/skin/social/services-16.png);
 }
 #social-undoactivation-button {
   -moz-margin-start: 0; /* override default label margin to match description margin */
--- a/browser/themes/linux/devtools/netmonitor.css
+++ b/browser/themes/linux/devtools/netmonitor.css
@@ -3,16 +3,20 @@
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 %include ../../shared/devtools/netmonitor.inc.css
 
 #headers-summary-resend {
   padding: 4px;
 }
 
+#toggle-raw-headers {
+  padding: 4px;
+}
+
 .requests-menu-status-and-method {
   width: 9em;
 }
 
 .requests-menu-domain {
   width: 16vw;
 }
 
--- a/browser/themes/osx/browser.css
+++ b/browser/themes/osx/browser.css
@@ -4414,58 +4414,16 @@ menulist.translate-infobar-element > .me
     width: 16px;
   }
 }
 
 #social-provider-button > .toolbarbutton-menu-dropmarker {
   display: none;
 }
 
-.toolbarbutton-badge-container {
-  margin: 0;
-  padding: 0;
-  position: relative;
-}
-
-.toolbarbutton-badge[badge]:not([badge=""]) {
-  /* The |content| property is set in the content stylesheet. */
-  font-size: 9px;
-  font-weight: bold;
-  padding: 0 1px;
-  color: #fff;
-  background-color: rgb(240,61,37);
-  border: 1px solid rgb(216,55,34);
-  border-radius: 2px;
-  box-shadow: 0 1px 0 rgba(0,39,121,0.77);
-  position: absolute;
-  top: 0;
-  right: 0;
-  z-index: 1;
-}
-
-.toolbarbutton-badge[badge]:not([badge=""]):-moz-window-inactive {
-  background-color: rgb(230,230,230);
-  box-shadow: none;
-  border: 1px solid rgb(206,206,206);
-  color: rgb(192,192,192);
-}
-
-.toolbarbutton-badge[badge]:not([badge=""]):-moz-locale-dir(rtl) {
-  left: 0;
-  right: auto;
-}
-
-toolbar[mode="icons"] > *|* > .toolbarbutton-badge[badge]:not([badge=""]) {
-  right: -2px;
-}
-
-toolbar[mode="icons"] > *|* > .toolbarbutton-badge[badge]:not([badge=""]):-moz-locale-dir(rtl) {
-  left: -2px;
-}
-
 .popup-notification-icon[popupid="servicesInstall"] {
   list-style-image: url(chrome://browser/skin/social/services-64.png);
 }
 #servicesInstall-notification-icon {
   list-style-image: url(chrome://browser/skin/social/services-16.png);
 }
 
 @media (min-resolution: 2dppx) {
--- a/browser/themes/shared/devtools/netmonitor.inc.css
+++ b/browser/themes/shared/devtools/netmonitor.inc.css
@@ -480,16 +480,25 @@ label.requests-menu-status-code {
   padding-top: 2px;
 }
 
 #headers-summary-resend {
   margin-top: -10px;
   -moz-margin-end: 6px;
 }
 
+#toggle-raw-headers {
+  margin-top: -10px;
+  -moz-margin-end: 6px;
+}
+
+.raw-response-textarea {
+  height: 50vh;
+}
+
 /* Response tabpanel */
 
 #response-content-info-header {
   margin: 0;
   padding: 3px 8px;
 }
 
 .theme-dark  #response-content-info-header {
--- a/browser/themes/shared/devtools/profiler.inc.css
+++ b/browser/themes/shared/devtools/profiler.inc.css
@@ -246,23 +246,27 @@
   overflow: auto;
 }
 
 .call-tree-cells-container[categories-hidden] .call-tree-category {
   display: none;
 }
 
 .call-tree-header[type="duration"],
-.call-tree-cell[type="duration"] {
-  width: 7em;
+.call-tree-cell[type="duration"],
+.call-tree-header[type="self-duration"],
+.call-tree-cell[type="self-duration"] {
+  width: 9em;
 }
 
 .call-tree-header[type="percentage"],
-.call-tree-cell[type="percentage"] {
-  width: 5em;
+.call-tree-cell[type="percentage"],
+.call-tree-header[type="self-percentage"],
+.call-tree-cell[type="self-percentage"] {
+  width: 6em;
 }
 
 .call-tree-header[type="samples"],
 .call-tree-cell[type="samples"] {
   width: 5em;
 }
 
 .call-tree-header[type="function"],
--- a/browser/themes/windows/browser.css
+++ b/browser/themes/windows/browser.css
@@ -2694,69 +2694,16 @@ toolbar[brighttext] #switch-to-metro-but
   list-style-image: url(chrome://browser/skin/Metro_Glyph-inverted.png);
 }
 
 #switch-to-metro-button[cui-areatype="menu-panel"],
 toolbarpaletteitem[place="palette"] > #switch-to-metro-button {
   list-style-image: url(chrome://browser/skin/Metro_Glyph-menuPanel.png);
 }
 
-.toolbarbutton-badge-container {
-  margin: 0;
-  padding: 0;
-  position: relative;
-}
-
-#nav-bar .toolbarbutton-1 > .toolbarbutton-badge-container {
-  padding: 2px 5px;
-}
-
-.toolbarbutton-1 > .toolbarbutton-badge-container > .toolbar-icon {
-  position: absolute;
-  top: 2px;
-  right: 2px;
-}
-
-.toolbarbutton-badge-container > .toolbarbutton-icon[label]:not([label=""]) {
-  -moz-margin-end: 0;
-}
-
-.toolbarbutton-badge[badge=""] {
-  display: none;
-}
-.toolbarbutton-badge[badge]:not([badge=""])::after {
-  /* The |content| property is set in the content stylesheet. */
-  font-size: 9px;
-  font-weight: bold;
-  padding: 0 1px;
-  color: #fff;
-  background-color: rgb(240,61,37);
-  border: 1px solid rgb(216,55,34);
-  border-radius: 2px;
-  box-shadow: 0 1px 0 rgba(0,39,121,0.77);
-  position: absolute;
-  top: 0;
-  right: 0;
-}
-
-#nav-bar .toolbarbutton-badge[badge]:not([badge=""])::after {
-  top: 1px;
-  right: 1px;
-}
-
-.toolbarbutton-badge[badge]:not([badge=""]):-moz-locale-dir(rtl)::after {
-  left: 0;
-  right: auto;
-}
-
-#nav-bar .toolbarbutton-badge[badge]:not([badge=""]):-moz-locale-dir(rtl)::after {
-  left: 1px;
-  right: auto;
-}
-
 .popup-notification-icon[popupid="servicesInstall"] {
   list-style-image: url(chrome://browser/skin/social/services-64.png);
 }
 #servicesInstall-notification-icon {
   list-style-image: url(chrome://browser/skin/social/services-16.png);
 }
 #social-undoactivation-button {
   -moz-margin-start: 0; /* override default label margin to match description margin */
--- a/configure.in
+++ b/configure.in
@@ -3847,16 +3847,17 @@ MOZ_USE_NATIVE_POPUP_WINDOWS=
 MOZ_ANDROID_HISTORY=
 MOZ_WEBSMS_BACKEND=
 MOZ_ANDROID_BEAM=
 MOZ_LOCALE_SWITCHER=
 MOZ_ANDROID_SEARCH_ACTIVITY=
 MOZ_ANDROID_DOWNLOADS_INTEGRATION=
 MOZ_ANDROID_MLS_STUMBLER=
 MOZ_ANDROID_SHARE_OVERLAY=
+MOZ_ANDROID_NEW_TABLET_UI=
 ACCESSIBILITY=1
 MOZ_TIME_MANAGER=
 MOZ_PAY=
 MOZ_AUDIO_CHANNEL_MANAGER=
 NSS_NO_LIBPKIX=
 MOZ_CONTENT_SANDBOX=
 MOZ_GMP_SANDBOX=
 MOZ_SANDBOX=1
@@ -4907,16 +4908,24 @@ fi
 dnl ========================================================
 dnl = Include share overlay on Android
 dnl ========================================================
 if test -n "$MOZ_ANDROID_SHARE_OVERLAY"; then
     AC_DEFINE(MOZ_ANDROID_SHARE_OVERLAY)
 fi
 
 dnl ========================================================
+dnl = Include New Tablet UI on Android
+dnl = Temporary build flag to allow development in Nightly
+dnl ========================================================
+if test -n "$MOZ_ANDROID_NEW_TABLET_UI"; then
+    AC_DEFINE(MOZ_ANDROID_NEW_TABLET_UI)
+fi
+
+dnl ========================================================
 dnl = Enable IPDL's "expensive" unit tests
 dnl ========================================================
 MOZ_IPDL_TESTS=
 
 MOZ_ARG_ENABLE_BOOL(ipdl-tests,
 [  --enable-ipdl-tests     Enable expensive IPDL tests],
     MOZ_IPDL_TESTS=1,
     MOZ_IPDL_TESTS=)
@@ -8515,16 +8524,17 @@ AC_SUBST(MOZ_METRO)
 
 AC_SUBST(MOZ_ANDROID_HISTORY)
 AC_SUBST(MOZ_WEBSMS_BACKEND)
 AC_SUBST(MOZ_ANDROID_BEAM)
 AC_SUBST(MOZ_LOCALE_SWITCHER)
 AC_SUBST(MOZ_DISABLE_GECKOVIEW)
 AC_SUBST(MOZ_ANDROID_SEARCH_ACTIVITY)
 AC_SUBST(MOZ_ANDROID_SHARE_OVERLAY)
+AC_SUBST(MOZ_ANDROID_NEW_TABLET_UI)
 AC_SUBST(MOZ_ANDROID_MLS_STUMBLER)
 AC_SUBST(MOZ_ANDROID_DOWNLOADS_INTEGRATION)
 AC_SUBST(ENABLE_STRIP)
 AC_SUBST(PKG_SKIP_STRIP)
 AC_SUBST(STRIP_FLAGS)
 AC_SUBST(USE_ELF_HACK)
 AC_SUBST(INCREMENTAL_LINKER)
 AC_SUBST(MOZ_COMPONENTS_VERSION_SCRIPT_LDFLAGS)
--- a/content/base/public/nsHostObjectProtocolHandler.h
+++ b/content/base/public/nsHostObjectProtocolHandler.h
@@ -13,20 +13,20 @@
 
 #define BLOBURI_SCHEME "blob"
 #define MEDIASTREAMURI_SCHEME "mediastream"
 #define MEDIASOURCEURI_SCHEME "mediasource"
 #define FONTTABLEURI_SCHEME "moz-fonttable"
 #define RTSPURI_SCHEME "rtsp"
 
 class nsIDOMBlob;
-class nsIDOMMediaStream;
 class nsIPrincipal;
 
 namespace mozilla {
+class DOMMediaStream;
 namespace dom {
 class MediaSource;
 }
 }
 
 class nsHostObjectProtocolHandler : public nsIProtocolHandler
 {
 public:
@@ -117,17 +117,17 @@ inline bool IsFontTableURI(nsIURI* aUri)
   bool isFont;
   return NS_SUCCEEDED(aUri->SchemeIs(FONTTABLEURI_SCHEME, &isFont)) && isFont;
 }
 
 extern nsresult
 NS_GetStreamForBlobURI(nsIURI* aURI, nsIInputStream** aStream);
 
 extern nsresult
-NS_GetStreamForMediaStreamURI(nsIURI* aURI, nsIDOMMediaStream** aStream);
+NS_GetStreamForMediaStreamURI(nsIURI* aURI, mozilla::DOMMediaStream** aStream);
 
 extern nsresult
 NS_GetSourceForMediaSourceURI(nsIURI* aURI, mozilla::dom::MediaSource** aSource);
 
 #define NS_BLOBPROTOCOLHANDLER_CID \
 { 0xb43964aa, 0xa078, 0x44b2, \
   { 0xb0, 0x6b, 0xfd, 0x4d, 0x1b, 0x17, 0x2e, 0x66 } }
 
--- a/content/base/src/nsGkAtomList.h
+++ b/content/base/src/nsGkAtomList.h
@@ -694,16 +694,17 @@ GK_ATOM(onclick, "onclick")
 GK_ATOM(onclirmodechange, "onclirmodechange")
 GK_ATOM(onclose, "onclose")
 GK_ATOM(oncommand, "oncommand")
 GK_ATOM(oncommandupdate, "oncommandupdate")
 GK_ATOM(oncomplete, "oncomplete")
 GK_ATOM(oncompositionend, "oncompositionend")
 GK_ATOM(oncompositionstart, "oncompositionstart")
 GK_ATOM(oncompositionupdate, "oncompositionupdate")
+GK_ATOM(onconfigurationchange, "onconfigurationchange")
 GK_ATOM(onconnect, "onconnect")
 GK_ATOM(onconnected, "onconnected")
 GK_ATOM(onconnecting, "onconnecting")
 GK_ATOM(oncontextmenu, "oncontextmenu")
 GK_ATOM(oncopy, "oncopy")
 GK_ATOM(oncut, "oncut")
 GK_ATOM(ondatachange, "ondatachange")
 GK_ATOM(ondataerror, "ondataerror")
@@ -743,16 +744,17 @@ GK_ATOM(ondragleave, "ondragleave")
 GK_ATOM(ondragover, "ondragover")
 GK_ATOM(ondragstart, "ondragstart")
 GK_ATOM(ondrop, "ondrop")
 GK_ATOM(onenabled, "onenabled")
 GK_ATOM(onenterpincodereq, "onenterpincodereq")
 GK_ATOM(onemergencycbmodechange, "onemergencycbmodechange")
 GK_ATOM(onerror, "onerror")
 GK_ATOM(onevicted, "onevicted")
+GK_ATOM(onfacesdetected, "onfacesdetected")
 GK_ATOM(onfailed, "onfailed")
 GK_ATOM(onfetch, "onfetch")
 GK_ATOM(onfocus, "onfocus")
 GK_ATOM(onfrequencychange, "onfrequencychange")
 GK_ATOM(onspeakerforcedchange, "onspeakerforcedchange")
 GK_ATOM(onget, "onget")
 GK_ATOM(ongroupchange, "ongroupchange")
 GK_ATOM(onhashchange, "onhashchange")
@@ -812,30 +814,33 @@ GK_ATOM(onpagehide, "onpagehide")
 GK_ATOM(onpageshow, "onpageshow")
 GK_ATOM(onpaint, "onpaint")
 GK_ATOM(onpairedstatuschanged, "onpairedstatuschanged")
 GK_ATOM(onpairingconfirmationreq, "onpairingconfirmationreq")
 GK_ATOM(onpairingconsentreq, "onpairingconsentreq")
 GK_ATOM(onpaste, "onpaste")
 GK_ATOM(onpendingchange, "onpendingchange")
 GK_ATOM(onpichange, "onpichange")
+GK_ATOM(onpicture, "onpicture")
 GK_ATOM(onpopuphidden, "onpopuphidden")
 GK_ATOM(onpopuphiding, "onpopuphiding")
 GK_ATOM(onpopupshowing, "onpopupshowing")
 GK_ATOM(onpopupshown, "onpopupshown")
+GK_ATOM(onpreviewstatechange, "onpreviewstatechange")
 GK_ATOM(onpschange, "onpschange")
 GK_ATOM(onptychange, "onptychange")
 GK_ATOM(onradiostatechange, "onradiostatechange")
 GK_ATOM(onrdsdisabled, "onrdsdisabled")
 GK_ATOM(onrdsenabled, "onrdsenabled")
 GK_ATOM(onreaderror, "onreaderror")
 GK_ATOM(onreadsuccess, "onreadsuccess")
 GK_ATOM(onready, "onready")
 GK_ATOM(onreadystatechange, "onreadystatechange")
 GK_ATOM(onreceived, "onreceived")
+GK_ATOM(onrecorderstatechange, "onrecorderstatechange")
 GK_ATOM(onremoteheld, "onremoteheld")
 GK_ATOM(onremoteresumed, "onremoteresumed")
 GK_ATOM(onresourcetimingbufferfull, "onresourcetimingbufferfull")
 GK_ATOM(onretrieving, "onretrieving")
 GK_ATOM(onRequest, "onRequest")
 GK_ATOM(onrequestmediaplaystatus, "onrequestmediaplaystatus")
 GK_ATOM(onreset, "onreset")
 GK_ATOM(onresuming, "onresuming")
@@ -843,16 +848,17 @@ GK_ATOM(onresize, "onresize")
 GK_ATOM(onrtchange, "onrtchange")
 GK_ATOM(onscostatuschanged, "onscostatuschanged")
 GK_ATOM(onscroll, "onscroll")
 GK_ATOM(onselect, "onselect")
 GK_ATOM(onsending, "onsending")
 GK_ATOM(onsent, "onsent")
 GK_ATOM(onset, "onset")
 GK_ATOM(onshow, "onshow")
+GK_ATOM(onshutter, "onshutter")
 GK_ATOM(onstatechange, "onstatechange")
 GK_ATOM(onstatuschanged, "onstatuschanged")
 GK_ATOM(onstkcommand, "onstkcommand")
 GK_ATOM(onstksessionend, "onstksessionend")
 GK_ATOM(onsubmit, "onsubmit")
 GK_ATOM(onsuccess, "onsuccess")
 GK_ATOM(ontypechange, "ontypechange")
 GK_ATOM(ontext, "ontext")
--- a/content/base/src/nsHostObjectProtocolHandler.cpp
+++ b/content/base/src/nsHostObjectProtocolHandler.cpp
@@ -6,30 +6,30 @@
 
 #include "nsHostObjectProtocolHandler.h"
 #include "nsHostObjectURI.h"
 #include "nsError.h"
 #include "nsClassHashtable.h"
 #include "nsNetUtil.h"
 #include "nsIPrincipal.h"
 #include "nsDOMFile.h"
-#include "nsIDOMMediaStream.h"
+#include "DOMMediaStream.h"
 #include "mozilla/dom/MediaSource.h"
 #include "nsIMemoryReporter.h"
 #include "mozilla/Preferences.h"
 #include "mozilla/LoadInfo.h"
 
 using mozilla::dom::DOMFileImpl;
 using mozilla::LoadInfo;
 
 // -----------------------------------------------------------------------
 // Hash table
 struct DataInfo
 {
-  // mObject is expected to be an nsIDOMBlob, nsIDOMMediaStream, or MediaSource
+  // mObject is expected to be an nsIDOMBlob, DOMMediaStream, or MediaSource
   nsCOMPtr<nsISupports> mObject;
   nsCOMPtr<nsIPrincipal> mPrincipal;
   nsCString mStack;
 };
 
 static nsClassHashtable<nsCStringHashKey, DataInfo>* gDataTable;
 
 // Memory reporting for the hash table.
@@ -600,30 +600,22 @@ NS_GetStreamForBlobURI(nsIURI* aURI, nsI
     return NS_ERROR_DOM_BAD_URI;
   }
 
   DOMFileImpl* blob = static_cast<DOMFileImpl*>(blobImpl.get());
   return blob->GetInternalStream(aStream);
 }
 
 nsresult
-NS_GetStreamForMediaStreamURI(nsIURI* aURI, nsIDOMMediaStream** aStream)
+NS_GetStreamForMediaStreamURI(nsIURI* aURI, mozilla::DOMMediaStream** aStream)
 {
   NS_ASSERTION(IsMediaStreamURI(aURI), "Only call this with mediastream URIs");
 
   *aStream = nullptr;
-
-  nsCOMPtr<nsIDOMMediaStream> stream = do_QueryInterface(GetDataObject(aURI));
-  if (!stream) {
-    return NS_ERROR_DOM_BAD_URI;
-  }
-
-  *aStream = stream;
-  NS_ADDREF(*aStream);
-  return NS_OK;
+  return CallQueryInterface(GetDataObject(aURI), aStream);
 }
 
 NS_IMETHODIMP
 nsFontTableProtocolHandler::NewURI(const nsACString& aSpec,
                                    const char *aCharset,
                                    nsIURI *aBaseURI,
                                    nsIURI **aResult)
 {
--- a/content/html/content/public/HTMLMediaElement.h
+++ b/content/html/content/public/HTMLMediaElement.h
@@ -515,16 +515,17 @@ public:
   void SetMozIsCasting(bool aShow)
   {
     mIsCasting = aShow;
   }
 
   already_AddRefed<DOMMediaStream> GetMozSrcObject() const;
 
   void SetMozSrcObject(DOMMediaStream& aValue);
+  void SetMozSrcObject(DOMMediaStream* aValue);
 
   bool MozPreservesPitch() const
   {
     return mPreservesPitch;
   }
 
   // XPCOM MozPreservesPitch() is OK
 
--- a/content/html/content/src/HTMLMediaElement.cpp
+++ b/content/html/content/src/HTMLMediaElement.cpp
@@ -504,37 +504,27 @@ already_AddRefed<DOMMediaStream>
 HTMLMediaElement::GetMozSrcObject() const
 {
   NS_ASSERTION(!mSrcAttrStream || mSrcAttrStream->GetStream(),
                "MediaStream should have been set up properly");
   nsRefPtr<DOMMediaStream> stream = mSrcAttrStream;
   return stream.forget();
 }
 
-NS_IMETHODIMP
-HTMLMediaElement::GetMozSrcObject(nsIDOMMediaStream** aStream)
-{
-  nsRefPtr<DOMMediaStream> stream = GetMozSrcObject();
-  stream.forget(aStream);
-  return NS_OK;
-}
-
 void
 HTMLMediaElement::SetMozSrcObject(DOMMediaStream& aValue)
 {
   mSrcAttrStream = &aValue;
   Load();
 }
 
-NS_IMETHODIMP
-HTMLMediaElement::SetMozSrcObject(nsIDOMMediaStream* aStream)
+void
+HTMLMediaElement::SetMozSrcObject(DOMMediaStream* aValue)
 {
-  DOMMediaStream* stream = static_cast<DOMMediaStream*>(aStream);
-  SetMozSrcObject(*stream);
-  return NS_OK;
+  SetMozSrcObject(*aValue);
 }
 
 /* readonly attribute nsIDOMHTMLMediaElement mozAutoplayEnabled; */
 NS_IMETHODIMP HTMLMediaElement::GetMozAutoplayEnabled(bool *aAutoplayEnabled)
 {
   *aAutoplayEnabled = mAutoplayEnabled;
 
   return NS_OK;
@@ -1143,27 +1133,27 @@ nsresult HTMLMediaElement::LoadResource(
   if (other && other->mDecoder) {
     // Clone it.
     nsresult rv = InitializeDecoderAsClone(other->mDecoder);
     if (NS_SUCCEEDED(rv))
       return rv;
   }
 
   if (IsMediaStreamURI(mLoadingSrc)) {
-    nsCOMPtr<nsIDOMMediaStream> stream;
+    nsRefPtr<DOMMediaStream> stream;
     rv = NS_GetStreamForMediaStreamURI(mLoadingSrc, getter_AddRefs(stream));
     if (NS_FAILED(rv)) {
       nsCString specUTF8;
       mLoadingSrc->GetSpec(specUTF8);
       NS_ConvertUTF8toUTF16 spec(specUTF8);
       const char16_t* params[] = { spec.get() };
       ReportLoadError("MediaLoadInvalidURI", params, ArrayLength(params));
       return rv;
     }
-    SetupSrcMediaStreamPlayback(static_cast<DOMMediaStream*>(stream.get()));
+    SetupSrcMediaStreamPlayback(stream);
     return NS_OK;
   }
 
   if (IsMediaSourceURI(mLoadingSrc)) {
     nsRefPtr<MediaSource> source;
     rv = NS_GetSourceForMediaSourceURI(mLoadingSrc, getter_AddRefs(source));
     if (NS_FAILED(rv)) {
       nsCString specUTF8;
@@ -1872,42 +1862,28 @@ HTMLMediaElement::MozCaptureStream(Error
   if (!stream) {
     aRv.Throw(NS_ERROR_FAILURE);
     return nullptr;
   }
 
   return stream.forget();
 }
 
-NS_IMETHODIMP HTMLMediaElement::MozCaptureStream(nsIDOMMediaStream** aStream)
-{
-  ErrorResult rv;
-  *aStream = MozCaptureStream(rv).take();
-  return rv.ErrorCode();
-}
-
 already_AddRefed<DOMMediaStream>
 HTMLMediaElement::MozCaptureStreamUntilEnded(ErrorResult& aRv)
 {
   nsRefPtr<DOMMediaStream> stream = CaptureStreamInternal(true);
   if (!stream) {
     aRv.Throw(NS_ERROR_FAILURE);
     return nullptr;
   }
 
   return stream.forget();
 }
 
-NS_IMETHODIMP HTMLMediaElement::MozCaptureStreamUntilEnded(nsIDOMMediaStream** aStream)
-{
-  ErrorResult rv;
-  *aStream = MozCaptureStreamUntilEnded(rv).take();
-  return rv.ErrorCode();
-}
-
 NS_IMETHODIMP HTMLMediaElement::GetMozAudioCaptured(bool* aCaptured)
 {
   *aCaptured = MozAudioCaptured();
   return NS_OK;
 }
 
 class MediaElementSetForURI : public nsURIHashKey {
 public:
--- a/content/html/content/test/test_ignoreuserfocus.html
+++ b/content/html/content/test/test_ignoreuserfocus.html
@@ -135,20 +135,23 @@
 
         document.body.appendChild(witness);
         document.body.appendChild(iframe);
         document.body.appendChild(witness2);
 
         iframe.setAttribute("src", "file_ignoreuserfocus.html");
       }
       addEventListener("load", function() {
-        SpecialPowers.addPermission("browser", true, document);
-        SpecialPowers.pushPrefEnv({
-          "set": [
-            ["dom.mozBrowserFramesEnabled", true]
-          ]
-        }, function() {
-          SimpleTest.waitForFocus(runTest);
-        });
+        SpecialPowers.pushPermissions(
+          [{'type': 'browser', 'allow': true, 'context': document}],
+          function() {
+            SpecialPowers.pushPrefEnv({
+              "set": [
+                ["dom.mozBrowserFramesEnabled", true]
+              ]
+            }, function() {
+              SimpleTest.waitForFocus(runTest);
+            });
+          });
       });
     </script>
   </body>
 </html>
--- a/content/media/DOMMediaStream.cpp
+++ b/content/media/DOMMediaStream.cpp
@@ -14,44 +14,30 @@
 #include "mozilla/dom/VideoTrackList.h"
 #include "MediaStreamGraph.h"
 #include "AudioStreamTrack.h"
 #include "VideoStreamTrack.h"
 
 using namespace mozilla;
 using namespace mozilla::dom;
 
-NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(DOMMediaStream)
-  NS_WRAPPERCACHE_INTERFACE_MAP_ENTRY
-  NS_INTERFACE_MAP_ENTRY(nsISupports)
-  NS_INTERFACE_MAP_ENTRY(nsIDOMMediaStream)
-NS_INTERFACE_MAP_END
-
-NS_IMPL_CYCLE_COLLECTING_ADDREF(DOMMediaStream)
-NS_IMPL_CYCLE_COLLECTING_RELEASE(DOMMediaStream)
-
-NS_IMPL_CYCLE_COLLECTION_CLASS(DOMMediaStream)
+NS_IMPL_CYCLE_COLLECTION_INHERITED(DOMMediaStream,
+                                   DOMEventTargetHelper,
+                                   mWindow,
+                                   mTracks,
+                                   mConsumersToKeepAlive);
 
-NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN(DOMMediaStream)
-  tmp->Destroy();
-  NS_IMPL_CYCLE_COLLECTION_UNLINK(mWindow)
-  NS_IMPL_CYCLE_COLLECTION_UNLINK(mTracks)
-  NS_IMPL_CYCLE_COLLECTION_UNLINK(mConsumersToKeepAlive)
-  NS_IMPL_CYCLE_COLLECTION_UNLINK_PRESERVED_WRAPPER
-NS_IMPL_CYCLE_COLLECTION_UNLINK_END
-NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN(DOMMediaStream)
-  NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mWindow)
-  NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mTracks)
-  NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mConsumersToKeepAlive)
-  NS_IMPL_CYCLE_COLLECTION_TRAVERSE_SCRIPT_OBJECTS
-NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END
-NS_IMPL_CYCLE_COLLECTION_TRACE_WRAPPERCACHE(DOMMediaStream)
+NS_IMPL_ADDREF_INHERITED(DOMMediaStream, DOMEventTargetHelper)
+NS_IMPL_RELEASE_INHERITED(DOMMediaStream, DOMEventTargetHelper)
 
-NS_IMPL_ISUPPORTS_INHERITED(DOMLocalMediaStream, DOMMediaStream,
-                            nsIDOMLocalMediaStream)
+NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION_INHERITED(DOMMediaStream)
+  NS_INTERFACE_MAP_ENTRY(DOMMediaStream)
+NS_INTERFACE_MAP_END_INHERITING(DOMEventTargetHelper)
+
+NS_IMPL_ISUPPORTS_INHERITED0(DOMLocalMediaStream, DOMMediaStream)
 
 NS_IMPL_CYCLE_COLLECTION_INHERITED(DOMAudioNodeMediaStream, DOMMediaStream,
                                    mStreamNode)
 
 NS_IMPL_ADDREF_INHERITED(DOMAudioNodeMediaStream, DOMMediaStream)
 NS_IMPL_RELEASE_INHERITED(DOMAudioNodeMediaStream, DOMMediaStream)
 
 NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION_INHERITED(DOMAudioNodeMediaStream)
@@ -88,18 +74,22 @@ public:
       nsRefPtr<MediaStreamTrack> track;
       if (mEvents & MediaStreamListener::TRACK_EVENT_CREATED) {
         track = stream->CreateDOMTrack(mID, mType);
         stream->NotifyMediaStreamTrackCreated(track);
       } else {
         track = stream->GetDOMTrackFor(mID);
       }
       if (mEvents & MediaStreamListener::TRACK_EVENT_ENDED) {
-        track->NotifyEnded();
-        stream->NotifyMediaStreamTrackEnded(track);
+        if (track) {
+          track->NotifyEnded();
+          stream->NotifyMediaStreamTrackEnded(track);
+        } else {
+          NS_ERROR("track ended but not found");
+        }
       }
       return NS_OK;
     }
 
     StreamTime mEndTime;
     nsRefPtr<StreamListener> mListener;
     TrackID mID;
     uint32_t mEvents;
--- a/content/media/DOMMediaStream.h
+++ b/content/media/DOMMediaStream.h
@@ -1,23 +1,23 @@
 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-*/
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this file,
  * You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #ifndef NSDOMMEDIASTREAM_H_
 #define NSDOMMEDIASTREAM_H_
 
-#include "nsIDOMMediaStream.h"
 #include "nsCycleCollectionParticipant.h"
 #include "nsWrapperCache.h"
 #include "StreamBuffer.h"
 #include "nsIDOMWindow.h"
 #include "nsIPrincipal.h"
 #include "mozilla/PeerIdentity.h"
+#include "mozilla/DOMEventTargetHelper.h"
 
 class nsXPCClassInfo;
 
 // GetCurrentTime is defined in winbase.h as zero argument macro forwarding to
 // GetTickCount() and conflicts with NS_DECL_NSIDOMMEDIASTREAM, containing
 // currentTime getter.
 #ifdef GetCurrentTime
 #undef GetCurrentTime
@@ -43,39 +43,45 @@ class AudioTrack;
 class VideoTrack;
 class AudioTrackList;
 class VideoTrackList;
 class MediaTrackListListener;
 }
 
 class MediaStreamDirectListener;
 
+#define NS_DOMMEDIASTREAM_IID \
+{ 0x8cb65468, 0x66c0, 0x444e, \
+  { 0x89, 0x9f, 0x89, 0x1d, 0x9e, 0xd2, 0xbe, 0x7c } }
+
 /**
  * DOM wrapper for MediaStreams.
  */
-class DOMMediaStream : public nsIDOMMediaStream,
-                       public nsWrapperCache
+class DOMMediaStream : public DOMEventTargetHelper
 {
   friend class DOMLocalMediaStream;
   typedef dom::MediaStreamTrack MediaStreamTrack;
   typedef dom::AudioStreamTrack AudioStreamTrack;
   typedef dom::VideoStreamTrack VideoStreamTrack;
   typedef dom::AudioTrack AudioTrack;
   typedef dom::VideoTrack VideoTrack;
   typedef dom::AudioTrackList AudioTrackList;
   typedef dom::VideoTrackList VideoTrackList;
   typedef dom::MediaTrackListListener MediaTrackListListener;
 
 public:
   typedef uint8_t TrackTypeHints;
 
   DOMMediaStream();
 
-  NS_DECL_CYCLE_COLLECTION_SCRIPT_HOLDER_CLASS(DOMMediaStream)
-  NS_DECL_CYCLE_COLLECTING_ISUPPORTS
+  NS_DECL_ISUPPORTS_INHERITED
+  NS_REALLY_FORWARD_NSIDOMEVENTTARGET(DOMEventTargetHelper)
+  NS_DECL_CYCLE_COLLECTION_CLASS_INHERITED(DOMMediaStream,
+                                           DOMEventTargetHelper)
+  NS_DECLARE_STATIC_IID_ACCESSOR(NS_DOMMEDIASTREAM_IID)
 
   nsIDOMWindow* GetParentObject() const
   {
     return mWindow;
   }
   virtual JSObject* WrapObject(JSContext* aCx) MOZ_OVERRIDE;
 
   // WebIDL
@@ -290,23 +296,30 @@ private:
   // If null, this stream can be used by anyone because it has no content yet.
   nsCOMPtr<nsIPrincipal> mPrincipal;
   nsTArray<PrincipalChangeObserver*> mPrincipalChangeObservers;
   // this is used in gUM and WebRTC to identify peers that this stream
   // is allowed to be sent to
   nsAutoPtr<PeerIdentity> mPeerIdentity;
 };
 
-class DOMLocalMediaStream : public DOMMediaStream,
-                            public nsIDOMLocalMediaStream
+NS_DEFINE_STATIC_IID_ACCESSOR(DOMMediaStream,
+                              NS_DOMMEDIASTREAM_IID)
+
+#define NS_DOMLOCALMEDIASTREAM_IID \
+{ 0xb1437260, 0xec61, 0x4dfa, \
+  { 0x92, 0x54, 0x04, 0x44, 0xe2, 0xb5, 0x94, 0x9c } }
+
+class DOMLocalMediaStream : public DOMMediaStream
 {
 public:
   DOMLocalMediaStream() {}
 
   NS_DECL_ISUPPORTS_INHERITED
+  NS_DECLARE_STATIC_IID_ACCESSOR(NS_DOMLOCALMEDIASTREAM_IID)
 
   virtual JSObject* WrapObject(JSContext* aCx) MOZ_OVERRIDE;
 
   virtual void Stop();
 
   virtual MediaEngineSource* GetMediaEngine(TrackID aTrackID) { return nullptr; }
 
   /**
@@ -320,16 +333,19 @@ public:
    */
   static already_AddRefed<DOMLocalMediaStream>
   CreateTrackUnionStream(nsIDOMWindow* aWindow, TrackTypeHints aHintContents = 0);
 
 protected:
   virtual ~DOMLocalMediaStream();
 };
 
+NS_DEFINE_STATIC_IID_ACCESSOR(DOMLocalMediaStream,
+                              NS_DOMLOCALMEDIASTREAM_IID)
+
 class DOMAudioNodeMediaStream : public DOMMediaStream
 {
   typedef dom::AudioNode AudioNode;
 public:
   explicit DOMAudioNodeMediaStream(AudioNode* aNode);
 
   NS_DECL_ISUPPORTS_INHERITED
   NS_DECL_CYCLE_COLLECTION_CLASS_INHERITED(DOMAudioNodeMediaStream, DOMMediaStream)
--- a/content/media/directshow/DirectShowReader.cpp
+++ b/content/media/directshow/DirectShowReader.cpp
@@ -2,20 +2,19 @@
 /* vim: set ts=8 sts=2 et sw=2 tw=80: */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "DirectShowReader.h"
 #include "MediaDecoderReader.h"
 #include "mozilla/RefPtr.h"
-#include "dshow.h"
+#include "DirectShowUtils.h"
 #include "AudioSinkFilter.h"
 #include "SourceFilter.h"
-#include "DirectShowUtils.h"
 #include "SampleSink.h"
 #include "MediaResource.h"
 #include "VideoUtils.h"
 
 namespace mozilla {
 
 
 #ifdef PR_LOGGING
--- a/content/media/directshow/DirectShowUtils.cpp
+++ b/content/media/directshow/DirectShowUtils.cpp
@@ -1,18 +1,17 @@
 /* vim:set ts=2 sw=2 sts=2 et cindent: */
 /* 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 "dshow.h"
+#include "DirectShowUtils.h"
 #include "dmodshow.h"
 #include "wmcodecdsp.h"
 #include "dmoreg.h"
-#include "DirectShowUtils.h"
 #include "nsAutoPtr.h"
 #include "mozilla/ArrayUtils.h"
 #include "mozilla/RefPtr.h"
 #include "nsPrintfCString.h"
 
 #define WARN(...) NS_WARNING(nsPrintfCString(__VA_ARGS__).get())
 
 namespace mozilla {
--- a/content/media/directshow/DirectShowUtils.h
+++ b/content/media/directshow/DirectShowUtils.h
@@ -3,16 +3,24 @@
  * 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 _DirectShowUtils_h_
 #define _DirectShowUtils_h_
 
 #include <stdint.h>
 #include "dshow.h"
+
+// XXXbz windowsx.h defines GetFirstChild, GetNextSibling,
+// GetPrevSibling are macros, apparently... Eeevil.  We have functions
+// called that on some classes, so undef them.
+#undef GetFirstChild
+#undef GetNextSibling
+#undef GetPrevSibling
+
 #include "DShowTools.h"
 #include "prlog.h"
 
 namespace mozilla {
 
 // Win32 "Event" wrapper. Must be paired with a CriticalSection to create a
 // Java-style "monitor".
 class Signal {
--- a/content/media/webspeech/recognition/SpeechRecognition.cpp
+++ b/content/media/webspeech/recognition/SpeechRecognition.cpp
@@ -929,18 +929,21 @@ SpeechEvent::Run()
   return NS_OK;
 }
 
 NS_IMPL_ISUPPORTS(SpeechRecognition::GetUserMediaSuccessCallback, nsIDOMGetUserMediaSuccessCallback)
 
 NS_IMETHODIMP
 SpeechRecognition::GetUserMediaSuccessCallback::OnSuccess(nsISupports* aStream)
 {
-  nsCOMPtr<nsIDOMLocalMediaStream> localStream = do_QueryInterface(aStream);
-  mRecognition->StartRecording(static_cast<DOMLocalMediaStream*>(localStream.get()));
+  DOMLocalMediaStream *localStream = nullptr;
+  nsresult rv = CallQueryInterface(aStream, &localStream);
+  if (NS_SUCCEEDED(rv)) {
+    mRecognition->StartRecording(localStream);
+  }
   return NS_OK;
 }
 
 NS_IMPL_ISUPPORTS(SpeechRecognition::GetUserMediaErrorCallback, nsIDOMGetUserMediaErrorCallback)
 
 NS_IMETHODIMP
 SpeechRecognition::GetUserMediaErrorCallback::OnError(const nsAString& aError)
 {
--- a/dom/camera/DOMCameraControl.cpp
+++ b/dom/camera/DOMCameraControl.cpp
@@ -15,45 +15,58 @@
 #include "mozilla/MediaManager.h"
 #include "mozilla/Services.h"
 #include "mozilla/unused.h"
 #include "nsIAppsService.h"
 #include "nsIObserverService.h"
 #include "nsIDOMDeviceStorage.h"
 #include "nsIDOMEventListener.h"
 #include "nsIScriptSecurityManager.h"
+#include "nsDOMFile.h"
 #include "Navigator.h"
 #include "nsXULAppAPI.h"
 #include "DOMCameraManager.h"
 #include "DOMCameraCapabilities.h"
 #include "CameraCommon.h"
 #include "nsGlobalWindow.h"
 #include "CameraPreviewMediaStream.h"
+#include "mozilla/dom/CameraUtilBinding.h"
 #include "mozilla/dom/CameraControlBinding.h"
 #include "mozilla/dom/CameraManagerBinding.h"
 #include "mozilla/dom/CameraCapabilitiesBinding.h"
+#include "mozilla/dom/CameraConfigurationEvent.h"
+#include "mozilla/dom/CameraConfigurationEventBinding.h"
+#include "mozilla/dom/CameraFacesDetectedEvent.h"
+#include "mozilla/dom/CameraFacesDetectedEventBinding.h"
+#include "mozilla/dom/CameraStateChangeEvent.h"
+#include "mozilla/dom/BlobEvent.h"
 #include "DOMCameraDetectedFace.h"
 #include "mozilla/dom/BindingUtils.h"
 #include "nsPrintfCString.h"
 
 using namespace mozilla;
 using namespace mozilla::dom;
 using namespace mozilla::ipc;
 
 NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION_INHERITED(nsDOMCameraControl)
   NS_INTERFACE_MAP_ENTRY(nsISupports)
-  NS_INTERFACE_MAP_ENTRY(nsIDOMMediaStream)
 NS_INTERFACE_MAP_END_INHERITING(DOMMediaStream)
 
 NS_IMPL_ADDREF_INHERITED(nsDOMCameraControl, DOMMediaStream)
 NS_IMPL_RELEASE_INHERITED(nsDOMCameraControl, DOMMediaStream)
 
 NS_IMPL_CYCLE_COLLECTION_INHERITED(nsDOMCameraControl, DOMMediaStream,
                                    mCapabilities,
                                    mWindow,
+                                   mGetCameraPromise,
+                                   mAutoFocusPromise,
+                                   mTakePicturePromise,
+                                   mStartRecordingPromise,
+                                   mReleasePromise,
+                                   mSetConfigurationPromise,
                                    mGetCameraOnSuccessCb,
                                    mGetCameraOnErrorCb,
                                    mAutoFocusOnSuccessCb,
                                    mAutoFocusOnErrorCb,
                                    mTakePictureOnSuccessCb,
                                    mTakePictureOnErrorCb,
                                    mStartRecordingOnSuccessCb,
                                    mStartRecordingOnErrorCb,
@@ -130,20 +143,22 @@ nsDOMCameraControl::DOMCameraConfigurati
 {
   MOZ_COUNT_DTOR(nsDOMCameraControl::DOMCameraConfiguration);
 }
 
 nsDOMCameraControl::nsDOMCameraControl(uint32_t aCameraId,
                                        const CameraConfiguration& aInitialConfig,
                                        GetCameraCallback* aOnSuccess,
                                        CameraErrorCallback* aOnError,
+                                       Promise* aPromise,
                                        nsPIDOMWindow* aWindow)
   : DOMMediaStream()
   , mCameraControl(nullptr)
   , mAudioChannelAgent(nullptr)
+  , mGetCameraPromise(aPromise)
   , mGetCameraOnSuccessCb(aOnSuccess)
   , mGetCameraOnErrorCb(aOnError)
   , mAutoFocusOnSuccessCb(nullptr)
   , mAutoFocusOnErrorCb(nullptr)
   , mTakePictureOnSuccessCb(nullptr)
   , mTakePictureOnErrorCb(nullptr)
   , mStartRecordingOnSuccessCb(nullptr)
   , mStartRecordingOnErrorCb(nullptr)
@@ -154,20 +169,22 @@ nsDOMCameraControl::nsDOMCameraControl(u
   , mOnShutterCb(nullptr)
   , mOnClosedCb(nullptr)
   , mOnRecorderStateChangeCb(nullptr)
   , mOnPreviewStateChangeCb(nullptr)
   , mOnAutoFocusMovingCb(nullptr)
   , mOnAutoFocusCompletedCb(nullptr)
   , mOnFacesDetectedCb(nullptr)
   , mWindow(aWindow)
+  , mPreviewState(CameraControlListener::kPreviewStopped)
 {
   DOM_CAMERA_LOGT("%s:%d : this=%p\n", __func__, __LINE__, this);
   mInput = new CameraPreviewMediaStream(this);
 
+  BindToOwner(aWindow);
   SetIsDOMBinding();
 
   nsRefPtr<DOMCameraConfiguration> initialConfig =
     new DOMCameraConfiguration(aInitialConfig);
 
   // Create and initialize the underlying camera.
   ICameraControl::Configuration config;
   bool haveInitialConfig = false;
@@ -678,38 +695,39 @@ public:
   }
 
 protected:
   nsRefPtr<CameraErrorCallback> mCallback;
   nsString mMessage;
 };
 
 // Methods.
-void
+already_AddRefed<Promise>
 nsDOMCameraControl::StartRecording(const CameraStartRecordingOptions& aOptions,
                                    nsDOMDeviceStorage& aStorageArea,
                                    const nsAString& aFilename,
-                                   CameraStartRecordingCallback& aOnSuccess,
+                                   const Optional<OwningNonNull<CameraStartRecordingCallback> >& aOnSuccess,
                                    const Optional<OwningNonNull<CameraErrorCallback> >& aOnError,
                                    ErrorResult& aRv)
 {
   MOZ_ASSERT(mCameraControl);
 
-  nsRefPtr<CameraStartRecordingCallback> cb = mStartRecordingOnSuccessCb;
-  if (cb) {
+  nsRefPtr<Promise> promise = CreatePromise(aRv);
+  if (aRv.Failed()) {
+    return nullptr;
+  }
+
+  if (mStartRecordingPromise) {
+    promise->MaybeReject(NS_ERROR_IN_PROGRESS);
     if (aOnError.WasPassed()) {
       DOM_CAMERA_LOGT("%s:onError WasPassed\n", __func__);
       NS_DispatchToMainThread(new ImmediateErrorCallback(&aOnError.Value(),
                               NS_LITERAL_STRING("StartRecordingInProgress")));
-    } else {
-      DOM_CAMERA_LOGT("%s:onError NS_ERROR_FAILURE\n", __func__);
-      // Only throw if no error callback was passed in.
-      aRv = NS_ERROR_FAILURE;
     }
-    return;
+    return promise.forget();
   }
 
   NotifyRecordingStatusChange(NS_LITERAL_STRING("starting"));
 
 #ifdef MOZ_B2G
   if (!mAudioChannelAgent) {
     mAudioChannelAgent = do_CreateInstance("@mozilla.org/audiochannelagent;1");
     if (mAudioChannelAgent) {
@@ -722,29 +740,34 @@ nsDOMCameraControl::StartRecording(const
   }
 #endif
 
   nsCOMPtr<nsIDOMDOMRequest> request;
   mDSFileDescriptor = new DeviceStorageFileDescriptor();
   aRv = aStorageArea.CreateFileDescriptor(aFilename, mDSFileDescriptor.get(),
                                           getter_AddRefs(request));
   if (aRv.Failed()) {
-    return;
+    return nullptr;
   }
 
+  mStartRecordingPromise = promise;
   mOptions = aOptions;
-  mStartRecordingOnSuccessCb = &aOnSuccess;
+  mStartRecordingOnSuccessCb = nullptr;
+  if (aOnSuccess.WasPassed()) {
+    mStartRecordingOnSuccessCb = &aOnSuccess.Value();
+  }
   mStartRecordingOnErrorCb = nullptr;
   if (aOnError.WasPassed()) {
     mStartRecordingOnErrorCb = &aOnError.Value();
   }
 
   nsCOMPtr<nsIDOMEventListener> listener = new StartRecordingHelper(this);
   request->AddEventListener(NS_LITERAL_STRING("success"), listener, false);
   request->AddEventListener(NS_LITERAL_STRING("error"), listener, false);
+  return promise.forget();
 }
 
 void
 nsDOMCameraControl::OnCreatedFileDescriptor(bool aSucceeded)
 {
   nsresult rv = NS_ERROR_FAILURE;
 
   if (aSucceeded && mDSFileDescriptor->mFileDescriptor.IsValid()) {
@@ -789,118 +812,147 @@ nsDOMCameraControl::StopRecording(ErrorR
 
 void
 nsDOMCameraControl::ResumePreview(ErrorResult& aRv)
 {
   MOZ_ASSERT(mCameraControl);
   aRv = mCameraControl->StartPreview();
 }
 
-void
+already_AddRefed<Promise>
 nsDOMCameraControl::SetConfiguration(const CameraConfiguration& aConfiguration,
                                      const Optional<OwningNonNull<CameraSetConfigurationCallback> >& aOnSuccess,
                                      const Optional<OwningNonNull<CameraErrorCallback> >& aOnError,
                                      ErrorResult& aRv)
 {
   MOZ_ASSERT(mCameraControl);
 
-  nsRefPtr<CameraTakePictureCallback> cb = mTakePictureOnSuccessCb;
-  if (cb) {
+  nsRefPtr<Promise> promise = CreatePromise(aRv);
+  if (aRv.Failed()) {
+    return nullptr;
+  }
+
+  if (mTakePicturePromise) {
+    promise->MaybeReject(NS_ERROR_IN_PROGRESS);
     // We're busy taking a picture, can't change modes right now.
     if (aOnError.WasPassed()) {
       // There is already a call to TakePicture() in progress, abort this
       // call and invoke the error callback (if one was passed in).
       NS_DispatchToMainThread(new ImmediateErrorCallback(&aOnError.Value(),
                               NS_LITERAL_STRING("TakePictureInProgress")));
-    } else {
-      // Only throw if no error callback was passed in.
-      aRv = NS_ERROR_FAILURE;
     }
-    return;
+    return promise.forget();
   }
 
   ICameraControl::Configuration config;
   config.mRecorderProfile = aConfiguration.mRecorderProfile;
   config.mPreviewSize.width = aConfiguration.mPreviewSize.mWidth;
   config.mPreviewSize.height = aConfiguration.mPreviewSize.mHeight;
   config.mMode = ICameraControl::kPictureMode;
   if (aConfiguration.mMode == CameraMode::Video) {
     config.mMode = ICameraControl::kVideoMode;
   }
 
+  aRv = mCameraControl->SetConfiguration(config);
+  if (aRv.Failed()) {
+    return nullptr;
+  }
+
+  mSetConfigurationPromise = promise;
   mSetConfigurationOnSuccessCb = nullptr;
   if (aOnSuccess.WasPassed()) {
     mSetConfigurationOnSuccessCb = &aOnSuccess.Value();
   }
   mSetConfigurationOnErrorCb = nullptr;
   if (aOnError.WasPassed()) {
     mSetConfigurationOnErrorCb = &aOnError.Value();
   }
-
-  aRv = mCameraControl->SetConfiguration(config);
+  return promise.forget();
 }
 
-void
-nsDOMCameraControl::AutoFocus(CameraAutoFocusCallback& aOnSuccess,
+already_AddRefed<Promise>
+nsDOMCameraControl::AutoFocus(const Optional<OwningNonNull<CameraAutoFocusCallback> >& aOnSuccess,
                               const Optional<OwningNonNull<CameraErrorCallback> >& aOnError,
                               ErrorResult& aRv)
 {
   MOZ_ASSERT(mCameraControl);
 
-  nsRefPtr<CameraErrorCallback> ecb = mAutoFocusOnErrorCb.forget();
-  if (ecb) {
+  nsRefPtr<Promise> promise = mAutoFocusPromise.forget();
+  if (promise) {
     // There is already a call to AutoFocus() in progress, cancel it and
     // invoke the error callback (if one was passed in).
-    NS_DispatchToMainThread(new ImmediateErrorCallback(ecb,
-                            NS_LITERAL_STRING("AutoFocusInterrupted")));
+    promise->MaybeReject(NS_ERROR_IN_PROGRESS);
+    mAutoFocusOnSuccessCb = nullptr;
+    nsRefPtr<CameraErrorCallback> ecb = mAutoFocusOnErrorCb.forget();
+    if (ecb) {
+      NS_DispatchToMainThread(new ImmediateErrorCallback(ecb,
+                              NS_LITERAL_STRING("AutoFocusInterrupted")));
+    }
   }
 
-  mAutoFocusOnSuccessCb = &aOnSuccess;
+  promise = CreatePromise(aRv);
+  if (aRv.Failed()) {
+    return nullptr;
+  }
+
+  aRv = mCameraControl->AutoFocus();
+  if (aRv.Failed()) {
+    return nullptr;
+  }
+
+  DispatchStateEvent(NS_LITERAL_STRING("focus"), NS_LITERAL_STRING("focusing"));
+
+  mAutoFocusPromise = promise;
+  mAutoFocusOnSuccessCb = nullptr;
+  if (aOnSuccess.WasPassed()) {
+    mAutoFocusOnSuccessCb = &aOnSuccess.Value();
+  }
   mAutoFocusOnErrorCb = nullptr;
   if (aOnError.WasPassed()) {
     mAutoFocusOnErrorCb = &aOnError.Value();
   }
-
-  aRv = mCameraControl->AutoFocus();
+  return promise.forget();
 }
 
 void
 nsDOMCameraControl::StartFaceDetection(ErrorResult& aRv)
 {
   MOZ_ASSERT(mCameraControl);
   aRv = mCameraControl->StartFaceDetection();
 }
 
 void
 nsDOMCameraControl::StopFaceDetection(ErrorResult& aRv)
 {
   MOZ_ASSERT(mCameraControl);
   aRv = mCameraControl->StopFaceDetection();
 }
 
-void
+already_AddRefed<Promise>
 nsDOMCameraControl::TakePicture(const CameraPictureOptions& aOptions,
-                                CameraTakePictureCallback& aOnSuccess,
+                                const Optional<OwningNonNull<CameraTakePictureCallback> >& aOnSuccess,
                                 const Optional<OwningNonNull<CameraErrorCallback> >& aOnError,
                                 ErrorResult& aRv)
 {
   MOZ_ASSERT(mCameraControl);
 
-  nsRefPtr<CameraTakePictureCallback> cb = mTakePictureOnSuccessCb;
-  if (cb) {
+  nsRefPtr<Promise> promise = CreatePromise(aRv);
+  if (aRv.Failed()) {
+    return nullptr;
+  }
+
+  if (mTakePicturePromise) {
+    // There is already a call to TakePicture() in progress, abort this new
+    // one and invoke the error callback (if one was passed in).
+    promise->MaybeReject(NS_ERROR_IN_PROGRESS);
     if (aOnError.WasPassed()) {
-      // There is already a call to TakePicture() in progress, abort this new
-      // one and invoke the error callback (if one was passed in).
       NS_DispatchToMainThread(new ImmediateErrorCallback(&aOnError.Value(),
                               NS_LITERAL_STRING("TakePictureAlreadyInProgress")));
-    } else {
-      // Only throw if no error callback was passed in.
-      aRv = NS_ERROR_FAILURE;
     }
-    return;
+    return promise.forget();
   }
 
   {
     ICameraControlParameterSetAutoEnter batch(mCameraControl);
 
     // XXXmikeh - remove this: see bug 931155
     ICameraControl::Size s;
     s.width = aOptions.mPictureSize.mWidth;
@@ -916,42 +968,60 @@ nsDOMCameraControl::TakePicture(const Ca
       mCameraControl->Set(CAMERA_PARAM_PICTURE_SIZE, s);
     }
     mCameraControl->Set(CAMERA_PARAM_PICTURE_ROTATION, aOptions.mRotation);
     mCameraControl->Set(CAMERA_PARAM_PICTURE_FILEFORMAT, aOptions.mFileFormat);
     mCameraControl->Set(CAMERA_PARAM_PICTURE_DATETIME, aOptions.mDateTime);
     mCameraControl->SetLocation(p);
   }
 
-  mTakePictureOnSuccessCb = &aOnSuccess;
+  aRv = mCameraControl->TakePicture();
+  if (aRv.Failed()) {
+    return nullptr;
+  }
+
+  mTakePicturePromise = promise;
+  mTakePictureOnSuccessCb = nullptr;
+  if (aOnSuccess.WasPassed()) {
+    mTakePictureOnSuccessCb = &aOnSuccess.Value();
+  }
   mTakePictureOnErrorCb = nullptr;
   if (aOnError.WasPassed()) {
     mTakePictureOnErrorCb = &aOnError.Value();
   }
-
-  aRv = mCameraControl->TakePicture();
+  return promise.forget();
 }
 
-void
+already_AddRefed<Promise>
 nsDOMCameraControl::ReleaseHardware(const Optional<OwningNonNull<CameraReleaseCallback> >& aOnSuccess,
                                     const Optional<OwningNonNull<CameraErrorCallback> >& aOnError,
                                     ErrorResult& aRv)
 {
   MOZ_ASSERT(mCameraControl);
 
+  nsRefPtr<Promise> promise = CreatePromise(aRv);
+  if (aRv.Failed()) {
+    return nullptr;
+  }
+
+  aRv = mCameraControl->Stop();
+  if (aRv.Failed()) {
+    return nullptr;
+  }
+
+  mReleasePromise = promise;
   mReleaseOnSuccessCb = nullptr;
   if (aOnSuccess.WasPassed()) {
     mReleaseOnSuccessCb = &aOnSuccess.Value();
   }
   mReleaseOnErrorCb = nullptr;
   if (aOnError.WasPassed()) {
     mReleaseOnErrorCb = &aOnError.Value();
   }
-
-  aRv = mCameraControl->Stop();
+  return promise.forget();
 }
 
 void
 nsDOMCameraControl::ResumeContinuousFocus(ErrorResult& aRv)
 {
   MOZ_ASSERT(mCameraControl);
   aRv = mCameraControl->ResumeContinuousFocus();
 }
@@ -960,16 +1030,22 @@ void
 nsDOMCameraControl::Shutdown()
 {
   DOM_CAMERA_LOGI("%s:%d\n", __func__, __LINE__);
   MOZ_ASSERT(mCameraControl);
 
   // Remove any pending solicited event handlers; these
   // reference our window object, which in turn references
   // us. If we don't remove them, we can leak DOM objects.
+  AbortPromise(mGetCameraPromise);
+  AbortPromise(mAutoFocusPromise);
+  AbortPromise(mTakePicturePromise);
+  AbortPromise(mStartRecordingPromise);
+  AbortPromise(mReleasePromise);
+  AbortPromise(mSetConfigurationPromise);
   mGetCameraOnSuccessCb = nullptr;
   mGetCameraOnErrorCb = nullptr;
   mAutoFocusOnSuccessCb = nullptr;
   mAutoFocusOnErrorCb = nullptr;
   mTakePictureOnSuccessCb = nullptr;
   mTakePictureOnErrorCb = nullptr;
   mStartRecordingOnSuccessCb = nullptr;
   mStartRecordingOnErrorCb = nullptr;
@@ -996,47 +1072,124 @@ nsDOMCameraControl::NotifyRecordingStatu
   NS_ENSURE_TRUE(mWindow, NS_ERROR_FAILURE);
 
   return MediaManager::NotifyRecordingStatusChange(mWindow,
                                                    aMsg,
                                                    true /* aIsAudio */,
                                                    true /* aIsVideo */);
 }
 
+already_AddRefed<Promise>
+nsDOMCameraControl::CreatePromise(ErrorResult& aRv)
+{
+  nsCOMPtr<nsIGlobalObject> global = do_QueryInterface(mWindow);
+  if (!global) {
+    aRv.Throw(NS_ERROR_FAILURE);
+    return nullptr;
+  }
+  return Promise::Create(global, aRv);
+}
+
+void
+nsDOMCameraControl::AbortPromise(nsRefPtr<Promise>& aPromise)
+{
+  nsRefPtr<Promise> promise = aPromise.forget();
+  if (promise) {
+    promise->MaybeReject(NS_ERROR_NOT_AVAILABLE);
+  }
+}
+
+void
+nsDOMCameraControl::EventListenerAdded(nsIAtom* aType)
+{
+  if (aType == nsGkAtoms::onpreviewstatechange) {
+    DispatchPreviewStateEvent(mPreviewState);
+  }
+}
+
+void
+nsDOMCameraControl::DispatchPreviewStateEvent(CameraControlListener::PreviewState aState)
+{
+  nsString state;
+  switch (aState) {
+    case CameraControlListener::kPreviewStarted:
+      state = NS_LITERAL_STRING("started");
+      break;
+
+    default:
+      state = NS_LITERAL_STRING("stopped");
+      break;
+  }
+
+  DispatchStateEvent(NS_LITERAL_STRING("previewstatechange"), state);
+}
+
+void
+nsDOMCameraControl::DispatchStateEvent(const nsString& aType, const nsString& aState)
+{
+  CameraStateChangeEventInit eventInit;
+  eventInit.mNewState = aState;
+
+  nsRefPtr<CameraStateChangeEvent> event =
+    CameraStateChangeEvent::Constructor(this, aType, eventInit);
+
+  DispatchTrustedEvent(event);
+}
+
 // Camera Control event handlers--must only be called from the Main Thread!
 void
 nsDOMCameraControl::OnHardwareStateChange(CameraControlListener::HardwareState aState)
 {
   MOZ_ASSERT(NS_IsMainThread());
   ErrorResult ignored;
 
   DOM_CAMERA_LOGI("DOM OnHardwareStateChange(%d)\n", aState);
 
   switch (aState) {
     case CameraControlListener::kHardwareOpen:
-      // The hardware is open, so we can return a camera to JS, even if
-      // the preview hasn't started yet.
-      if (mGetCameraOnSuccessCb) {
+      {
+        // The hardware is open, so we can return a camera to JS, even if
+        // the preview hasn't started yet.
+        nsRefPtr<Promise> promise = mGetCameraPromise.forget();
+        if (promise) {
+          CameraGetPromiseData data;
+          data.mCamera = this;
+          data.mConfiguration = *mCurrentConfiguration;
+          promise->MaybeResolve(data);
+        }
         nsRefPtr<GetCameraCallback> cb = mGetCameraOnSuccessCb.forget();
-        ErrorResult ignored;
         mGetCameraOnErrorCb = nullptr;
-        cb->Call(*this, *mCurrentConfiguration, ignored);
+        if (cb) {
+          ErrorResult ignored;
+          cb->Call(*this, *mCurrentConfiguration, ignored);
+        }
       }
       break;
 
     case CameraControlListener::kHardwareClosed:
-      if (mReleaseOnSuccessCb) {
-        // If we have this event handler, this was a solicited hardware close.
-        nsRefPtr<CameraReleaseCallback> cb = mReleaseOnSuccessCb.forget();
-        mReleaseOnErrorCb = nullptr;
-        cb->Call(ignored);
-      } else if(mOnClosedCb) {
-        // If not, something else closed the hardware.
-        nsRefPtr<CameraClosedCallback> cb = mOnClosedCb;
-        cb->Call(ignored);
+      {
+        nsRefPtr<Promise> promise = mReleasePromise.forget();
+        if (promise || mReleaseOnSuccessCb) {
+          // If we have this event handler, this was a solicited hardware close.
+          if (promise) {
+            promise->MaybeResolve(JS::UndefinedHandleValue);
+          }
+          nsRefPtr<CameraReleaseCallback> cb = mReleaseOnSuccessCb.forget();
+          mReleaseOnErrorCb = nullptr;
+          if (cb) {
+            cb->Call(ignored);
+          }
+        } else {
+          // If not, something else closed the hardware.
+          nsRefPtr<CameraClosedCallback> cb = mOnClosedCb;
+          if (cb) {
+            cb->Call(ignored);
+          }
+        }
+        DispatchTrustedEvent(NS_LITERAL_STRING("close"));
       }
       break;
 
     default:
       MOZ_ASSERT_UNREACHABLE("Unanticipated camera hardware state");
   }
 }
 
@@ -1047,61 +1200,71 @@ nsDOMCameraControl::OnShutter()
 
   DOM_CAMERA_LOGI("DOM ** SNAP **\n");
 
   nsRefPtr<CameraShutterCallback> cb = mOnShutterCb;
   if (cb) {
     ErrorResult ignored;
     cb->Call(ignored);
   }
+
+  DispatchTrustedEvent(NS_LITERAL_STRING("shutter"));
 }
 
 void
 nsDOMCameraControl::OnPreviewStateChange(CameraControlListener::PreviewState aState)
 {
   MOZ_ASSERT(NS_IsMainThread());
 
-  if (!mOnPreviewStateChangeCb) {
-    return;
-  }
-
+  mPreviewState = aState;
   nsString state;
   switch (aState) {
     case CameraControlListener::kPreviewStarted:
       state = NS_LITERAL_STRING("started");
       break;
 
     default:
       state = NS_LITERAL_STRING("stopped");
       break;
   }
 
   nsRefPtr<CameraPreviewStateChange> cb = mOnPreviewStateChangeCb;
-  ErrorResult ignored;
-  cb->Call(state, ignored);
+  if (cb) {
+    ErrorResult ignored;
+    cb->Call(state, ignored);
+  }
+
+  DispatchPreviewStateEvent(aState);
 }
 
 void
 nsDOMCameraControl::OnRecorderStateChange(CameraControlListener::RecorderState aState,
                                           int32_t aArg, int32_t aTrackNum)
 {
   // For now, we do nothing with 'aStatus' and 'aTrackNum'.
   MOZ_ASSERT(NS_IsMainThread());
 
   ErrorResult ignored;
   nsString state;
 
   switch (aState) {
     case CameraControlListener::kRecorderStarted:
-      if (mStartRecordingOnSuccessCb) {
-        nsRefPtr<CameraStartRecordingCallback> cb = mStartRecordingOnSuccessCb.forget();
+      {
+        nsRefPtr<Promise> promise = mStartRecordingPromise.forget();
+        if (promise) {
+          promise->MaybeResolve(JS::UndefinedHandleValue);
+        }
+
+        nsRefPtr<CameraStartRecordingCallback> scb = mStartRecordingOnSuccessCb.forget();
         mStartRecordingOnErrorCb = nullptr;
-        cb->Call(ignored);
+        if (scb) {
+          scb->Call(ignored);
+        }
+        state = NS_LITERAL_STRING("Started");
       }
-      state = NS_LITERAL_STRING("Started");
       break;
 
     case CameraControlListener::kRecorderStopped:
       NotifyRecordingStatusChange(NS_LITERAL_STRING("shutdown"));
       state = NS_LITERAL_STRING("Stopped");
       break;
 
 #ifdef MOZ_B2G_CAMERA
@@ -1134,156 +1297,219 @@ nsDOMCameraControl::OnRecorderStateChang
       MOZ_ASSERT_UNREACHABLE("Unanticipated video recorder error");
       return;
   }
 
   nsRefPtr<CameraRecorderStateChange> cb = mOnRecorderStateChangeCb;
   if (cb) {
     cb->Call(state, ignored);
   }
+
+  DispatchStateEvent(NS_LITERAL_STRING("recorderstatechange"), state);
 }
 
 void
 nsDOMCameraControl::OnConfigurationChange(DOMCameraConfiguration* aConfiguration)
 {
   MOZ_ASSERT(NS_IsMainThread());
+  MOZ_ASSERT(aConfiguration != nullptr);
 
   // Update our record of the current camera configuration
   mCurrentConfiguration = aConfiguration;
 
   DOM_CAMERA_LOGI("DOM OnConfigurationChange: this=%p\n", this);
   DOM_CAMERA_LOGI("    mode                   : %s\n",
     mCurrentConfiguration->mMode == CameraMode::Video ? "video" : "picture");
   DOM_CAMERA_LOGI("    maximum focus areas    : %d\n",
     mCurrentConfiguration->mMaxFocusAreas);
   DOM_CAMERA_LOGI("    maximum metering areas : %d\n",
     mCurrentConfiguration->mMaxMeteringAreas);
   DOM_CAMERA_LOGI("    preview size (w x h)   : %d x %d\n",
     mCurrentConfiguration->mPreviewSize.mWidth, mCurrentConfiguration->mPreviewSize.mHeight);
   DOM_CAMERA_LOGI("    recorder profile       : %s\n",
     NS_ConvertUTF16toUTF8(mCurrentConfiguration->mRecorderProfile).get());
 
+  nsRefPtr<Promise> promise = mSetConfigurationPromise.forget();
+  if (promise) {
+    promise->MaybeResolve(*aConfiguration);
+  }
+
   nsRefPtr<CameraSetConfigurationCallback> cb = mSetConfigurationOnSuccessCb.forget();
   mSetConfigurationOnErrorCb = nullptr;
   if (cb) {
     ErrorResult ignored;
     cb->Call(*mCurrentConfiguration, ignored);
   }
+
+  CameraConfigurationEventInit eventInit;
+  eventInit.mMode = mCurrentConfiguration->mMode;
+  eventInit.mRecorderProfile = mCurrentConfiguration->mRecorderProfile;
+  eventInit.mPreviewSize = new DOMRect(this, 0, 0,
+                                       mCurrentConfiguration->mPreviewSize.mWidth,
+                                       mCurrentConfiguration->mPreviewSize.mHeight);
+
+  nsRefPtr<CameraConfigurationEvent> event =
+    CameraConfigurationEvent::Constructor(this,
+                                          NS_LITERAL_STRING("configurationchanged"),
+                                          eventInit);
+
+  DispatchTrustedEvent(event);
 }
 
 void
 nsDOMCameraControl::OnAutoFocusComplete(bool aAutoFocusSucceeded)
 {
   MOZ_ASSERT(NS_IsMainThread());
 
+  nsRefPtr<Promise> promise = mAutoFocusPromise.forget();
+  if (promise) {
+    promise->MaybeResolve(aAutoFocusSucceeded);
+  }
+
   nsRefPtr<CameraAutoFocusCallback> cb = mAutoFocusOnSuccessCb.forget();
   mAutoFocusOnErrorCb = nullptr;
   if (cb) {
     ErrorResult ignored;
     cb->Call(aAutoFocusSucceeded, ignored);
   }
 
   cb = mOnAutoFocusCompletedCb;
   if (cb) {
     ErrorResult ignored;
     cb->Call(aAutoFocusSucceeded, ignored);
   }
+
+  if (aAutoFocusSucceeded) {
+    DispatchStateEvent(NS_LITERAL_STRING("focus"), NS_LITERAL_STRING("focused"));
+  } else {
+    DispatchStateEvent(NS_LITERAL_STRING("focus"), NS_LITERAL_STRING("unfocused"));
+  }
 }
 
 void
 nsDOMCameraControl::OnAutoFocusMoving(bool aIsMoving)
 {
   MOZ_ASSERT(NS_IsMainThread());
 
   nsRefPtr<CameraAutoFocusMovingCallback> cb = mOnAutoFocusMovingCb;
   if (cb) {
     ErrorResult ignored;
     cb->Call(aIsMoving, ignored);
   }
+
+  if (aIsMoving) {
+    DispatchStateEvent(NS_LITERAL_STRING("focus"), NS_LITERAL_STRING("focusing"));
+  }
 }
 
 void
 nsDOMCameraControl::OnFacesDetected(const nsTArray<ICameraControl::Face>& aFaces)
 {
   DOM_CAMERA_LOGI("DOM OnFacesDetected %u face(s)\n", aFaces.Length());
   MOZ_ASSERT(NS_IsMainThread());
 
-  nsRefPtr<CameraFaceDetectionCallback> cb = mOnFacesDetectedCb;
-  if (!cb) {
-    return;
-  }
-
   Sequence<OwningNonNull<DOMCameraDetectedFace> > faces;
   uint32_t len = aFaces.Length();
 
   if (faces.SetCapacity(len)) {
     nsRefPtr<DOMCameraDetectedFace> f;
     for (uint32_t i = 0; i < len; ++i) {
       f = new DOMCameraDetectedFace(this, aFaces[i]);
       *faces.AppendElement() = f.forget().take();
     }
   }
 
-  ErrorResult ignored;
-  cb->Call(faces, ignored);
+  nsRefPtr<CameraFaceDetectionCallback> cb = mOnFacesDetectedCb;
+  if (cb) {
+    ErrorResult ignored;
+    cb->Call(faces, ignored);
+  }
+
+  CameraFacesDetectedEventInit eventInit;
+  eventInit.mFaces.SetValue(faces);
+
+  nsRefPtr<CameraFacesDetectedEvent> event =
+    CameraFacesDetectedEvent::Constructor(this,
+                                          NS_LITERAL_STRING("facesdetected"),
+                                          eventInit);
+
+  DispatchTrustedEvent(event);
 }
 
 void
 nsDOMCameraControl::OnTakePictureComplete(nsIDOMBlob* aPicture)
 {
   MOZ_ASSERT(NS_IsMainThread());
+  MOZ_ASSERT(aPicture != nullptr);
+
+  nsRefPtr<Promise> promise = mTakePicturePromise.forget();
+  if (promise) {
+    nsCOMPtr<nsIDOMBlob> picture = aPicture;
+    promise->MaybeResolve(picture);
+  }
 
   nsRefPtr<CameraTakePictureCallback> cb = mTakePictureOnSuccessCb.forget();
   mTakePictureOnErrorCb = nullptr;
-  if (!cb) {
-    // Warn because it shouldn't be possible to get here without
-    // having passed a success callback into takePicture(), even
-    // though we guard against a nullptr dereference.
-    NS_WARNING("DOM Null success callback in OnTakePictureComplete()");
-    return;
+  if (cb) {
+    ErrorResult ignored;
+    cb->Call(aPicture, ignored);
   }
 
-  ErrorResult ignored;
-  cb->Call(aPicture, ignored);
+  BlobEventInit eventInit;
+  eventInit.mData = aPicture;
+
+  nsRefPtr<BlobEvent> event = BlobEvent::Constructor(this,
+                                                     NS_LITERAL_STRING("picture"),
+                                                     eventInit);
+
+  DispatchTrustedEvent(event);
 }
 
 void
 nsDOMCameraControl::OnUserError(CameraControlListener::UserContext aContext, nsresult aError)
 {
   MOZ_ASSERT(NS_IsMainThread());
 
+  nsRefPtr<Promise> promise;
   nsRefPtr<CameraErrorCallback> errorCb;
 
   switch (aContext) {
     case CameraControlListener::kInStartCamera:
+      promise = mGetCameraPromise.forget();
       mGetCameraOnSuccessCb = nullptr;
       errorCb = mGetCameraOnErrorCb.forget();
       break;
 
     case CameraControlListener::kInStopCamera:
+      promise = mReleasePromise.forget();
       mReleaseOnSuccessCb = nullptr;
       errorCb = mReleaseOnErrorCb.forget();
       break;
 
     case CameraControlListener::kInSetConfiguration:
+      promise = mSetConfigurationPromise.forget();
       mSetConfigurationOnSuccessCb = nullptr;
       errorCb = mSetConfigurationOnErrorCb.forget();
       break;
 
     case CameraControlListener::kInAutoFocus:
+      promise = mAutoFocusPromise.forget();
       mAutoFocusOnSuccessCb = nullptr;
       errorCb = mAutoFocusOnErrorCb.forget();
+      DispatchStateEvent(NS_LITERAL_STRING("focus"), NS_LITERAL_STRING("unfocused"));
       break;
 
     case CameraControlListener::kInTakePicture:
+      promise = mTakePicturePromise.forget();
       mTakePictureOnSuccessCb = nullptr;
       errorCb = mTakePictureOnErrorCb.forget();
       break;
 
     case CameraControlListener::kInStartRecording:
+      promise = mStartRecordingPromise.forget();
       mStartRecordingOnSuccessCb = nullptr;
       errorCb = mStartRecordingOnErrorCb.forget();
       break;
 
     case CameraControlListener::kInStartFaceDetection:
       // This method doesn't have any callbacks, so all we can do is log the
       // failure. This only happens after the hardware has been released.
       NS_WARNING("Failed to start face detection");
@@ -1335,57 +1561,62 @@ nsDOMCameraControl::OnUserError(CameraCo
       {
         nsPrintfCString msg("Unhandled aContext=%u, aError=0x%x\n", aContext, aError);
         NS_WARNING(msg.get());
       }
       MOZ_ASSERT_UNREACHABLE("Unhandled user error");
       return;
   }
 
-  if (!errorCb) {
+  if (!promise && !errorCb) {
     DOM_CAMERA_LOGW("DOM No error handler for aError=0x%x in aContext=%u\n",
       aError, aContext);
     return;
   }
 
-  nsString error;
-  switch (aError) {
-    case NS_ERROR_INVALID_ARG:
-      error = NS_LITERAL_STRING("InvalidArgument");
-      break;
-
-    case NS_ERROR_NOT_AVAILABLE:
-      error = NS_LITERAL_STRING("NotAvailable");
-      break;
-
-    case NS_ERROR_NOT_IMPLEMENTED:
-      error = NS_LITERAL_STRING("NotImplemented");
-      break;
-
-    case NS_ERROR_NOT_INITIALIZED:
-      error = NS_LITERAL_STRING("HardwareClosed");
-      break;
-
-    case NS_ERROR_ALREADY_INITIALIZED:
-      error = NS_LITERAL_STRING("HardwareAlreadyOpen");
-      break;
-
-    case NS_ERROR_OUT_OF_MEMORY:
-      error = NS_LITERAL_STRING("OutOfMemory");
-      break;
-
-    default:
-      {
-        nsPrintfCString msg("Reporting aError=0x%x as generic\n", aError);
-        NS_WARNING(msg.get());
-      }
-      // fallthrough
-
-    case NS_ERROR_FAILURE:
-      error = NS_LITERAL_STRING("GeneralFailure");
-      break;
+  DOM_CAMERA_LOGI("DOM OnUserError aContext=%u, aError=0x%x\n", aContext, aError);
+  if (promise) {
+    promise->MaybeReject(aError);
   }
 
-  DOM_CAMERA_LOGI("DOM OnUserError aContext=%u, error='%s'\n", aContext,
-    NS_ConvertUTF16toUTF8(error).get());
-  ErrorResult ignored;
-  errorCb->Call(error, ignored);
+  if (errorCb) {
+    nsString error;
+    switch (aError) {
+      case NS_ERROR_INVALID_ARG:
+        error = NS_LITERAL_STRING("InvalidArgument");
+        break;
+
+      case NS_ERROR_NOT_AVAILABLE:
+        error = NS_LITERAL_STRING("NotAvailable");
+        break;
+
+      case NS_ERROR_NOT_IMPLEMENTED:
+        error = NS_LITERAL_STRING("NotImplemented");
+        break;
+
+      case NS_ERROR_NOT_INITIALIZED:
+        error = NS_LITERAL_STRING("HardwareClosed");
+        break;
+
+      case NS_ERROR_ALREADY_INITIALIZED:
+        error = NS_LITERAL_STRING("HardwareAlreadyOpen");
+        break;
+
+      case NS_ERROR_OUT_OF_MEMORY:
+        error = NS_LITERAL_STRING("OutOfMemory");
+        break;
+
+      default:
+        {
+          nsPrintfCString msg("Reporting aError=0x%x as generic\n", aError);
+          NS_WARNING(msg.get());
+        }
+        // fallthrough
+
+      case NS_ERROR_FAILURE:
+        error = NS_LITERAL_STRING("GeneralFailure");
+        break;
+    }
+
+    ErrorResult ignored;
+    errorCb->Call(error, ignored);
+  }
 }
--- a/dom/camera/DOMCameraControl.h
+++ b/dom/camera/DOMCameraControl.h
@@ -4,16 +4,17 @@
 
 #ifndef DOM_CAMERA_DOMCAMERACONTROL_H
 #define DOM_CAMERA_DOMCAMERACONTROL_H
 
 #include "nsCOMPtr.h"
 #include "nsAutoPtr.h"
 #include "nsCycleCollectionParticipant.h"
 #include "mozilla/dom/CameraControlBinding.h"
+#include "mozilla/dom/Promise.h"
 #include "ICameraControl.h"
 #include "CameraCommon.h"
 #include "DOMMediaStream.h"
 #include "AudioChannelAgent.h"
 #include "nsProxyRelease.h"
 #include "nsHashPropertyBag.h"
 #include "DeviceStorage.h"
 #include "DOMCameraControlListener.h"
@@ -48,16 +49,17 @@ public:
   // HasSupport() method in each header. We can get rid of these with the
   // Great Renaming proposed in bug 983177.
   static bool HasSupport(JSContext* aCx, JSObject* aGlobal);
 
   nsDOMCameraControl(uint32_t aCameraId,
                      const dom::CameraConfiguration& aInitialConfig,
                      dom::GetCameraCallback* aOnSuccess,
                      dom::CameraErrorCallback* aOnError,
+                     dom::Promise* aPromise,
                      nsPIDOMWindow* aWindow);
 
   void Shutdown();
 
   nsPIDOMWindow* GetParentObject() const { return mWindow; }
 
   // Attributes.
   void GetEffect(nsString& aEffect, ErrorResult& aRv);
@@ -97,52 +99,61 @@ public:
   dom::CameraAutoFocusMovingCallback* GetOnAutoFocusMoving();
   void SetOnAutoFocusMoving(dom::CameraAutoFocusMovingCallback* aCb);
   dom::CameraAutoFocusCallback* GetOnAutoFocusCompleted();
   void SetOnAutoFocusCompleted(dom::CameraAutoFocusCallback* aCb);
   dom::CameraFaceDetectionCallback* GetOnFacesDetected();
   void SetOnFacesDetected(dom::CameraFaceDetectionCallback* aCb);
 
   // Methods.
-  void SetConfiguration(const dom::CameraConfiguration& aConfiguration,
-                        const dom::Optional<dom::OwningNonNull<dom::CameraSetConfigurationCallback> >& aOnSuccess,
-                        const dom::Optional<dom::OwningNonNull<dom::CameraErrorCallback> >& aOnError,
-                        ErrorResult& aRv);
+  already_AddRefed<dom::Promise> SetConfiguration(const dom::CameraConfiguration& aConfiguration,
+                                                  const dom::Optional<dom::OwningNonNull<dom::CameraSetConfigurationCallback> >& aOnSuccess,
+                                                  const dom::Optional<dom::OwningNonNull<dom::CameraErrorCallback> >& aOnError,
+                                                  ErrorResult& aRv);
   void GetMeteringAreas(nsTArray<dom::CameraRegion>& aAreas, ErrorResult& aRv);
   void SetMeteringAreas(const dom::Optional<dom::Sequence<dom::CameraRegion> >& aAreas, ErrorResult& aRv);
   void GetFocusAreas(nsTArray<dom::CameraRegion>& aAreas, ErrorResult& aRv);
   void SetFocusAreas(const dom::Optional<dom::Sequence<dom::CameraRegion> >& aAreas, ErrorResult& aRv);
   void GetPictureSize(dom::CameraSize& aSize, ErrorResult& aRv);
   void SetPictureSize(const dom::CameraSize& aSize, ErrorResult& aRv);
   void GetThumbnailSize(dom::CameraSize& aSize, ErrorResult& aRv);
   void SetThumbnailSize(const dom::CameraSize& aSize, ErrorResult& aRv);
-  void AutoFocus(dom::CameraAutoFocusCallback& aOnSuccess,
-                 const dom::Optional<dom::OwningNonNull<dom::CameraErrorCallback> >& aOnError,
-                 ErrorResult& aRv);
+  already_AddRefed<dom::Promise> AutoFocus(const dom::Optional<dom::OwningNonNull<dom::CameraAutoFocusCallback> >& aOnSuccess,
+                                           const dom::Optional<dom::OwningNonNull<dom::CameraErrorCallback> >& aOnError,
+                                           ErrorResult& aRv);
   void StartFaceDetection(ErrorResult& aRv);
   void StopFaceDetection(ErrorResult& aRv);
-  void TakePicture(const dom::CameraPictureOptions& aOptions,
-                   dom::CameraTakePictureCallback& aOnSuccess,
-                   const dom::Optional<dom::OwningNonNull<dom::CameraErrorCallback> >& aOnError,
-                   ErrorResult& aRv);
-  void StartRecording(const dom::CameraStartRecordingOptions& aOptions,
-                      nsDOMDeviceStorage& storageArea,
-                      const nsAString& filename,
-                      dom::CameraStartRecordingCallback& aOnSuccess,
-                      const dom::Optional<dom::OwningNonNull<dom::CameraErrorCallback> >& aOnError,
-                      ErrorResult& aRv);
+  already_AddRefed<dom::Promise> TakePicture(const dom::CameraPictureOptions& aOptions,
+                                             const dom::Optional<dom::OwningNonNull<dom::CameraTakePictureCallback> >& aOnSuccess,
+                                             const dom::Optional<dom::OwningNonNull<dom::CameraErrorCallback> >& aOnError,
+                                             ErrorResult& aRv);
+  already_AddRefed<dom::Promise> StartRecording(const dom::CameraStartRecordingOptions& aOptions,
+                                                nsDOMDeviceStorage& storageArea,
+                                                const nsAString& filename,
+                                                const dom::Optional<dom::OwningNonNull<dom::CameraStartRecordingCallback> >& aOnSuccess,
+                                                const dom::Optional<dom::OwningNonNull<dom::CameraErrorCallback> >& aOnError,
+                                                ErrorResult& aRv);
   void StopRecording(ErrorResult& aRv);
   void ResumePreview(ErrorResult& aRv);
-  void ReleaseHardware(const dom::Optional<dom::OwningNonNull<dom::CameraReleaseCallback> >& aOnSuccess,
-                       const dom::Optional<dom::OwningNonNull<dom::CameraErrorCallback> >& aOnError,
-                       ErrorResult& aRv);
+  already_AddRefed<dom::Promise> ReleaseHardware(const dom::Optional<dom::OwningNonNull<dom::CameraReleaseCallback> >& aOnSuccess,
+                                                 const dom::Optional<dom::OwningNonNull<dom::CameraErrorCallback> >& aOnError,
+                                                 ErrorResult& aRv);
   void ResumeContinuousFocus(ErrorResult& aRv);
 
   virtual JSObject* WrapObject(JSContext* aCx) MOZ_OVERRIDE;
 
+  IMPL_EVENT_HANDLER(facesdetected)
+  IMPL_EVENT_HANDLER(shutter)
+  IMPL_EVENT_HANDLER(close)
+  IMPL_EVENT_HANDLER(recorderstatechange)
+  IMPL_EVENT_HANDLER(previewstatechange)
+  IMPL_EVENT_HANDLER(focus)
+  IMPL_EVENT_HANDLER(picture)
+  IMPL_EVENT_HANDLER(configurationchange)
+
 protected:
   virtual ~nsDOMCameraControl();
 
   class DOMCameraConfiguration MOZ_FINAL : public dom::CameraConfiguration
   {
   public:
     NS_INLINE_DECL_REFCOUNTING(DOMCameraConfiguration)
 
@@ -174,27 +185,41 @@ protected:
   void OnConfigurationChange(DOMCameraConfiguration* aConfiguration);
   void OnShutter();
   void OnUserError(CameraControlListener::UserContext aContext, nsresult aError);
 
   bool IsWindowStillActive();
 
   nsresult NotifyRecordingStatusChange(const nsString& aMsg);
 
+  already_AddRefed<dom::Promise> CreatePromise(ErrorResult& aRv);
+  void AbortPromise(nsRefPtr<dom::Promise>& aPromise);
+  virtual void EventListenerAdded(nsIAtom* aType) MOZ_OVERRIDE;
+  void DispatchPreviewStateEvent(DOMCameraControlListener::PreviewState aState);
+  void DispatchStateEvent(const nsString& aType, const nsString& aState);
+
   nsRefPtr<ICameraControl> mCameraControl; // non-DOM camera control
 
   // An agent used to join audio channel service.
   nsCOMPtr<nsIAudioChannelAgent> mAudioChannelAgent;
 
   nsresult Set(uint32_t aKey, const dom::Optional<dom::Sequence<dom::CameraRegion> >& aValue, uint32_t aLimit);
   nsresult Get(uint32_t aKey, nsTArray<dom::CameraRegion>& aValue);
 
   nsRefPtr<DOMCameraConfiguration>              mCurrentConfiguration;
   nsRefPtr<dom::CameraCapabilities>             mCapabilities;
 
+  // camera control pending promises
+  nsRefPtr<dom::Promise>                        mGetCameraPromise;
+  nsRefPtr<dom::Promise>                        mAutoFocusPromise;
+  nsRefPtr<dom::Promise>                        mTakePicturePromise;
+  nsRefPtr<dom::Promise>                        mStartRecordingPromise;
+  nsRefPtr<dom::Promise>                        mReleasePromise;
+  nsRefPtr<dom::Promise>                        mSetConfigurationPromise;
+
   // solicited camera control event handlers
   nsRefPtr<dom::GetCameraCallback>              mGetCameraOnSuccessCb;
   nsRefPtr<dom::CameraErrorCallback>            mGetCameraOnErrorCb;
   nsRefPtr<dom::CameraAutoFocusCallback>        mAutoFocusOnSuccessCb;
   nsRefPtr<dom::CameraErrorCallback>            mAutoFocusOnErrorCb;
   nsRefPtr<dom::CameraTakePictureCallback>      mTakePictureOnSuccessCb;
   nsRefPtr<dom::CameraErrorCallback>            mTakePictureOnErrorCb;
   nsRefPtr<dom::CameraStartRecordingCallback>   mStartRecordingOnSuccessCb;
@@ -221,16 +246,17 @@ protected:
   // our viewfinder stream
   nsRefPtr<CameraPreviewMediaStream> mInput;
 
   // set once when this object is created
   nsCOMPtr<nsPIDOMWindow>   mWindow;
 
   dom::CameraStartRecordingOptions mOptions;
   nsRefPtr<DeviceStorageFileDescriptor> mDSFileDescriptor;
+  DOMCameraControlListener::PreviewState mPreviewState;
 
 private:
   nsDOMCameraControl(const nsDOMCameraControl&) MOZ_DELETE;
   nsDOMCameraControl& operator=(const nsDOMCameraControl&) MOZ_DELETE;
 };
 
 } // namespace mozilla
 
--- a/dom/camera/DOMCameraManager.cpp
+++ b/dom/camera/DOMCameraManager.cpp
@@ -141,24 +141,26 @@ public:
                                            nsIContentPermissionRequest)
 
   CameraPermissionRequest(nsIPrincipal* aPrincipal,
                           nsPIDOMWindow* aWindow,
                           nsRefPtr<nsDOMCameraManager> aManager,
                           uint32_t aCameraId,
                           const CameraConfiguration& aInitialConfig,
                           nsRefPtr<GetCameraCallback> aOnSuccess,
-                          nsRefPtr<CameraErrorCallback> aOnError)
+                          nsRefPtr<CameraErrorCallback> aOnError,
+                          nsRefPtr<Promise> aPromise)
     : mPrincipal(aPrincipal)
     , mWindow(aWindow)
     , mCameraManager(aManager)
     , mCameraId(aCameraId)
     , mInitialConfig(aInitialConfig)
     , mOnSuccess(aOnSuccess)
     , mOnError(aOnError)
+    , mPromise(aPromise)
   {
   }
 
 protected:
   virtual ~CameraPermissionRequest()
   {
   }
 
@@ -167,19 +169,23 @@ protected:
   void CallCancel();
   nsCOMPtr<nsIPrincipal> mPrincipal;
   nsCOMPtr<nsPIDOMWindow> mWindow;
   nsRefPtr<nsDOMCameraManager> mCameraManager;
   uint32_t mCameraId;
   CameraConfiguration mInitialConfig;
   nsRefPtr<GetCameraCallback> mOnSuccess;
   nsRefPtr<CameraErrorCallback> mOnError;
+  nsRefPtr<Promise> mPromise;
 };
 
-NS_IMPL_CYCLE_COLLECTION(CameraPermissionRequest, mWindow, mOnSuccess, mOnError)
+NS_IMPL_CYCLE_COLLECTION(CameraPermissionRequest, mWindow,
+                                                  mOnSuccess,
+                                                  mOnError,
+                                                  mPromise)
 
 NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(CameraPermissionRequest)
   NS_INTERFACE_MAP_ENTRY(nsIContentPermissionRequest)
   NS_INTERFACE_MAP_ENTRY(nsIRunnable)
   NS_INTERFACE_MAP_ENTRY_AMBIGUOUS(nsISupports, nsIContentPermissionRequest)
 NS_INTERFACE_MAP_END
 
 NS_IMPL_CYCLE_COLLECTING_ADDREF(CameraPermissionRequest)
@@ -235,98 +241,118 @@ CameraPermissionRequest::DispatchCallbac
     callbackRunnable = NS_NewRunnableMethod(this, &CameraPermissionRequest::CallCancel);
   }
   return NS_DispatchToMainThread(callbackRunnable);
 }
 
 void
 CameraPermissionRequest::CallAllow()
 {
-  mCameraManager->PermissionAllowed(mCameraId, mInitialConfig, mOnSuccess, mOnError);
+  mCameraManager->PermissionAllowed(mCameraId, mInitialConfig, mOnSuccess, mOnError, mPromise);
 }
 
 void
 CameraPermissionRequest::CallCancel()
 {
-  mCameraManager->PermissionCancelled(mCameraId, mInitialConfig, mOnSuccess, mOnError);
+  mCameraManager->PermissionCancelled(mCameraId, mInitialConfig, mOnSuccess, mOnError, mPromise);
 }
 
 NS_IMETHODIMP
 CameraPermissionRequest::GetTypes(nsIArray** aTypes)
 {
   nsTArray<nsString> emptyOptions;
   return nsContentPermissionUtils::CreatePermissionArray(NS_LITERAL_CSTRING("camera"),
                                                          NS_LITERAL_CSTRING("unused"),
                                                          emptyOptions,
                                                          aTypes);
 }
 
-void
+already_AddRefed<Promise>
 nsDOMCameraManager::GetCamera(const nsAString& aCamera,
                               const CameraConfiguration& aInitialConfig,
-                              GetCameraCallback& aOnSuccess,
+                              const OptionalNonNullGetCameraCallback& aOnSuccess,
                               const OptionalNonNullCameraErrorCallback& aOnError,
                               ErrorResult& aRv)
 {
   DOM_CAMERA_LOGT("%s:%d\n", __func__, __LINE__);
 
   uint32_t cameraId = 0;  // back (or forward-facing) camera by default
   if (aCamera.EqualsLiteral("front")) {
     cameraId = 1;
   }
 
-  nsRefPtr<CameraErrorCallback> errorCallback = nullptr;
+  nsCOMPtr<nsIGlobalObject> global = do_QueryInterface(mWindow);
+  if (!global) {
+    aRv.Throw(NS_ERROR_FAILURE);
+    return nullptr;
+  }
+
+  nsRefPtr<Promise> promise = Promise::Create(global, aRv);
+  if (aRv.Failed()) {
+    return nullptr;
+  }
+
+  nsRefPtr<GetCameraCallback> successCallback;
+  if (aOnSuccess.WasPassed()) {
+    successCallback = &aOnSuccess.Value();
+  }
+
+  nsRefPtr<CameraErrorCallback> errorCallback;
   if (aOnError.WasPassed()) {
     errorCallback = &aOnError.Value();
   }
 
   if (mPermission == nsIPermissionManager::ALLOW_ACTION) {
-    PermissionAllowed(cameraId, aInitialConfig, &aOnSuccess, errorCallback);
-    return;
+    PermissionAllowed(cameraId, aInitialConfig, successCallback, errorCallback, promise);
+    return promise.forget();
   }
 
   nsCOMPtr<nsIScriptObjectPrincipal> sop = do_QueryInterface(mWindow);
   if (!sop) {
     aRv.Throw(NS_ERROR_UNEXPECTED);
-    return;
+    return nullptr;
   }
 
   nsCOMPtr<nsIPrincipal> principal = sop->GetPrincipal();
 
   nsCOMPtr<nsIRunnable> permissionRequest =
     new CameraPermissionRequest(principal, mWindow, this, cameraId, aInitialConfig,
-                                &aOnSuccess, errorCallback);
+                                successCallback, errorCallback, promise);
 
   NS_DispatchToMainThread(permissionRequest);
+  return promise.forget();
 }
 
 void
 nsDOMCameraManager::PermissionAllowed(uint32_t aCameraId,
                                       const CameraConfiguration& aInitialConfig,
                                       GetCameraCallback* aOnSuccess,
-                                      CameraErrorCallback* aOnError)
+                                      CameraErrorCallback* aOnError,
+                                      Promise* aPromise)
 {
   mPermission = nsIPermissionManager::ALLOW_ACTION;
 
   // Creating this object will trigger the aOnSuccess callback
   //  (or the aOnError one, if it fails).
   nsRefPtr<nsDOMCameraControl> cameraControl =
-    new nsDOMCameraControl(aCameraId, aInitialConfig, aOnSuccess, aOnError, mWindow);
+    new nsDOMCameraControl(aCameraId, aInitialConfig, aOnSuccess, aOnError, aPromise, mWindow);
 
   Register(cameraControl);
 }
 
 void
 nsDOMCameraManager::PermissionCancelled(uint32_t aCameraId,
                                         const CameraConfiguration& aInitialConfig,
                                         GetCameraCallback* aOnSuccess,
-                                        CameraErrorCallback* aOnError)
+                                        CameraErrorCallback* aOnError,
+                                        Promise* aPromise)
 {
   mPermission = nsIPermissionManager::DENY_ACTION;
 
+  aPromise->MaybeReject(NS_ERROR_DOM_SECURITY_ERR);
   if (aOnError) {
     ErrorResult ignored;
     aOnError->Call(NS_LITERAL_STRING("Permission denied."), ignored);
   }
 }
 
 void
 nsDOMCameraManager::Register(nsDOMCameraControl* aDOMCameraControl)
--- a/dom/camera/DOMCameraManager.h
+++ b/dom/camera/DOMCameraManager.h
@@ -3,16 +3,17 @@
 /* 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 DOM_CAMERA_DOMCAMERAMANAGER_H
 #define DOM_CAMERA_DOMCAMERAMANAGER_H
 
 #include "mozilla/dom/BindingDeclarations.h"
+#include "mozilla/dom/Promise.h"
 #include "nsCOMPtr.h"
 #include "nsAutoPtr.h"
 #include "nsIObserver.h"
 #include "nsHashKeys.h"
 #include "nsWrapperCache.h"
 #include "nsWeakReference.h"
 #include "nsClassHashtable.h"
 #include "nsCycleCollectionParticipant.h"
@@ -27,17 +28,19 @@ namespace mozilla {
     struct CameraConfiguration;
     class GetCameraCallback;
     class CameraErrorCallback;
   }
 }
 
 typedef nsTArray<nsRefPtr<mozilla::nsDOMCameraControl> > CameraControls;
 typedef nsClassHashtable<nsUint64HashKey, CameraControls> WindowTable;
-typedef mozilla::dom::Optional<mozilla::dom::OwningNonNull<mozilla::dom::CameraErrorCallback>>
+typedef mozilla::dom::Optional<mozilla::dom::OwningNonNull<mozilla::dom::GetCameraCallback> >
+          OptionalNonNullGetCameraCallback;
+typedef mozilla::dom::Optional<mozilla::dom::OwningNonNull<mozilla::dom::CameraErrorCallback> >
           OptionalNonNullCameraErrorCallback;
 
 class nsDOMCameraManager MOZ_FINAL
   : public nsIObserver
   , public nsSupportsWeakReference
   , public nsWrapperCache
 {
 public:
@@ -59,29 +62,32 @@ public:
   static bool IsWindowStillActive(uint64_t aWindowId);
 
   void Register(mozilla::nsDOMCameraControl* aDOMCameraControl);
   void OnNavigation(uint64_t aWindowId);
 
   void PermissionAllowed(uint32_t aCameraId,
                          const mozilla::dom::CameraConfiguration& aOptions,
                          mozilla::dom::GetCameraCallback* aOnSuccess,
-                         mozilla::dom::CameraErrorCallback* aOnError);
+                         mozilla::dom::CameraErrorCallback* aOnError,
+                         mozilla::dom::Promise* aPromise);
 
   void PermissionCancelled(uint32_t aCameraId,
                            const mozilla::dom::CameraConfiguration& aOptions,
                            mozilla::dom::GetCameraCallback* aOnSuccess,
-                           mozilla::dom::CameraErrorCallback* aOnError);
+                           mozilla::dom::CameraErrorCallback* aOnError,
+                           mozilla::dom::Promise* aPromise);
 
   // WebIDL
-  void GetCamera(const nsAString& aCamera,
-                 const mozilla::dom::CameraConfiguration& aOptions,
-                 mozilla::dom::GetCameraCallback& aOnSuccess,
-                 const OptionalNonNullCameraErrorCallback& aOnError,
-                 mozilla::ErrorResult& aRv);
+  already_AddRefed<mozilla::dom::Promise>
+  GetCamera(const nsAString& aCamera,
+            const mozilla::dom::CameraConfiguration& aOptions,
+            const OptionalNonNullGetCameraCallback& aOnSuccess,
+            const OptionalNonNullCameraErrorCallback& aOnError,
+            mozilla::ErrorResult& aRv);
   void GetListOfCameras(nsTArray<nsString>& aList, mozilla::ErrorResult& aRv);
 
   nsPIDOMWindow* GetParentObject() const { return mWindow; }
   virtual JSObject* WrapObject(JSContext* aCx)
     MOZ_OVERRIDE;
 
 protected:
   void XpComShutdown();
new file mode 100644
--- /dev/null
+++ b/dom/camera/test/callback/test_bug1022766.html
@@ -0,0 +1,97 @@
+<!DOCTYPE HTML>
+<html>
+<head>
+  <title>Test for bug 1022766</title>
+  <script type="text/javascript" src="/MochiKit/MochiKit.js"></script>
+  <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
+  <script type="text/javascript" src="../camera_common.js"></script>
+  <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
+</head>
+<body>
+<video id="viewfinder" width="200" height="200" autoplay></video>
+<img src="#" alt="This image is going to load" id="testimage"/>
+<script class="testbody" type="text/javascript;version=1.7">
+
+var whichCamera = navigator.mozCameras.getListOfCameras()[0];
+var config = {
+  mode: 'picture',
+  recorderProfile: 'cif',
+  previewSize: {
+    width: 352,
+    height: 288
+  }
+};
+
+function onError(e) {
+  ok(false, "Error" + JSON.stringify(e));
+}
+
+var Camera = {
+  cameraObj: null,
+  _otherPictureSize: null,
+  get viewfinder() {
+    return document.getElementById('viewfinder');
+  },
+
+  firstCallFailed: false,
+  secondCallSucceeded: false,
+  checkForDone: function test_checkForDone() {
+    if (Camera.firstCallFailed && Camera.secondCallSucceeded) {
+      Camera.cameraObj.release();
+      Camera.cameraObj = null;
+      CameraTest.end();
+    }
+  },
+
+  successOne: function test_successOne(focused) {
+    ok(false, "First call to autoFocus() succeeded unexpectedly");
+  },
+  failureOne: function test_failureOne(error) {
+    ok(error == "AutoFocusInterrupted", "First call to autoFocus() failed with: "
+      + error);
+    Camera.firstCallFailed = true;
+    Camera.checkForDone();
+  },
+  successTwo: function test_successTwo(focused) {
+    ok(true, "Second call to autoFocus() succeeded");
+    Camera.secondCallSucceeded = true;
+    Camera.checkForDone();
+  },
+  failureTwo: function test_failureTwo(error) {
+    ok(false, "Second call to autoFocus() failed unexpectedly with: " + error);
+  },
+
+  start: function test_start() {
+    function onSuccess(camera, config) {
+      Camera.cameraObj = camera;
+      Camera.viewfinder.mozSrcObject = camera;
+      Camera.viewfinder.play();
+
+      // It doesn't matter if the emulator supports focus or not;
+      // this is just testing the sequencing.
+      camera.autoFocus(Camera.successOne, Camera.failureOne);
+      camera.autoFocus(Camera.successTwo, Camera.failureTwo);
+    };
+
+    navigator.mozCameras.getCamera(whichCamera, config, onSuccess, onError);
+  }
+}
+
+window.addEventListener('beforeunload', function() {
+  Camera.viewfinder.mozSrcObject = null;
+  if (Camera.cameraObj) {
+    Camera.cameraObj.release();
+    Camera.cameraObj = null;
+  }
+});
+
+CameraTest.begin("hardware", function(test) {
+  test.set("auto-focus-process-failure", function() {
+    Camera.start();
+  })
+});
+
+</script>
+</body>
+
+</html>
new file mode 100644
--- /dev/null
+++ b/dom/camera/test/callback/test_bug975472.html
@@ -0,0 +1,223 @@
+<!DOCTYPE HTML>
+<html>
+<head>
+  <title>Test for bug 975472</title>
+  <script type="text/javascript" src="/MochiKit/MochiKit.js"></script>
+  <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
+  <script type="text/javascript" src="../camera_common.js"></script>
+  <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
+</head>
+<body>
+<video id="viewfinder" width="200" height="200" autoplay></video>
+<img src="#" alt="This image is going to load" id="testimage"/>
+<script class="testbody" type="text/javascript;version=1.7">
+
+var whichCamera = navigator.mozCameras.getListOfCameras()[0];
+var config = {
+  mode: 'picture',
+  recorderProfile: 'cif',
+  previewSize: {
+    width: 352,
+    height: 288
+  }
+};
+var options = {
+  rotation: 0,
+  position: {
+    latitude: 43.645687,
+    longitude: -79.393661
+  },
+  dateTime: Date.now()
+};
+
+function onError(e) {
+  ok(false, "Error" + JSON.stringify(e));
+}
+function next() {
+  Camera.nextTest();
+}
+
+// The array of tests
+var tests = [
+  {
+    key: "release-after-release",
+    func: function testAutoFocus(camera) {
+      function onSuccess(success) {
+        ok(true, "release() succeeded");
+        next();
+      }
+      function onError(error) {
+        ok(false, "release() failed with: " + error);
+      }
+      camera.release(onSuccess, onError);
+    }
+  },
+  {
+    key: "set-picture-size-after-release",
+    func: function testSetPictureSize(camera) {
+      camera.setPictureSize({ width: 0, height: 0 });
+      next();
+    }
+  },
+  {
+    key: "set-thumbnail-size-after-release",
+    func: function testSetThumbnailSize(camera) {
+      camera.setThumbnailSize({ width: 0, height: 0 });
+      next();
+    }
+  },
+  {
+    key: "get-sensor-angle-after-release",
+    func: function testGetSensorAngle(camera) {
+      ok(camera.sensorAngle == 0, "camera.sensorAngle = " + camera.sensorAngle);
+      next();
+    }
+  },
+  {
+    key: "resume-preview-after-release",
+    func: function testResumePreview(camera) {
+      camera.resumePreview();
+      next();
+    }
+  },
+  {
+    key: "auto-focus-after-release",
+    func: function testAutoFocus(camera) {
+      function onSuccess(success) {
+        ok(false, "autoFocus() succeeded incorrectly");
+      }
+      function onError(error) {
+        ok(error === "HardwareClosed", "autoFocus() failed with: " + error);
+        next();
+      }
+      camera.autoFocus(onSuccess, onError);
+    }
+  },
+  {
+    key: "take-picture-after-release",
+    func: function testTakePicture(camera) {
+      function onSuccess(picture) {
+        ok(false, "takePicture() succeeded incorrectly");
+      }
+      function onError(error) {
+        ok(error === "HardwareClosed", "takePicture() failed with: " + error);
+        next();
+      }
+      camera.takePicture(null, onSuccess, onError);
+    }
+  },
+  {
+    key: "start-recording-after-release",
+    func: function testStartRecording(camera) {
+      function onSuccess(picture) {
+        ok(false, "startRecording() process succeeded incorrectly");
+      }
+      function onError(error) {
+        ok(error === "GeneralFailure", "startRecording() failed with: " + error);
+        next();
+      }
+      var recordingOptions = {
+        profile: 'cif',
+        rotation: 0
+      };
+      camera.startRecording(recordingOptions,
+                            navigator.getDeviceStorage('videos'),
+                            'bug975472.mp4',
+                            onSuccess, onError);
+    }
+  },
+  {
+    key: "stop-recording-after-release",
+    func: function testStopRecording(camera) {
+      camera.stopRecording();
+      next();
+    }
+  },
+  {
+    key: "set-configuration-after-release",
+    func: function testSetConfiguration(camera) {
+      function onSuccess(picture) {
+        ok(false, "setConfiguration() process succeeded incorrectly");
+      }
+      function onError(error) {
+        ok(error === "HardwareClosed", "setConfiguration() failed with: " + error);
+        next();
+      }
+      camera.setConfiguration(config, onSuccess, onError);
+    }
+  },
+];
+
+var testGenerator = function() {
+  for (var i = 0; i < tests.length; ++i ) {
+    yield tests[i];
+  }
+}();
+
+var Camera = {
+  cameraObj: null,
+  _otherPictureSize: null,
+  get viewfinder() {
+    return document.getElementById('viewfinder');
+  },
+  onCameraReady: function () {
+    Camera.nextTest = function() {
+      try {
+        var t = testGenerator.next();
+        info("test: " + t.key);
+        t.func(Camera.cameraObj);
+      } catch(e) {
+        if (e instanceof StopIteration) {
+          CameraTest.end();
+        } else {
+          throw e;
+        }
+      }
+    };
+    // Release the camera hardware, and call all of the asynchronous methods
+    // to make sure they properly handle being in this state.
+    Camera.cameraObj.release();
+    next();
+  },
+  release: function release() {
+    cameraObj = null;
+  },
+  start: function run_test() {
+    function onSuccess(camera, config) {
+      Camera.cameraObj = camera;
+      Camera.viewfinder.mozSrcObject = camera;
+      Camera.viewfinder.play();
+      ok(camera.capabilities.pictureSizes.length > 0,
+        "capabilities.pictureSizes.length = " +
+        camera.capabilities.pictureSizes.length);
+      Camera._otherPictureSize = camera.capabilities.pictureSizes.slice(-1)[0];
+      camera.setPictureSize(camera.capabilities.pictureSizes[0]);
+      options.pictureSize = Camera._otherPictureSize;
+      options.fileFormat = camera.capabilities.fileFormats[0];
+      info("getCamera callback, setting pictureSize = " + options.pictureSize.toSource());
+      Camera.cameraObj.onPreviewStateChange = function(state) {
+        if (state === 'started') {
+          info("viewfinder is ready and playing");
+          Camera.cameraObj.onPreviewStateChange = null;
+          Camera.onCameraReady();
+        }
+      };
+    };
+    navigator.mozCameras.getCamera(whichCamera, config, onSuccess, onError);
+  }
+}
+
+SimpleTest.waitForExplicitFinish();
+
+window.addEventListener('beforeunload', function() {
+  Camera.viewfinder.mozSrcObject = null;
+  Camera.cameraObj.release();
+  Camera.cameraObj = null;
+});
+
+Camera.start();
+
+</script>
+</body>
+
+</html>
new file mode 100644
--- /dev/null
+++ b/dom/camera/test/callback/test_camera.html
@@ -0,0 +1,242 @@
+<!DOCTYPE HTML>
+<html>
+<head>
+  <title>Test for mozCameras.getCamera() with separate .setConfiguration() call</title>
+  <script type="text/javascript" src="/MochiKit/MochiKit.js"></script>
+  <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
+  <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
+</head>
+<body>
+<video id="viewfinder" width="200" height="200" autoplay></video>
+<img src="#" alt="This image is going to load" id="testimage"/>
+<script class="testbody" type="text/javascript;version=1.7">
+
+var whichCamera = navigator.mozCameras.getListOfCameras()[0];
+var options = {
+  mode: 'picture',
+  recorderProfile: 'cif',
+  previewSize: {
+    width: 352,
+    height: 288
+  }
+};
+
+var config = {
+  dateTime: Date.now() / 1000,
+  pictureSize: null,
+  fileFormat: 'jpeg',
+  rotation: 90
+};
+
+function onError(e) {
+  ok(false, "Error" + JSON.stringify(e));
+}
+
+var capabilities = [ 'previewSizes', 'pictureSizes', 'fileFormats', 'maxFocusAreas', 'minExposureCompensation',
+                     'maxExposureCompensation', 'stepExposureCompensation', 'maxMeteringAreas', 'videoSizes',
+                     'recorderProfiles', 'zoomRatios', 'isoModes'];
+
+var Camera = {
+  cameraObj: null,
+  _recording: false,
+  _currentTest: null,
+  _autoFocusSupported: 0,
+  _manuallyFocused: false,
+  _flashmodes: null,
+  _pictureSizes: null,
+  _previewSizes: null,
+  _whiteBalanceModes: null,
+  _zoomRatios: null,
+  _sceneModes: null,
+  _focusModes: null,
+  _zoomRatios: null,
+  _testsCompleted: 0,
+  _shutter: 0,
+  _config: {
+    dateTime: Date.now() / 1000,
+    pictureSize: null,
+    fileFormat: 'jpeg',
+    rotation: 90
+  },
+  _tests: null,
+  get viewfinder() {
+    return document.getElementById('viewfinder');
+  },
+  setFlashMode: function camera_setFlash(mode) {
+    this.cameraObj.flashMode = mode;
+  },
+  setFocus: function camera_setfocus(mode) {
+    this.cameraObj.focus = mode;
+  },
+  setZoom: function camera_setZoom(zoom) {
+    this.cameraObj.zoom = zoom;
+  },
+  getZoom: function camera_getZoom() {
+    return this.cameraObj.zoom;
+  },
+  getFileFormats: function camera_formats() {
+    this._fileFormats = this.cameraObj.capabilities.fileFormats;
+  },
+  getFlashModes: function camera_getFlash() {
+    this._flashmodes = this.cameraObj.capabilities.flashModes;
+  },
+  getFocusModes: function camera_getFocus() {
+    this._focusModes = this.cameraObj.capabilities.focusModes;
+  },
+  getSceneModes: function camera_getScene() {
+    this._sceneModes = this.cameraObj.capabilities.sceneModes;
+  },
+  getZoomRatios: function camera_getZoom() {
+    this._zoomRatios = this.cameraObj.capabilities.zoomRatios;
+  },
+  getWhiteBalance: function camera_white() {
+    this._whitebalanceModes = this.cameraObj.capabilities.whiteBalanceModes;
+  },
+  getPictureSizes: function camera_sizes() {
+    this._pictureSizes = this.cameraObj.capabilities.pictureSizes;
+  },
+  getPreviewSizes: function camera_preview() {
+    this._previewSizes = this.cameraObj.capabilities.previewSizes;
+  },
+  getZoomRatios: function camera_preview() {
+    this._zoomRatios = this.cameraObj.capabilities.zoomRatios;
+  },
+  takePictureSuccess: function taken_foto(blob) {
+    var img = new Image();
+    var test = this._currentTest;
+    img.onload = function Imgsize() {
+      ok(this.width == test.pictureSize.width, "The image taken has the width " + 
+                                              this.width + " pictureSize width = " + test.pictureSize.width);
+      ok(this.height == test.pictureSize.height, "The image taken has the height " + 
+                                              this.height + " picturesize height = " + test.pictureSize.height);
+      Camera._testsCompleted++;
+      if(Camera._testsCompleted == Camera._tests.length) {
+        ok(true, "test finishing");
+        SimpleTest.finish();
+      } else {
+        Camera.runTests();
+      }
+    }
+    ok(blob.size > 100 , "Blob Size Gathered = " + blob.size);
+    ok("image/" + test.fileFormat ==  blob.type, "Blob Type = " + blob.type);
+    img.src = window.URL.createObjectURL(blob);
+  },
+  shutter: function onShutter () {
+    Camera._shutter++;
+    
+    ok(Camera._shutter == (Camera._testsCompleted + 1), "on Shutter has been called " +
+                           Camera._shutter + " times");
+
+  },
+  onReady: function onReady() {
+    var camcap = Camera.cameraObj.capabilities;
+    var tests = {};
+    for (var prop in capabilities) {
+      prop = capabilities[prop];
+      ok(camcap[prop] || isFinite(camcap[prop]) || camcap[prop] == null, "Camera Capability: " +
+                    prop + " is exposed, value = " + JSON.stringify(camcap[prop]));
+    }
+    ok(camcap.maxMeteringAreas >= 0, "maxMeteringAreas = " + camcap.maxMeteringAreas);
+    ok(camcap.maxFocusAreas >= 0, "maxFocusAreas = " + camcap.maxFocusAreas);
+    for (var prop in camcap) {
+      if(camcap[prop] && camcap[prop].length > 1)  {
+        tests[prop] = camcap[prop];
+      }
+    }
+    Camera.getPictureSizes();
+    Camera.getPreviewSizes();
+    Camera.getFileFormats();
+    Camera.getFocusModes();
+    Camera.getZoomRatios();
+    ok(Camera._previewSizes.length > 0, "previewSizes length = " + Camera._previewSizes.length);
+    ok(Camera._pictureSizes.length > 0, "picturesizes length = " + Camera._pictureSizes.length);
+    ok(Camera._fileFormats.length > 0, "file formats length = " + Camera._fileFormats.length);
+    ok(camcap.isoModes.length == 0, "ISO modes length = " + camcap.isoModes.length);
+
+    // The emulator doesn't support zoom, so these parameters will be very constrained
+    // For more ambitious tests, see test_camera_fake_parameters.html
+    ok(Camera._zoomRatios.length == 1, "zoom ratios length = " + Camera._zoomRatios.length);
+    ok(Camera.cameraObj.zoom == 1.0, "zoom = " + Camera.cameraObj.zoom);
+    // Test snapping to supported values
+    Camera.cameraObj.zoom = 0.9;
+    ok(Camera.cameraObj.zoom == 1.0, "zoom (lower limit) = " + Camera.cameraObj.zoom);
+    Camera.cameraObj.zoom = 1.1;
+    ok(Camera.cameraObj.zoom == 1.0, "zoom (upper limit) = " + Camera.cameraObj.zoom);
+
+    // Check image quality handling
+    Camera.cameraObj.pictureQuality = 0.0;
+    ok(Camera.cameraObj.pictureQuality == 0.0, "picture quality = " + Camera.cameraObj.pictureQuality);
+    Camera.cameraObj.pictureQuality = -0.1;
+    ok(Camera.cameraObj.pictureQuality == 0.0, "picture quality (minimum limit) = " + Camera.cameraObj.pictureQuality);
+    Camera.cameraObj.pictureQuality = -Math.pow(2, 80);
+    ok(Camera.cameraObj.pictureQuality == 0.0, "picture quality (BIG negative) = " + Camera.cameraObj.pictureQuality);
+    Camera.cameraObj.pictureQuality = 1.0;
+    ok(Camera.cameraObj.pictureQuality == 1.0, "picture quality = " + Camera.cameraObj.pictureQuality);
+    Camera.cameraObj.pictureQuality = 1.1;
+    ok(Camera.cameraObj.pictureQuality == 1.0, "picture quality (maximum limit) = " + Camera.cameraObj.pictureQuality);
+    Camera.cameraObj.pictureQuality = Math.pow(2, 80);
+    ok(Camera.cameraObj.pictureQuality == 1.0, "picture quality (BIG positive) = " + Camera.cameraObj.pictureQuality);
+
+    Camera._tests = new Array();
+    for (var i in Camera._pictureSizes) {
+      for (var l in Camera._fileFormats) {
+        var config = {
+          pictureSize: Camera._pictureSizes[i],
+          fileFormat: Camera._fileFormats[l]
+        };
+        Camera._tests.push(config);
+      }
+    }
+    Camera.runTests();
+  },
+  runTests: function run_tests() {
+    var test = this._tests[this._testsCompleted];
+    this._currentTest = test;
+    Camera.setFlashMode(test.flashMode);
+    config.fileFormat = test.fileFormat;
+    config.pictureSize = test.pictureSize;
+    ok(true, "testing picture size " + JSON.stringify(config.pictureSize));
+    Camera.cameraObj.takePicture(config, this.takePictureSuccess.bind(this), onError);
+  },
+  onConfigChange: function onConfigChange(config) {
+    ok(config.mode === options.mode, "configuration mode = " + config.mode);
+    ok(config.recorderProfile === options.recorderProfile, "recorder profile = " + config.recorderProfile);
+    ok(config.previewSize.width === options.previewSize.width &&
+      config.previewSize.height === options.previewSize.height,
+      "preview size (w x h) = " + config.previewSize.width + " x " + config.previewSize.height);
+  },
+  setUp: function setup_tests() {
+    function onSuccess(camera) {
+      Camera.cameraObj = camera;
+      Camera.viewfinder.mozSrcObject = camera;
+      Camera.viewfinder.play();
+      Camera.cameraObj.onPreviewStateChange = function(state) {
+        if (state === 'started') {
+          ok(true, "viewfinder is ready and playing");
+          Camera.cameraObj.onPreviewStateChange = null;
+          Camera.onReady();
+        }
+      };
+      SimpleTest.expectAssertions(0);
+      ok(true, "Camera Control object has been successfully initialized");
+      Camera.cameraObj.setConfiguration(options, Camera.onConfigChange, onError);
+      Camera.cameraObj.onShutter = Camera.shutter;
+    };
+    navigator.mozCameras.getCamera(whichCamera, null, onSuccess, onError);
+  }
+}
+
+SimpleTest.waitForExplicitFinish();
+
+window.addEventListener('beforeunload', function() {
+  Camera.viewfinder.mozSrcObject = null;
+  Camera.cameraObj.release();
+  Camera.cameraObj = null;
+});
+
+Camera.setUp();
+
+</script>
+</body>
+
+</html>
new file mode 100644
--- /dev/null
+++ b/dom/camera/test/callback/test_camera_2.html
@@ -0,0 +1,200 @@
+<!DOCTYPE HTML>
+<html>
+<head>
+  <title>Test for mozCameras.getCamera() using an initial configuration</title>
+  <script type="text/javascript" src="/MochiKit/MochiKit.js"></script>
+  <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
+  <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
+</head>
+<body>
+<video id="viewfinder" width="200" height="200" autoplay></video>
+<img src="#" alt="This image is going to load" id="testimage"/>
+<script class="testbody" type="text/javascript;version=1.7">
+
+var whichCamera = navigator.mozCameras.getListOfCameras()[0];
+var options = {
+  mode: 'picture',
+  recorderProfile: 'cif',
+  previewSize: {
+    width: 352,
+    height: 288
+  }
+};
+
+var config = {
+  dateTime: Date.now() / 1000,
+  pictureSize: null,
+  fileFormat: 'jpeg',
+  rotation: 90
+};
+
+function onError(e) {
+  ok(false, "Error" + JSON.stringify(e));
+}
+
+var capabilities = [ 'previewSizes', 'pictureSizes', 'fileFormats', 'maxFocusAreas', 'minExposureCompensation',
+                     'maxExposureCompensation', 'stepExposureCompensation', 'maxMeteringAreas', 'videoSizes',
+                     'recorderProfiles'];
+
+var Camera = {
+  cameraObj: null,
+  _recording: false,
+  _currentTest: null,
+  _autoFocusSupported: 0,
+  _manuallyFocused: false,
+  _flashmodes: null,
+  _pictureSizes: null,
+  _previewSizes: null,
+  _whiteBalanceModes: null,
+  _zoomRatios: null,
+  _sceneModes: null,
+  _focusModes: null,
+  _testsCompleted: 0,
+  _shutter: 0,
+  _config: {
+    dateTime: Date.now() / 1000,
+    pictureSize: null,
+    fileFormat: 'jpeg',
+    rotation: 90
+  },
+  _tests: null,
+  get viewfinder() {
+    return document.getElementById('viewfinder');
+  },
+  setFlashMode: function camera_setFlash(mode) {
+    this.cameraObj.flashMode = mode;
+  },
+  setFocus: function camera_setfocus(mode) {
+    this.cameraObj.focus = mode;
+  },
+  getFileFormats: function camera_formats() {
+    this._fileFormats = this.cameraObj.capabilities.fileFormats;
+  },
+  getFlashModes: function camera_getFlash() {
+    this._flashmodes = this.cameraObj.capabilities.flashModes;
+  },
+  getFocusModes: function camera_getFocus() {
+    this._focusModes = this.cameraObj.capabilities.focusModes;
+  },
+  getSceneModes: function camera_getScene() {
+    this._sceneModes = this.cameraObj.capabilities.sceneModes;
+  },
+  getZoomRatios: function camera_getZoom() {
+    this._zoomRatios = this.cameraObj.capabilities.zoomRatios;
+  },
+  getWhiteBalance: function camera_white() {
+    this._whitebalanceModes = this.cameraObj.capabilities.whiteBalanceModes;
+  },
+  getPictureSizes: function camera_sizes() {
+    this._pictureSizes = this.cameraObj.capabilities.pictureSizes;
+  },
+  getPreviewSizes: function camera_preview() {
+    this._previewSizes = this.cameraObj.capabilities.previewSizes;
+  },
+  takePictureSuccess: function taken_foto(blob) {
+    var img = new Image();
+    var test = this._currentTest;
+    img.onload = function Imgsize() {
+      ok(this.width == test.pictureSize.width, "The image taken has the width " +
+                                              this.width + " pictureSize width = " + test.pictureSize.width);
+      ok(this.height == test.pictureSize.height, "The image taken has the height " +
+                                              this.height + " picturesize height = " + test.pictureSize.height);
+      Camera._testsCompleted++;
+      if(Camera._testsCompleted == Camera._tests.length) {
+        ok(true, "test finishing");
+        SimpleTest.finish();
+      } else {
+        Camera.runTests();
+      }
+    }
+    ok(blob.size > 100 , "Blob Size Gathered = " + blob.size);
+    ok("image/" + test.fileFormat ==  blob.type, "Blob Type = " + blob.type);
+    img.src = window.URL.createObjectURL(blob);
+  },
+  shutter: function onShutter () {
+    Camera._shutter++;
+    
+    ok(Camera._shutter == (Camera._testsCompleted + 1), "on Shutter has been called " +
+                           Camera._shutter + " times");
+
+  },
+  onReady: function onReady() {
+    var camcap = Camera.cameraObj.capabilities;
+    var tests = {};
+    for (var prop in capabilities) {
+      prop = capabilities[prop];
+      ok(camcap[prop] || isFinite(camcap[prop]) || camcap[prop] == null, "Camera Capability: " +
+                    prop + " is exposed, value = " + JSON.stringify(camcap[prop]));
+    } 
+    for (var prop in camcap) {
+      if(camcap[prop] && camcap[prop].length > 1)  {
+        tests[prop] = camcap[prop];
+      }
+    }
+    Camera.getPictureSizes();
+    Camera.getPreviewSizes();
+    Camera.getFileFormats();
+    Camera.getFocusModes();
+    ok(Camera._previewSizes.length > 0, "previewSizes length = " + Camera._previewSizes.length);
+    ok(Camera._pictureSizes.length > 0, "picturesizes length = " + Camera._pictureSizes.length);
+    ok(Camera._fileFormats.length > 0, "file formats length = " + Camera._fileFormats.length);
+    Camera._tests = new Array();
+    for (var i in Camera._pictureSizes) {
+      for (var l in Camera._fileFormats) {
+        var config = {
+          pictureSize: Camera._pictureSizes[i],
+          fileFormat: Camera._fileFormats[l]
+        };
+        Camera._tests.push(config);
+      }
+    }
+    Camera.runTests();
+  },
+  runTests: function run_tests() {
+    var test = this._tests[this._testsCompleted];
+    this._currentTest = test;
+    Camera.setFlashMode(test.flashMode);
+    config.fileFormat = test.fileFormat;
+    config.pictureSize = test.pictureSize;
+    ok(true, "testing picture size " + JSON.stringify(config.pictureSize));
+    Camera.cameraObj.takePicture(config, this.takePictureSuccess.bind(this), onError);
+  },
+  setUp: function setup_tests() {
+    function onSuccess(camera, config) {
+      ok(true, "Camera Control object has been successfully initialized");
+      ok(config.mode === options.mode, "configuration mode = " + config.mode);
+      ok(config.recorderProfile === options.recorderProfile, "recorder profile = " + config.recorderProfile);
+      ok(config.previewSize.width === options.previewSize.width &&
+        config.previewSize.height === options.previewSize.height,
+        "preview size (w x h) = " + config.previewSize.width + " x " + config.previewSize.height);
+      Camera.cameraObj = camera;
+      Camera.viewfinder.mozSrcObject = camera;
+      Camera.viewfinder.play();
+      Camera.cameraObj.onPreviewStateChange = function(state) {
+        if (state === 'started') {
+          ok(true, "viewfinder is ready and playing");
+          Camera.cameraObj.onPreviewStateChange = null;
+          Camera.onReady();
+        }
+      };
+      SimpleTest.expectAssertions(0);
+      Camera.cameraObj.onShutter = Camera.shutter;
+    };
+    navigator.mozCameras.getCamera(whichCamera, options, onSuccess, onError);
+  }
+}
+
+SimpleTest.waitForExplicitFinish();
+
+window.addEventListener('beforeunload', function() {
+  Camera.viewfinder.mozSrcObject = null;
+  Camera.cameraObj.release();
+  Camera.cameraObj = null;
+});
+
+Camera.setUp();
+
+</script>
+</body>
+
+</html>
new file mode 100644
--- /dev/null
+++ b/dom/camera/test/callback/test_camera_3.html
@@ -0,0 +1,76 @@
+<!DOCTYPE HTML>
+<html>
+<head>
+  <title>Test for multiple calls to mozCameras.getCamera()</title>
+  <script type="text/javascript" src="/MochiKit/MochiKit.js"></script>
+  <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
+  <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
+</head>
+<body>
+<video id="viewfinder" width="200" height="200" autoplay></video>
+<img src="#" alt="This image is going to load" id="testimage"/>
+<script class="testbody" type="text/javascript;version=1.7">
+
+var whichCamera = navigator.mozCameras.getListOfCameras()[0];
+var options = {
+  mode: 'picture',
+  recorderProfile: 'cif',
+  previewSize: {
+    width: 352,
+    height: 288
+  }
+};
+
+function onError(e) {
+  ok(false, "Error" + JSON.stringify(e));
+}
+
+var Camera = {
+  cameraObj: null,
+  get viewfinder() {
+    return document.getElementById('viewfinder');
+  },
+  onReady: function take_two() {
+    function onSuccess(camera, config) {
+      ok(false, "Unexpectedly got second camera instance: " + config.toSource);
+    }
+    function onFailure(error) {
+      ok(true, "Correctly failed to get camera again");
+      SimpleTest.finish();
+    }
+    navigator.mozCameras.getCamera(whichCamera, options, onSuccess, onFailure);
+  },
+  release: function release() {
+    cameraObj = null;
+  },
+  start: function run_test() {
+    function onSuccess(camera, config) {
+      Camera.cameraObj = camera;
+      Camera.viewfinder.mozSrcObject = camera;
+      Camera.viewfinder.play();
+      Camera.cameraObj.onPreviewStateChange = function(state) {
+        if (state === 'started') {
+          ok(true, "viewfinder is ready and playing");
+          Camera.cameraObj.onPreviewStateChange = null;
+          Camera.onReady();
+        }
+      };
+    };
+    navigator.mozCameras.getCamera(whichCamera, options, onSuccess, onError);
+  }
+}
+
+SimpleTest.waitForExplicitFinish();
+
+window.addEventListener('beforeunload', function() {
+  Camera.viewfinder.mozSrcObject = null;
+  Camera.cameraObj.release();
+  Camera.cameraObj = null;
+});
+
+Camera.start();
+
+</script>
+</body>
+
+</html>
new file mode 100644
--- /dev/null
+++ b/dom/camera/test/callback/test_camera_hardware_auto_focus_moving_cb.html
@@ -0,0 +1,131 @@
+<!DOCTYPE HTML>
+<html>
+<!--
+https://bugzilla.mozilla.org/show_bug.cgi?id=965421
+-->
+<head>
+  <title>Bug 965421 - Test camera hardware API for Auto focus moving Callback</title>
+  <script type="text/javascript" src="/MochiKit/MochiKit.js"></script>
+  <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
+  <script type="text/javascript" src="../camera_common.js"></script>
+  <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
+</head>
+<body>
+  <a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=965421">Mozilla Bug 965421</a>
+  <video id="viewfinder" width = "200" height = "200" autoplay></video>
+  <img src="#" alt="This image is going to load" id="testimage"/>
+
+<script class="testbody" type="text/javascript;version=1.7">
+
+var whichCamera = navigator.mozCameras.getListOfCameras()[0];
+var initialConfig = {
+  mode: 'picture',
+  recorderProfile: 'cif',
+  previewSize: {
+    width: 352,
+    height: 288
+  }
+};
+
+const PREF_AUTOFOCUSCALLBACK_ENABLED = "camera.control.autofocus_moving_callback.enabled";
+
+var cameraObj;
+var oldPref;
+
+// Shorthand functions
+function end() {
+  function reallyEnd() {
+    CameraTest.end();
+  }
+  if (oldPref) {
+    SpecialPowers.pushPrefEnv(
+      {'set': [[PREF_AUTOFOCUSCALLBACK_ENABLED, oldPref]]}, reallyEnd);
+  } else {
+    SpecialPowers.pushPrefEnv(
+      {'clear': [[PREF_AUTOFOCUSCALLBACK_ENABLED]]}, reallyEnd);
+  }
+}
+function next() {
+  CameraTest.next();
+}
+
+var tests = [
+  {
+    key: "autofocus-moving-true",
+    func: function testAutoFocusMovingIsTrue(camera) {
+      camera.onAutoFocusMoving = function(aIsMoving) {
+        ok(aIsMoving == true,"onAutoFocusMoving callback received true correctly");
+        camera.focusMode = 'auto';
+        next();
+      }
+      camera.focusMode = 'continuous-picture';
+    }
+  },
+  {
+    key: "autofocus-moving-false",
+    func: function testAutoFocusMovingIsFalse(camera) {
+      camera.onAutoFocusMoving = function(aIsMoving) {
+        ok(aIsMoving == false, "onAutoFocusMoving callback received false correctly");
+        camera.focusMode = 'auto';
+        end();
+      }
+      camera.focusMode = 'continuous-video';
+    }
+  },
+];
+
+var testGenerator = function() {
+  for (var i = 0; i < tests.length; ++i ) {
+    yield tests[i];
+  }
+}();
+
+window.addEventListener('beforeunload', function() {
+  document.getElementById('viewfinder').mozSrcObject = null;
+  cameraObj.release();
+  cameraObj = null;
+});
+
+// Must call CameraTest.begin() before any other async methods.
+CameraTest.begin("hardware", function(test) {
+  // If the pref doesn't exist, this get will fail; catch it and continue.
+  try {
+    oldPref = SpecialPowers.getBoolPref(PREF_AUTOFOCUSCALLBACK_ENABLED);
+  } catch(e) { }
+
+  SpecialPowers.pushPrefEnv({'set': [[PREF_AUTOFOCUSCALLBACK_ENABLED, true]]}, function() {
+    var enabled;
+    try {
+      enabled = SpecialPowers.getBoolPref(PREF_AUTOFOCUSCALLBACK_ENABLED);
+    } catch(e) { }
+    ok(enabled, PREF_AUTOFOCUSCALLBACK_ENABLED + " is " + enabled);
+
+    function onSuccess(camera, config) {
+      document.getElementById('viewfinder').mozSrcObject = camera;
+      cameraObj = camera;
+      CameraTest.next = function() {
+        try {
+          var t = testGenerator.next();
+          test.set(t.key, t.func.bind(undefined, camera));
+        } catch(e) {
+          if (e instanceof StopIteration) {
+            end();
+          } else {
+            throw e;
+          }
+        }
+      };
+      next();
+    }
+    function onError(error) {
+      ok(false, "getCamera() failed with: " + error);
+      end();
+    }
+    navigator.mozCameras.getCamera(whichCamera, initialConfig, onSuccess, onError);
+  })
+});
+
+</script>
+</body>
+
+</html>
new file mode 100644
--- /dev/null
+++ b/dom/camera/test/callback/test_camera_hardware_face_detection.html
@@ -0,0 +1,320 @@
+<!DOCTYPE HTML>
+<html>
+<!--
+https://bugzilla.mozilla.org/show_bug.cgi?id=965420
+-->
+<head>
+  <title>Bug 965420 - Test camera hardware API for face detection</title>
+  <script type="text/javascript" src="/MochiKit/MochiKit.js"></script>
+  <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
+  <script type="text/javascript" src="../camera_common.js"></script>
+  <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
+</head>
+<body>
+  <a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=965420">Mozilla Bug 965420</a>
+  <video id="viewfinder" width = "200" height = "200" autoplay></video>
+  <img src="#" alt="This image is going to load" id="testimage"/>
+
+<script class="testbody" type="text/javascript;version=1.7">
+
+var whichCamera = navigator.mozCameras.getListOfCameras()[0];
+var initialConfig = {
+  mode: 'picture',
+  recorderProfile: 'cif',
+  previewSize: {
+    width: 352,
+    height: 288
+  }
+};
+
+const PREF_FACEDETECTION_ENABLED = "camera.control.face_detection.enabled";
+
+var cameraObj;
+var oldPref;
+
+// Shorthand functions
+function end() {
+  function reallyEnd() {
+    CameraTest.end();
+  }
+  if (oldPref) {
+    SpecialPowers.pushPrefEnv(
+      {'set': [[PREF_FACEDETECTION_ENABLED, oldPref]]}, reallyEnd);
+  } else {
+    SpecialPowers.pushPrefEnv(
+      {'clear': [[PREF_FACEDETECTION_ENABLED]]}, reallyEnd);
+  }
+}
+function next() {
+  CameraTest.next();
+}
+
+function compareFaces(aFaces, expected)
+{
+  ok(aFaces, "have detected faces object");
+  ok(aFaces.length == expected.faces.length,
+    "expected=" + expected.faces.length + ", got=" + aFaces.length);
+  aFaces.forEach(function (face, index) {
+    let result = compareFace(face, expected.faces[index]);
+    ok(result === "ok", "face check: " + result);
+    if (result !== "ok") {
+      return false;
+    }
+  });
+  return true;
+}
+
+function compareFace(aFace, expected)
+{
+  if (aFace.id != expected.id) {
+    return "expected face.id=" + expected.id + ", got=" + aFace.id;
+  }
+  if (aFace.score != expected.score) {
+    return "expected face.score=" + expected.score + ", got=" + aFace.score;
+  }
+  if (!aFace.bounds) {
+    return "face.bounds is missing";
+  }
+  if (aFace.bounds.left != expected.bounds.left ||
+      aFace.bounds.top != expected.bounds.top ||
+      aFace.bounds.right != expected.bounds.right ||
+      aFace.bounds.bottom != expected.bounds.bottom) {
+    return "expected face.bounds=" + expected.bounds.toSource() +
+      ", got=({left:" + aFace.bounds.left + ", top:" + aFace.bounds.top + ", right:" + aFace.bounds.right + ", bottom:" + aFace.bounds.bottom + "})";
+  }
+
+  if (aFace.leftEye && !expected.leftEye) {
+    return "expected null face.leftEye, got=({x:" + aFace.leftEye.x + ", y:" + aFace.leftEye.y + "})";
+  }
+  if (!aFace.leftEye && expected.leftEye) {
+    return "expected face.leftEye=" + expected.leftEye.toSource() + ", got null leftEye";
+  }
+  if (aFace.leftEye && expected.leftEye &&
+      (aFace.leftEye.x != expected.leftEye.x || aFace.leftEye.y != expected.leftEye.y)) {
+    return "expected face.leftEye=" + expected.leftEye.toSource() +
+      ", got=({x:" + aFace.leftEye.x + ", y:" + aFace.leftEye.y + "})";
+  }
+
+  if (aFace.rightEye && !expected.rightEye) {
+    return "expected null face.rightEye, got=({x:" + aFace.rightEye.x + ", y:" + aFace.rightEye.y + "})";
+  }
+  if (!aFace.rightEye && expected.rightEye) {
+    return "expected face.rightEye=" + expected.rightEye.toSource() + ", got null rightEye";
+  }
+  if (aFace.rightEye && expected.rightEye &&
+      (aFace.rightEye.x != expected.rightEye.x || aFace.rightEye.y != expected.rightEye.y)) {
+    return "expected face.rightEye=" + expected.rightEye.toSource() +
+      ", got=({x:" + aFace.rightEye.x + ", y:" + aFace.rightEye.y + "})";
+  }
+
+  if (aFace.mouth && !expected.mouth) {
+    return "expected null face.mouth, got=({x:" + aFace.mouth.x + ", y:" + aFace.mouth.y + "})";
+  }
+  if (!aFace.mouth && expected.mouth) {
+    return "expected face.mouth=" + expected.mouth.toSource() + ", got null mouth";
+  }
+  if (aFace.mouth && expected.mouth &&
+      (aFace.mouth.x != expected.mouth.x || aFace.mouth.y != expected.mouth.y)) {
+    return "expected face.mouth=" + expected.mouth.toSource() +
+      ", got=({x:" + aFace.mouth.x + ", y:" + aFace.mouth.y + "})";
+  }
+
+  return "ok";
+}
+
+var tests = [
+  {
+    key: "face-detection-detected-one-face",
+    func: function testFaceDetectionFoundOneFace(camera) {
+      var expected = {
+        faces: [ {
+          id:       1,
+          score:    2,
+          bounds: {
+            left:   3,
+            top:    4,
+            right:  5,
+            bottom: 6
+          },
+          leftEye: {
+            x:      7,
+            y:      8
+          },
+          rightEye: {
+            x:      9,
+            y:      10
+          },
+          mouth: {
+            x:      11,
+            y:      12
+          }
+        } ]
+      };
+      camera.onFacesDetected = function(aFaces) {
+        ok(compareFaces(aFaces, expected),
+          "onFaceDetected received the detected faces correctly");
+        camera.stopFaceDetection();
+        next();
+      }
+      camera.startFaceDetection();
+    }
+  },
+  {
+    key: "face-detection-detected-two-faces",
+    func: function testFaceDetectionFoundTwoFace(camera) {
+      var expected = {
+        faces: [ {
+          id:       1,
+          score:    2,
+          bounds: {
+            left:   3,
+            top:    4,
+            right:  5,
+            bottom: 6
+          },
+          leftEye: {
+            x:      7,
+            y:      8
+          },
+          rightEye: {
+            x:      9,
+            y:      10
+          },
+          mouth: {
+            x:      11,
+            y:      12
+          }
+        },
+        {
+          id:       13,
+          score:    14,
+          bounds: {
+            left:   15,
+            top:    16,
+            right:  17,
+            bottom: 18
+          },
+          leftEye: {
+            x:      19,
+            y:      20
+          },
+          rightEye: {
+            x:      21,
+            y:      22
+          },
+          mouth: {
+            x:      23,
+            y:      24
+          }
+        } ]
+      };
+      camera.onFacesDetected = function(aFaces) {
+        ok(compareFaces(aFaces, expected),
+          "onFaceDetected received the detected faces correctly");
+        camera.stopFaceDetection();
+        next();
+      }
+      camera.startFaceDetection();
+    }
+  },
+  {
+    key: "face-detection-detected-one-face-no-features",
+    func: function (camera) {
+      var expected = {
+        faces: [ {
+          id:       1,
+          score:    100,
+          bounds: {
+            left:   3,
+            top:    4,
+            right:  5,
+            bottom: 6
+          },
+          leftEye:  null,
+          rightEye: null,
+          mouth:    null
+        } ]
+      };
+      camera.onFacesDetected = function(aFaces) {
+        ok(compareFaces(aFaces, expected),
+          "onFaceDetected received the detected faces correctly");
+        camera.stopFaceDetection();
+        next();
+      }
+      camera.startFaceDetection();
+    }
+  },
+  {
+    key: "face-detection-no-faces-detected",
+    func: function (camera) {
+      var expected = {
+        faces: []
+      };
+      camera.onFacesDetected = function(aFaces) {
+        ok(compareFaces(aFaces, expected),
+          "onFaceDetected received the detected faces correctly");
+        camera.stopFaceDetection();
+        next();
+      }
+      camera.startFaceDetection();
+    }
+  },
+];
+
+var testGenerator = function() {
+  for (var i = 0; i < tests.length; ++i ) {
+    yield tests[i];
+  }
+}();
+
+window.addEventListener('beforeunload', function() {
+  document.getElementById('viewfinder').mozSrcObject = null;
+  if (cameraObj) {
+    cameraObj.release();
+    cameraObj = null;
+  }
+});
+
+// Must call CameraTest.begin() before any other async methods.
+CameraTest.begin("hardware", function(test) {
+  // If the pref doesn't exist, this get will fail; catch it and continue.
+  try {
+    oldPref = SpecialPowers.getBoolPref(PREF_FACEDETECTION_ENABLED);
+  } catch(e) { }
+
+  SpecialPowers.pushPrefEnv({'set': [[PREF_FACEDETECTION_ENABLED, true]]}, function() {
+    var enabled;
+    try {
+      enabled = SpecialPowers.getBoolPref(PREF_FACEDETECTION_ENABLED);
+    } catch(e) { }
+    ok(enabled, PREF_FACEDETECTION_ENABLED + " is " + enabled);
+
+    function onSuccess(camera, config) {
+      document.getElementById('viewfinder').mozSrcObject = camera;
+      cameraObj = camera;
+      CameraTest.next = function() {
+        try {
+          var t = testGenerator.next();
+          test.set(t.key, t.func.bind(undefined, camera));
+        } catch(e) {
+          if (e instanceof StopIteration) {
+            end();
+          } else {
+            throw e;
+          }
+        }
+      };
+      next();
+    }
+    function onError(error) {
+      ok(false, "getCamera() failed with: " + error);
+      end();
+    }
+    navigator.mozCameras.getCamera(whichCamera, initialConfig, onSuccess, onError);
+  })
+});
+
+</script>
+</body>
+
+</html>
new file mode 100644
--- /dev/null
+++ b/dom/camera/test/callback/test_camera_hardware_failures.html
@@ -0,0 +1,145 @@
+<!DOCTYPE HTML>
+<html>
+<!--
+https://bugzilla.mozilla.org/show_bug.cgi?id=940424
+-->
+<head>
+  <title>Bug 940424 - Test camera hardware API failure handling</title>
+  <script type="text/javascript" src="/MochiKit/MochiKit.js"></script>
+  <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
+  <script type="text/javascript" src="../camera_common.js"></script>
+  <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
+</head>
+<body>
+  <a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=940424">Mozilla Bug 940424</a>
+  <video id="viewfinder" width = "200" height = "200" autoplay></video>
+  <img src="#" alt="This image is going to load" id="testimage"/>
+
+<script class="testbody" type="text/javascript;version=1.7">
+
+var whichCamera = navigator.mozCameras.getListOfCameras()[0];
+var initialConfig = {
+  mode: 'picture',
+  recorderProfile: 'cif',
+  previewSize: {
+    width: 352,
+    height: 288
+  }
+};
+
+var cameraObj;
+
+// Shorthand functions
+function end() {
+  CameraTest.end();
+}
+function next() {
+  CameraTest.next();
+}
+
+// The array of tests
+var tests = [
+  {
+    key: "auto-focus-failure",
+    func: function testAutoFocusApiFailure(camera) {
+      function onSuccess(success) {
+        ok(false, "autoFocus() succeeded incorrectly");
+        end();
+      }
+      function onError(error) {
+        ok(true, "autoFocus() failed correctly with: " + error);
+        next();
+      }
+      camera.autoFocus(onSuccess, onError);
+    }
+  },
+  {
+    key: "auto-focus-process-failure",
+    func: function testAutoFocusProcessFailure(camera) {
+      function onSuccess(success) {
+        if (success) {
+          ok(false, "autoFocus() process succeeded incorrectly");
+          end();
+        } else {
+          ok(true, "autoFocus() process failed correctly");
+          next();
+        }
+      }
+      function onError(error) {
+        ok(false, "autoFocus() process failed incorrectly with: " + error);
+        end();
+      }
+      camera.autoFocus(onSuccess, onError);
+    }
+  },
+  {
+    key: "take-picture-failure",
+    func: function testTakePictureApiFailure(camera) {
+      function onSuccess(picture) {
+        ok(false, "takePicture() succeeded incorrectly");
+        end();
+      }
+      function onError(error) {
+        ok(true, "takePicture() failed correctly with: " + error);
+        next();
+      }
+      camera.takePicture(null, onSuccess, onError);
+    }
+  },
+  {
+    key: "take-picture-process-failure",
+    func: function testTakePictureProcessFailure(camera) {
+      function onSuccess(picture) {
+        ok(false, "takePicture() process succeeded incorrectly");
+        end();
+      }
+      function onError(error) {
+        ok(true, "takePicture() process failed correctly with: " + error);
+        next();
+      }
+      camera.takePicture(null, onSuccess, onError);
+    }
+  },
+];
+
+var testGenerator = function() {
+  for (var i = 0; i < tests.length; ++i ) {
+    yield tests[i];
+  }
+}();
+
+window.addEventListener('beforeunload', function() {
+  document.getElementById('viewfinder').mozSrcObject = null;
+  cameraObj.release();
+  cameraObj = null;
+});
+
+CameraTest.begin("hardware", function(test) {
+  function onSuccess(camera, config) {
+    document.getElementById('viewfinder').mozSrcObject = camera;
+    cameraObj = camera;
+    CameraTest.next = function() {
+      try {
+        var t = testGenerator.next();
+        test.set(t.key, t.func.bind(undefined, camera));
+      } catch(e) {
+        if (e instanceof StopIteration) {
+          end();
+        } else {
+          throw e;
+        }
+      }
+    };
+    next();
+  }
+  function onError(error) {
+    ok(false, "getCamera() failed with: " + error);
+    end();
+  }
+  navigator.mozCameras.getCamera(whichCamera, initialConfig, onSuccess, onError);
+});
+
+</script>
+</body>
+
+</html>
new file mode 100644
--- /dev/null
+++ b/dom/camera/test/callback/test_camera_hardware_init_failure.html
@@ -0,0 +1,96 @@
+<!DOCTYPE HTML>
+<html>
+<!--
+https://bugzilla.mozilla.org/show_bug.cgi?id=940424
+-->
+<head>
+  <title>Bug 940424 - Test camera hardware init failure handling</title>
+  <script type="text/javascript" src="/MochiKit/MochiKit.js"></script>
+  <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
+  <script type="text/javascript" src="../camera_common.js"></script>
+  <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
+</head>
+<body>
+  <a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=940424">Mozilla Bug 940424</a>
+  <video id="viewfinder" width="200" height="200" autoplay></video>
+  <img src="#" alt="This image is going to load" id="testimage"/>
+
+<script class="testbody" type="text/javascript;version=1.7">
+
+SimpleTest.waitForExplicitFinish();
+
+var whichCamera = navigator.mozCameras.getListOfCameras()[0];
+var initialConfig = {
+  mode: 'picture',
+  recorderProfile: 'cif',
+  previewSize: {
+    width: 352,
+    height: 288
+  }
+};
+
+var tests = [
+  {
+    name: "init-failure",
+    key: "init-failure",
+    func: function testInitFailure(test) {
+      function onSuccess(camera, config) {
+        ok(false, "onSuccess called incorrectly");
+        camera.release();
+        test.next();
+      }
+      function onError(error) {
+        ok(true, "onError called correctly on init failure");
+        test.next();
+      }
+      info("Running test: init-failure");
+      navigator.mozCameras.getCamera(whichCamera, initialConfig, onSuccess, onError);
+    }
+  },
+  /* This test case (init-success) *must* follow the preceeding test case
+     (init-failure) in order for the desired condition to be verified */
+  {
+    name: "init-success",
+    key: "",
+    func: function(test) {
+      function onSuccess(camera, config) {
+        ok(true, "onSuccess called correctly");
+        camera.release();
+        test.next();
+      }
+      function onError(error) {
+        ok(false, "onError called incorrectly: " + error);
+        test.next();
+      }
+      info("Running test: init-success");
+      navigator.mozCameras.getCamera(whichCamera, initialConfig, onSuccess, onError)
+    }
+  }
+];
+
+var testGenerator = function() {
+  for (var i = 0; i < tests.length; ++i ) {
+    yield tests[i];
+  }
+}();
+
+CameraTest.begin("hardware", function(test) {
+  CameraTest.next = function() {
+    try {
+      var t = testGenerator.next();
+      test.set(t.key, t.func.bind(undefined, CameraTest));
+    } catch(e) {
+      if (e instanceof StopIteration) {
+        CameraTest.end();
+      } else {
+        throw e;
+      }
+    }
+  };
+  CameraTest.next();
+});
+
+</script>
+</body>
+
+</html>
--- a/dom/camera/test/camera_common.js
+++ b/dom/camera/test/camera_common.js
@@ -117,16 +117,17 @@ var CameraTest = (function() {
   function testEnd(callback) {
     // A chain of clean-up functions....
     function allCleanedUp() {
       SimpleTest.finish();
       if (callback) {
         callback();
       }
     }
+
     function cleanUpTestEnabled() {
       var next = allCleanedUp;
       if (oldTestEnabled) {
         SpecialPowers.pushPrefEnv({'set': [[PREF_TEST_ENABLED, oldTestEnabled]]}, next);
       } else {
         SpecialPowers.pushPrefEnv({'clear': [[PREF_TEST_ENABLED]]}, next);
       }
     }
--- a/dom/camera/test/mochitest.ini
+++ b/dom/camera/test/mochitest.ini
@@ -1,11 +1,20 @@
 [DEFAULT]
 support-files = camera_common.js
 
+[callback/test_camera.html]
+[callback/test_camera_2.html]
+[callback/test_camera_3.html]
+[callback/test_camera_hardware_init_failure.html]
+[callback/test_camera_hardware_failures.html]
+[callback/test_bug975472.html]
+[callback/test_camera_hardware_face_detection.html]
+[callback/test_camera_hardware_auto_focus_moving_cb.html]
+[callback/test_bug1022766.html]
 [test_camera.html]
 [test_camera_2.html]
 [test_camera_3.html]
 [test_camera_hardware_init_failure.html]
 [test_camera_hardware_failures.html]
 [test_bug975472.html]
 [test_camera_fake_parameters.html]
 [test_camera_hardware_face_detection.html]
--- a/dom/camera/test/test_bug1022766.html
+++ b/dom/camera/test/test_bug1022766.html
@@ -18,17 +18,17 @@ var config = {
   recorderProfile: 'cif',
   previewSize: {
     width: 352,
     height: 288
   }
 };
 
 function onError(e) {
-  ok(false, "Error" + JSON.stringify(e));
+  ok(false, "Error " + e);
 }
 
 var Camera = {
   cameraObj: null,
   _otherPictureSize: null,
   get viewfinder() {
     return document.getElementById('viewfinder');
   },
@@ -44,17 +44,17 @@ var Camera = {
       CameraTest.end();
     }
   },
 
   successOne: function test_successOne(focused) {
     ok(false, "First call to autoFocus() succeeded unexpectedly");
   },
   failureOne: function test_failureOne(error) {
-    ok(error == "AutoFocusInterrupted", "First call to autoFocus() failed with: "
+    ok(error.name == "NS_ERROR_IN_PROGRESS", "First call to autoFocus() failed with: "
       + error);
     Camera.firstCallFailed = true;
     Camera.checkForDone();
   },
   successTwo: function test_successTwo(focused) {
     ok(true, "Second call to autoFocus() succeeded");
     Camera.secondCallSucceeded = true;
     Camera.checkForDone();
@@ -62,29 +62,30 @@ var Camera = {
   failureTwo: function test_failureTwo(error) {
     ok(false, "Second call to autoFocus() failed unexpectedly with: " + error);
   },
   callback: function test_callback(focused) {
     Camera.callbackTriggered = true;
   },
 
   start: function test_start() {
-    function onSuccess(camera, config) {
+    function onSuccess(d) {
+      var camera = d.camera;
       Camera.cameraObj = camera;
       Camera.viewfinder.mozSrcObject = camera;
       Camera.viewfinder.play();
 
       // It doesn't matter if the emulator supports focus or not;
       // this is just testing the sequencing.
       camera.onAutoFocusCompleted = Camera.callback;
-      camera.autoFocus(Camera.successOne, Camera.failureOne);
-      camera.autoFocus(Camera.successTwo, Camera.failureTwo);
+      camera.autoFocus().then(Camera.successOne, Camera.failureOne);
+      camera.autoFocus().then(Camera.successTwo, Camera.failureTwo);
     };
 
-    navigator.mozCameras.getCamera(whichCamera, config, onSuccess, onError);
+    navigator.mozCameras.getCamera(whichCamera, config).then(onSuccess, onError);
   }
 }
 
 window.addEventListener('beforeunload', function() {
   Camera.viewfinder.mozSrcObject = null;
   if (Camera.cameraObj) {
     Camera.cameraObj.release();
     Camera.cameraObj = null;
--- a/dom/camera/test/test_bug1037322.html
+++ b/dom/camera/test/test_bug1037322.html
@@ -41,33 +41,35 @@ var Camera = {
          cfg.previewSize.height === config.previewSize.height,
          "Configured preview size = " + cfg.previewSize.width + "x" + cfg.previewSize.height);
       ok(cfg.recorderProfile === config.recorderProfile,
          "Configured recorder profile = '" + cfg.recorderProfile + "'");
 
       SimpleTest.finish();
     }
 
-    function getCamera_onSuccess(camera, cfg) {
+    function getCamera_onSuccess(d) {
+      var camera = d.camera;
+      var cfg = d.configuration;
       Camera.cameraObj = camera;
       Camera.viewfinder.mozSrcObject = camera;
       Camera.viewfinder.play();
 
       // Check the default configuration
       ok(cfg.mode === "unspecified", "Initial mode = " + cfg.mode);
       ok(cfg.previewSize.width === 0 && cfg.previewSize.height === 0,
          "Initial preview size = " + cfg.previewSize.width + "x" + cfg.previewSize.height);
       ok(cfg.recorderProfile === "",
          "Initial recorder profile = '" + cfg.recorderProfile + "'");
 
       // Apply our specific configuration
-      camera.setConfiguration(config, setConfig_onSuccess, onError);
+      camera.setConfiguration(config).then(setConfig_onSuccess, onError);
     }
 
-    navigator.mozCameras.getCamera(whichCamera, {}, getCamera_onSuccess, onError);
+    navigator.mozCameras.getCamera(whichCamera, {}).then(getCamera_onSuccess, onError);
   }
 }
 
 SimpleTest.waitForExplicitFinish();
 
 window.addEventListener('beforeunload', function() {
   Camera.viewfinder.mozSrcObject = null;
   if (Camera.cameraObj) {
--- a/dom/camera/test/test_bug975472.html
+++ b/dom/camera/test/test_bug975472.html
@@ -26,17 +26,17 @@ var options = {
   position: {
     latitude: 43.645687,
     longitude: -79.393661
   },
   dateTime: Date.now()
 };
 
 function onError(e) {
-  ok(false, "Error" + JSON.stringify(e));
+  ok(false, "Error " + e);
 }
 function next() {
   Camera.nextTest();
 }
 
 // The array of tests
 var tests = [
   {
@@ -44,17 +44,17 @@ var tests = [
     func: function testAutoFocus(camera) {
       function onSuccess(success) {
         ok(true, "release() succeeded");
         next();
       }
       function onError(error) {
         ok(false, "release() failed with: " + error);
       }
-      camera.release(onSuccess, onError);
+      camera.release().then(onSuccess, onError);
     }
   },
   {
     key: "set-picture-size-after-release",
     func: function testSetPictureSize(camera) {
       camera.setPictureSize({ width: 0, height: 0 });
       next();
     }
@@ -82,73 +82,72 @@ var tests = [
   },
   {
     key: "auto-focus-after-release",
     func: function testAutoFocus(camera) {
       function onSuccess(success) {
         ok(false, "autoFocus() succeeded incorrectly");
       }
       function onError(error) {
-        ok(error === "HardwareClosed", "autoFocus() failed with: " + error);
+        ok(error.name === "NS_ERROR_NOT_INITIALIZED", "autoFocus() failed with: " + error);
         next();
       }
-      camera.autoFocus(onSuccess, onError);
+      camera.autoFocus().then(onSuccess, onError);
     }
   },
   {
     key: "take-picture-after-release",
     func: function testTakePicture(camera) {
       function onSuccess(picture) {
         ok(false, "takePicture() succeeded incorrectly");
       }
       function onError(error) {
-        ok(error === "HardwareClosed", "takePicture() failed with: " + error);
+        ok(error.name === "NS_ERROR_NOT_INITIALIZED", "takePicture() failed with: " + error);
         next();
       }
-      camera.takePicture(null, onSuccess, onError);
+      camera.takePicture(null).then(onSuccess, onError);
     }
   },
   {
     key: "start-recording-after-release",
     func: function testStartRecording(camera) {
       function onSuccess(picture) {
         ok(false, "startRecording() process succeeded incorrectly");
       }
       function onError(error) {
-        ok(error === "GeneralFailure", "startRecording() failed with: " + error);
+        ok(error.name === "NS_ERROR_FAILURE", "startRecording() failed with: " + error);
         next();
       }
       var recordingOptions = {
         profile: 'cif',
         rotation: 0
       };
       camera.startRecording(recordingOptions,
                             navigator.getDeviceStorage('videos'),
-                            'bug975472.mp4',
-                            onSuccess, onError);
+                            'bug975472.mp4').then(onSuccess, onError);
     }
   },
   {
     key: "stop-recording-after-release",
     func: function testStopRecording(camera) {
       camera.stopRecording();
       next();
     }
   },
   {
     key: "set-configuration-after-release",
     func: function testSetConfiguration(camera) {
       function onSuccess(picture) {
         ok(false, "setConfiguration() process succeeded incorrectly");
       }
       function onError(error) {
-        ok(error === "HardwareClosed", "setConfiguration() failed with: " + error);
+        ok(error.name === "NS_ERROR_NOT_INITIALIZED", "setConfiguration() failed with: " + error);
         next();
       }
-      camera.setConfiguration(config, onSuccess, onError);
+      camera.setConfiguration(config).then(onSuccess, onError);
     }
   },
 ];
 
 var testGenerator = function() {
   for (var i = 0; i < tests.length; ++i ) {
     yield tests[i];
   }
@@ -178,37 +177,39 @@ var Camera = {
     // to make sure they properly handle being in this state.
     Camera.cameraObj.release();
     next();
   },
   release: function release() {
     cameraObj = null;
   },
   start: function run_test() {
-    function onSuccess(camera, config) {
+    function onSuccess(d) {
+      var camera = d.camera;
       Camera.cameraObj = camera;
+      var onPreviewStateChange = function(e) {
+        if (e.newState === 'started') {
+          info("viewfinder is ready and playing");
+          Camera.cameraObj.removeEventListener('previewstatechange', onPreviewStateChange);
+          Camera.onCameraReady();
+        }
+      };
+      camera.addEventListener('previewstatechange', onPreviewStateChange);
       Camera.viewfinder.mozSrcObject = camera;
       Camera.viewfinder.play();
       ok(camera.capabilities.pictureSizes.length > 0,
         "capabilities.pictureSizes.length = " +
         camera.capabilities.pictureSizes.length);
       Camera._otherPictureSize = camera.capabilities.pictureSizes.slice(-1)[0];
       camera.setPictureSize(camera.capabilities.pictureSizes[0]);
       options.pictureSize = Camera._otherPictureSize;
       options.fileFormat = camera.capabilities.fileFormats[0];
       info("getCamera callback, setting pictureSize = " + options.pictureSize.toSource());
-      Camera.cameraObj.onPreviewStateChange = function(state) {
-        if (state === 'started') {
-          info("viewfinder is ready and playing");
-          Camera.cameraObj.onPreviewStateChange = null;
-          Camera.onCameraReady();
-        }
-      };
     };
-    navigator.mozCameras.getCamera(whichCamera, config, onSuccess, onError);
+    navigator.mozCameras.getCamera(whichCamera, config).then(onSuccess, onError);
   }
 }
 
 SimpleTest.waitForExplicitFinish();
 
 window.addEventListener('beforeunload', function() {
   Camera.viewfinder.mozSrcObject = null;
   Camera.cameraObj.release();
--- a/dom/camera/test/test_camera.html
+++ b/dom/camera/test/test_camera.html
@@ -24,17 +24,17 @@ var options = {
 var config = {
   dateTime: Date.now() / 1000,
   pictureSize: null,
   fileFormat: 'jpeg',
   rotation: 90
 };
 
 function onError(e) {
-  ok(false, "Error" + JSON.stringify(e));
+  ok(false, "Error " + e);
 }
 
 var capabilities = [ 'previewSizes', 'pictureSizes', 'fileFormats', 'maxFocusAreas', 'minExposureCompensation',
                      'maxExposureCompensation', 'stepExposureCompensation', 'maxMeteringAreas', 'videoSizes',
                      'recorderProfiles', 'zoomRatios', 'isoModes'];
 
 var Camera = {
   cameraObj: null,
@@ -97,22 +97,27 @@ var Camera = {
   },
   getPreviewSizes: function camera_preview() {
     this._previewSizes = this.cameraObj.capabilities.previewSizes;
   },
   getZoomRatios: function camera_preview() {
     this._zoomRatios = this.cameraObj.capabilities.zoomRatios;
   },
   takePictureSuccess: function taken_foto(blob) {
+    ok(blob.size > 100 , "Blob Size Gathered = " + blob.size);
+    ok("image/" + test.fileFormat ==  blob.type, "Blob Type = " + blob.type);
+  },
+  takePictureEvent: function taken_foto_evt(e) {
+    var blob = e.data;
     var img = new Image();
     var test = this._currentTest;
     img.onload = function Imgsize() {
-      ok(this.width == test.pictureSize.width, "The image taken has the width " + 
+      ok(this.width == test.pictureSize.width, "The image taken has the width " +
                                               this.width + " pictureSize width = " + test.pictureSize.width);
-      ok(this.height == test.pictureSize.height, "The image taken has the height " + 
+      ok(this.height == test.pictureSize.height, "The image taken has the height " +
                                               this.height + " picturesize height = " + test.pictureSize.height);
       Camera._testsCompleted++;
       if(Camera._testsCompleted == Camera._tests.length) {
         ok(true, "test finishing");
         SimpleTest.finish();
       } else {
         Camera.runTests();
       }
@@ -191,43 +196,46 @@ var Camera = {
   },
   runTests: function run_tests() {
     var test = this._tests[this._testsCompleted];
     this._currentTest = test;
     Camera.setFlashMode(test.flashMode);
     config.fileFormat = test.fileFormat;
     config.pictureSize = test.pictureSize;
     ok(true, "testing picture size " + JSON.stringify(config.pictureSize));
-    Camera.cameraObj.takePicture(config, this.takePictureSuccess.bind(this), onError);
+    Camera.cameraObj.takePicture(config).then(this.takePictureSuccess.bind(this), onError);
   },
   onConfigChange: function onConfigChange(config) {
     ok(config.mode === options.mode, "configuration mode = " + config.mode);
     ok(config.recorderProfile === options.recorderProfile, "recorder profile = " + config.recorderProfile);
     ok(config.previewSize.width === options.previewSize.width &&
       config.previewSize.height === options.previewSize.height,
       "preview size (w x h) = " + config.previewSize.width + " x " + config.previewSize.height);
   },
+  onPreviewStateChange: function onPreviewStateChange(e) {
+    if (e.newState === 'started') {
+      ok(true, "viewfinder is ready and playing");
+      Camera.cameraObj.removeEventListener('previewstatechange', Camera.onPreviewStateChange);
+      Camera.onReady();
+    }
+  },
   setUp: function setup_tests() {
-    function onSuccess(camera) {
-      Camera.cameraObj = camera;
-      Camera.viewfinder.mozSrcObject = camera;
+    function onSuccess(d) {
+      Camera.cameraObj = d.camera;
+      Camera.cameraObj.addEventListener('previewstatechange', Camera.onPreviewStateChange);
+      Camera.cameraObj.addEventListener('configurationchanged', Camera.onConfigChange);
+      Camera.cameraObj.addEventListener('shutter', Camera.shutter);
+      Camera.cameraObj.addEventListener('picture', Camera.takePictureEvent.bind(Camera));
+      Camera.viewfinder.mozSrcObject = d.camera;
       Camera.viewfinder.play();
-      Camera.cameraObj.onPreviewStateChange = function(state) {
-        if (state === 'started') {
-          ok(true, "viewfinder is ready and playing");
-          Camera.cameraObj.onPreviewStateChange = null;
-          Camera.onReady();
-        }
-      };
       SimpleTest.expectAssertions(0);
       ok(true, "Camera Control object has been successfully initialized");
-      Camera.cameraObj.setConfiguration(options, Camera.onConfigChange, onError);
-      Camera.cameraObj.onShutter = Camera.shutter;
+      Camera.cameraObj.setConfiguration(options).then(Camera.onConfigChange, onError);
     };
-    navigator.mozCameras.getCamera(whichCamera, null, onSuccess, onError);
+    navigator.mozCameras.getCamera(whichCamera, null).then(onSuccess, onError);
   }
 }
 
 SimpleTest.waitForExplicitFinish();
 
 window.addEventListener('beforeunload', function() {
   Camera.viewfinder.mozSrcObject = null;
   Camera.cameraObj.release();
--- a/dom/camera/test/test_camera_2.html
+++ b/dom/camera/test/test_camera_2.html
@@ -24,17 +24,17 @@ var options = {
 var config = {
   dateTime: Date.now() / 1000,
   pictureSize: null,
   fileFormat: 'jpeg',
   rotation: 90
 };
 
 function onError(e) {
-  ok(false, "Error" + JSON.stringify(e));
+  ok(false, "Error " + e);
 }
 
 var capabilities = [ 'previewSizes', 'pictureSizes', 'fileFormats', 'maxFocusAreas', 'minExposureCompensation',
                      'maxExposureCompensation', 'stepExposureCompensation', 'maxMeteringAreas', 'videoSizes',
                      'recorderProfiles'];
 
 var Camera = {
   cameraObj: null,
@@ -108,29 +108,37 @@ var Camera = {
       }
     }
     ok(blob.size > 100 , "Blob Size Gathered = " + blob.size);
     ok("image/" + test.fileFormat ==  blob.type, "Blob Type = " + blob.type);
     img.src = window.URL.createObjectURL(blob);
   },
   shutter: function onShutter () {
     Camera._shutter++;
-    
+
     ok(Camera._shutter == (Camera._testsCompleted + 1), "on Shutter has been called " +
                            Camera._shutter + " times");
 
   },
+  onPreviewStateChange: function onPreviewStateChange(e) {
+      ok(true, "viewfinder state change " + e);
+    if (e.newState === 'started') {
+      ok(true, "viewfinder is ready and playing");
+      Camera.cameraObj.removeEventListener('previewstatechange', Camera.onPreviewStateChange);
+      Camera.onReady();
+    }
+  },
   onReady: function onReady() {
     var camcap = Camera.cameraObj.capabilities;
     var tests = {};
     for (var prop in capabilities) {
       prop = capabilities[prop];
       ok(camcap[prop] || isFinite(camcap[prop]) || camcap[prop] == null, "Camera Capability: " +
                     prop + " is exposed, value = " + JSON.stringify(camcap[prop]));
-    } 
+    }
     for (var prop in camcap) {
       if(camcap[prop] && camcap[prop].length > 1)  {
         tests[prop] = camcap[prop];
       }
     }
     Camera.getPictureSizes();
     Camera.getPreviewSizes();
     Camera.getFileFormats();
@@ -152,40 +160,35 @@ var Camera = {
   },
   runTests: function run_tests() {
     var test = this._tests[this._testsCompleted];
     this._currentTest = test;
     Camera.setFlashMode(test.flashMode);
     config.fileFormat = test.fileFormat;
     config.pictureSize = test.pictureSize;
     ok(true, "testing picture size " + JSON.stringify(config.pictureSize));
-    Camera.cameraObj.takePicture(config, this.takePictureSuccess.bind(this), onError);
+    Camera.cameraObj.takePicture(config).then(this.takePictureSuccess.bind(this), onError);
   },
   setUp: function setup_tests() {
-    function onSuccess(camera, config) {
+    function onSuccess(d) {
+      var config = d.configuration;
       ok(true, "Camera Control object has been successfully initialized");
       ok(config.mode === options.mode, "configuration mode = " + config.mode);
       ok(config.recorderProfile === options.recorderProfile, "recorder profile = " + config.recorderProfile);
       ok(config.previewSize.width === options.previewSize.width &&
         config.previewSize.height === options.previewSize.height,
         "preview size (w x h) = " + config.previewSize.width + " x " + config.previewSize.height);
-      Camera.cameraObj = camera;
-      Camera.viewfinder.mozSrcObject = camera;
+      Camera.cameraObj = d.camera;
+      Camera.cameraObj.addEventListener('previewstatechange', Camera.onPreviewStateChange);
+      Camera.cameraObj.addEventListener('shutter', Camera.shutter);
+      Camera.viewfinder.mozSrcObject = d.camera;
       Camera.viewfinder.play();
-      Camera.cameraObj.onPreviewStateChange = function(state) {
-        if (state === 'started') {
-          ok(true, "viewfinder is ready and playing");
-          Camera.cameraObj.onPreviewStateChange = null;
-          Camera.onReady();
-        }
-      };
       SimpleTest.expectAssertions(0);
-      Camera.cameraObj.onShutter = Camera.shutter;
     };
-    navigator.mozCameras.getCamera(whichCamera, options, onSuccess, onError);
+    navigator.mozCameras.getCamera(whichCamera, options).then(onSuccess, onError);
   }
 }
 
 SimpleTest.waitForExplicitFinish();
 
 window.addEventListener('beforeunload', function() {
   Camera.viewfinder.mozSrcObject = null;
   Camera.cameraObj.release();
--- a/dom/camera/test/test_camera_3.html
+++ b/dom/camera/test/test_camera_3.html
@@ -17,51 +17,52 @@ var options = {
   recorderProfile: 'cif',
   previewSize: {
     width: 352,
     height: 288
   }
 };
 
 function onError(e) {
-  ok(false, "Error" + JSON.stringify(e));
+  ok(false, "Error " + e);
 }
 
 var Camera = {
   cameraObj: null,
   get viewfinder() {
     return document.getElementById('viewfinder');
   },
   onReady: function take_two() {
-    function onSuccess(camera, config) {
-      ok(false, "Unexpectedly got second camera instance: " + config.toSource);
+    function onSuccess(d) {
+      ok(false, "Unexpectedly got second camera instance: " + d.config.toSource);
     }
     function onFailure(error) {
       ok(true, "Correctly failed to get camera again");
       SimpleTest.finish();
     }
-    navigator.mozCameras.getCamera(whichCamera, options, onSuccess, onFailure);
+    navigator.mozCameras.getCamera(whichCamera, options).then(onSuccess, onFailure);
+  },
+  onPreviewStateChange: function onPreviewStateChange(e) {
+    if (e.newState === 'started') {
+      ok(true, "viewfinder is ready and playing");
+      Camera.cameraObj.removeEventListener('previewstatechange', Camera.onPreviewStateChange);
+      Camera.onReady();
+    }
   },
   release: function release() {
     cameraObj = null;
   },
   start: function run_test() {
-    function onSuccess(camera, config) {
-      Camera.cameraObj = camera;
-      Camera.viewfinder.mozSrcObject = camera;
+    function onSuccess(d) {
+      Camera.cameraObj = d.camera;
+      Camera.cameraObj.addEventListener('previewstatechange', Camera.onPreviewStateChange);
+      Camera.viewfinder.mozSrcObject = d.camera;
       Camera.viewfinder.play();
-      Camera.cameraObj.onPreviewStateChange = function(state) {
-        if (state === 'started') {
-          ok(true, "viewfinder is ready and playing");
-          Camera.cameraObj.onPreviewStateChange = null;
-          Camera.onReady();
-        }
-      };
     };
-    navigator.mozCameras.getCamera(whichCamera, options, onSuccess, onError);
+    navigator.mozCameras.getCamera(whichCamera, options).then(onSuccess, onError);
   }
 }
 
 SimpleTest.waitForExplicitFinish();
 
 window.addEventListener('beforeunload', function() {
   Camera.viewfinder.mozSrcObject = null;
   Camera.cameraObj.release();
--- a/dom/camera/test/test_camera_fake_parameters.html
+++ b/dom/camera/test/test_camera_fake_parameters.html
@@ -23,17 +23,17 @@ var initialConfig = {
     height: 288
   }
 };
 
 var cameraObj = null;
 
 // Shorthand functions
 function onError(e) {
-  ok(false, "Error" + JSON.stringify(e));
+  ok(false, "Error " + e);
 }
 
 function end() {
   CameraTest.end();
 }
 function next() {
   if (cameraObj) {
     cameraObj.release(
@@ -422,30 +422,29 @@ CameraTest.begin("hardware", function(te
     ok(false, "getCamera() failed with: " + error);
     end();
   }
 
   CameraTest.next = function() {
     try {
       var t = testGenerator.next();
       info("test: " + t.key);
-      function onSuccess(camera, config) {
-        cameraObj = camera;
-        document.getElementById('viewfinder').mozSrcObject = camera;
-        camera.onPreviewStateChange = function (state) {
-          if (state === "started") {
-            t.test(camera, camera.capabilities);
-          } else {
-            ok(false, "preview started (state = '" + state + "')");
+      function onSuccess(d) {
+        cameraObj = d.camera;
+        document.getElementById('viewfinder').mozSrcObject = d.camera;
+        var onPreviewStateChange = function (evt) {
+          if (evt.newState === "started") {
+            cameraObj.removeEventListener('previewstatechange', onPreviewStateChange);
+            t.test(cameraObj, cameraObj.capabilities);
           }
-          camera.onPreviewStateChange = null;
         };
+        cameraObj.addEventListener('previewstatechange', onPreviewStateChange);
       }
       CameraTest.run = function() {
-        navigator.mozCameras.getCamera(whichCamera, initialConfig, onSuccess, onError);
+        navigator.mozCameras.getCamera(whichCamera, initialConfig).then(onSuccess, onError);
       };
       t.prep(test);
     } catch(e) {
       if (e instanceof StopIteration) {
         end();
       } else {
         throw e;
       }
--- a/dom/camera/test/test_camera_hardware_auto_focus_moving_cb.html
+++ b/dom/camera/test/test_camera_hardware_auto_focus_moving_cb.html
@@ -48,35 +48,26 @@ function end() {
 function next() {
   CameraTest.next();
 }
 
 var tests = [
   {
     key: "autofocus-moving-true",
     func: function testAutoFocusMovingIsTrue(camera) {
-      camera.onAutoFocusMoving = function(aIsMoving) {
-        ok(aIsMoving == true,"onAutoFocusMoving callback received true correctly");
+      var handler = function(evt) {
+        camera.removeEventListener("focus", handler);
+        ok(evt.newState == "focusing", "autofocus event state focusing == " + evt.newState);
         camera.focusMode = 'auto';
         next();
       }
+      camera.addEventListener("focus", handler);
       camera.focusMode = 'continuous-picture';
     }
   },
-  {
-    key: "autofocus-moving-false",
-    func: function testAutoFocusMovingIsFalse(camera) {
-      camera.onAutoFocusMoving = function(aIsMoving) {
-        ok(aIsMoving == false, "onAutoFocusMoving callback received false correctly");
-        camera.focusMode = 'auto';
-        end();
-      }
-      camera.focusMode = 'continuous-video';
-    }
-  },
 ];
 
 var testGenerator = function() {
   for (var i = 0; i < tests.length; ++i ) {
     yield tests[i];
   }
 }();
 
@@ -95,37 +86,37 @@ CameraTest.begin("hardware", function(te
 
   SpecialPowers.pushPrefEnv({'set': [[PREF_AUTOFOCUSCALLBACK_ENABLED, true]]}, function() {
     var enabled;
     try {
       enabled = SpecialPowers.getBoolPref(PREF_AUTOFOCUSCALLBACK_ENABLED);
     } catch(e) { }
     ok(enabled, PREF_AUTOFOCUSCALLBACK_ENABLED + " is " + enabled);
 
-    function onSuccess(camera, config) {
-      document.getElementById('viewfinder').mozSrcObject = camera;
-      cameraObj = camera;
+    function onSuccess(d) {
+      document.getElementById('viewfinder').mozSrcObject = d.camera;
+      cameraObj = d.camera;
       CameraTest.next = function() {
         try {
           var t = testGenerator.next();
-          test.set(t.key, t.func.bind(undefined, camera));
+          test.set(t.key, t.func.bind(undefined, d.camera));
         } catch(e) {
           if (e instanceof StopIteration) {
             end();
           } else {
             throw e;
           }
         }
       };
       next();
     }
     function onError(error) {
       ok(false, "getCamera() failed with: " + error);
       end();
     }
-    navigator.mozCameras.getCamera(whichCamera, initialConfig, onSuccess, onError);
+    navigator.mozCameras.getCamera(whichCamera, initialConfig).then(onSuccess, onError);
   })
 });
 
 </script>
 </body>
 
 </html>
--- a/dom/camera/test/test_camera_hardware_face_detection.html
+++ b/dom/camera/test/test_camera_hardware_face_detection.html
@@ -145,22 +145,26 @@ var tests = [
             y:      10
           },
           mouth: {
             x:      11,
             y:      12
           }
         } ]
       };
-      camera.onFacesDetected = function(aFaces) {
-        ok(compareFaces(aFaces, expected),
-          "onFaceDetected received the detected faces correctly");
+
+      var handler = function(evt) {
+        ok(compareFaces(evt.faces, expected),
+          "facedetected event received the detected faces correctly");
         camera.stopFaceDetection();
+        camera.removeEventListener('facesdetected', handler);
         next();
-      }
+      };
+
+      camera.addEventListener('facesdetected', handler);
       camera.startFaceDetection();
     }
   },
   {
     key: "face-detection-detected-two-faces",
     func: function testFaceDetectionFoundTwoFace(camera) {
       var expected = {
         faces: [ {
@@ -203,22 +207,26 @@ var tests = [
             y:      22
           },
           mouth: {
             x:      23,
             y:      24
           }
         } ]
       };
-      camera.onFacesDetected = function(aFaces) {
-        ok(compareFaces(aFaces, expected),
-          "onFaceDetected received the detected faces correctly");
+
+      var handler = function(evt) {
+        ok(compareFaces(evt.faces, expected),
+          "facedetected event received the detected faces correctly");
         camera.stopFaceDetection();
+        camera.removeEventListener('facesdetected', handler);
         next();
-      }
+      };
+
+      camera.addEventListener('facesdetected', handler);
       camera.startFaceDetection();
     }
   },
   {
     key: "face-detection-detected-one-face-no-features",
     func: function (camera) {
       var expected = {
         faces: [ {
@@ -230,37 +238,45 @@ var tests = [
             right:  5,
             bottom: 6
           },
           leftEye:  null,
           rightEye: null,
           mouth:    null
         } ]
       };
-      camera.onFacesDetected = function(aFaces) {
-        ok(compareFaces(aFaces, expected),
-          "onFaceDetected received the detected faces correctly");
+
+      var handler = function(evt) {
+        ok(compareFaces(evt.faces, expected),
+          "facedetected event received the detected faces correctly");
         camera.stopFaceDetection();
+        camera.removeEventListener('facesdetected', handler);
         next();
-      }
+      };
+
+      camera.addEventListener('facesdetected', handler);
       camera.startFaceDetection();
     }
   },
   {
     key: "face-detection-no-faces-detected",
     func: function (camera) {
       var expected = {
         faces: []
       };
-      camera.onFacesDetected = function(aFaces) {
-        ok(compareFaces(aFaces, expected),
-          "onFaceDetected received the detected faces correctly");
+
+      var handler = function(evt) {
+        ok(compareFaces(evt.faces, expected),
+          "facedetected event received the detected faces correctly");
         camera.stopFaceDetection();
+        camera.removeEventListener('facesdetected', handler);
         next();
-      }
+      };
+
+      camera.addEventListener('facesdetected', handler);
       camera.startFaceDetection();
     }
   },
 ];
 
 var testGenerator = function() {
   for (var i = 0; i < tests.length; ++i ) {
     yield tests[i];
@@ -284,37 +300,37 @@ CameraTest.begin("hardware", function(te
 
   SpecialPowers.pushPrefEnv({'set': [[PREF_FACEDETECTION_ENABLED, true]]}, function() {
     var enabled;
     try {
       enabled = SpecialPowers.getBoolPref(PREF_FACEDETECTION_ENABLED);
     } catch(e) { }
     ok(enabled, PREF_FACEDETECTION_ENABLED + " is " + enabled);
 
-    function onSuccess(camera, config) {
-      document.getElementById('viewfinder').mozSrcObject = camera;
-      cameraObj = camera;
+    function onSuccess(d) {
+      cameraObj = d.camera;
+      document.getElementById('viewfinder').mozSrcObject = cameraObj;
       CameraTest.next = function() {
         try {
           var t = testGenerator.next();
-          test.set(t.key, t.func.bind(undefined, camera));
+          test.set(t.key, t.func.bind(undefined, cameraObj));
         } catch(e) {
           if (e instanceof StopIteration) {
             end();
           } else {
             throw e;
           }
         }
       };
       next();
     }
     function onError(error) {
       ok(false, "getCamera() failed with: " + error);
       end();
     }
-    navigator.mozCameras.getCamera(whichCamera, initialConfig, onSuccess, onError);
+    navigator.mozCameras.getCamera(whichCamera, initialConfig).then(onSuccess, onError);
   })
 });
 
 </script>
 </body>
 
 </html>
--- a/dom/camera/test/test_camera_hardware_failures.html
+++ b/dom/camera/test/test_camera_hardware_failures.html
@@ -45,17 +45,17 @@ var tests = [
       function onSuccess(success) {
         ok(false, "autoFocus() succeeded incorrectly");
         end();
       }
       function onError(error) {
         ok(true, "autoFocus() failed correctly with: " + error);
         next();
       }
-      camera.autoFocus(onSuccess, onError);
+      camera.autoFocus().then(onSuccess, onError);
     }
   },
   {
     key: "auto-focus-process-failure",
     func: function testAutoFocusProcessFailure(camera) {
       function onSuccess(success) {
         if (success) {
           ok(false, "autoFocus() process succeeded incorrectly");
@@ -64,45 +64,45 @@ var tests = [
           ok(true, "autoFocus() process failed correctly");
           next();
         }
       }
       function onError(error) {
         ok(false, "autoFocus() process failed incorrectly with: " + error);
         end();
       }
-      camera.autoFocus(onSuccess, onError);
+      camera.autoFocus().then(onSuccess, onError);
     }
   },
   {
     key: "take-picture-failure",
     func: function testTakePictureApiFailure(camera) {
       function onSuccess(picture) {
         ok(false, "takePicture() succeeded incorrectly");
         end();
       }
       function onError(error) {
         ok(true, "takePicture() failed correctly with: " + error);
         next();
       }
-      camera.takePicture(null, onSuccess, onError);
+      camera.takePicture(null).then(onSuccess, onError);
     }
   },
   {
     key: "take-picture-process-failure",
     func: function testTakePictureProcessFailure(camera) {
       function onSuccess(picture) {
         ok(false, "takePicture() process succeeded incorrectly");
         end();
       }
       function onError(error) {
         ok(true, "takePicture() process failed correctly with: " + error);
         next();
       }
-      camera.takePicture(null, onSuccess, onError);
+      camera.takePicture(null).then(onSuccess, onError);
     }
   },
 ];
 
 var testGenerator = function() {
   for (var i = 0; i < tests.length; ++i ) {
     yield tests[i];
   }
@@ -110,36 +110,36 @@ var testGenerator = function() {
 
 window.addEventListener('beforeunload', function() {
   document.getElementById('viewfinder').mozSrcObject = null;
   cameraObj.release();
   cameraObj = null;
 });
 
 CameraTest.begin("hardware", function(test) {
-  function onSuccess(camera, config) {
-    document.getElementById('viewfinder').mozSrcObject = camera;
-    cameraObj = camera;
+  function onSuccess(d) {
+    cameraObj = d.camera;
+    document.getElementById('viewfinder').mozSrcObject = cameraObj;
     CameraTest.next = function() {
       try {
         var t = testGenerator.next();
-        test.set(t.key, t.func.bind(undefined, camera));
+        test.set(t.key, t.func.bind(undefined, cameraObj));
       } catch(e) {
         if (e instanceof StopIteration) {
           end();
         } else {
           throw e;
         }
       }
     };
     next();
   }
   function onError(error) {
     ok(false, "getCamera() failed with: " + error);
     end();
   }
-  navigator.mozCameras.getCamera(whichCamera, initialConfig, onSuccess, onError);
+  navigator.mozCameras.getCamera(whichCamera, initialConfig).then(onSuccess, onError);
 });
 
 </script>
 </body>
 
 </html>
--- a/dom/camera/test/test_camera_hardware_init_failure.html
+++ b/dom/camera/test/test_camera_hardware_init_failure.html
@@ -29,46 +29,46 @@ var initialConfig = {
   }
 };
 
 var tests = [
   {
     name: "init-failure",
     key: "init-failure",
     func: function testInitFailure(test) {
-      function onSuccess(camera, config) {
+      function onSuccess(d) {
         ok(false, "onSuccess called incorrectly");
-        camera.release();
+        d.camera.release();
         test.next();
       }
       function onError(error) {
         ok(true, "onError called correctly on init failure");
         test.next();
       }
       info("Running test: init-failure");
-      navigator.mozCameras.getCamera(whichCamera, initialConfig, onSuccess, onError);
+      navigator.mozCameras.getCamera(whichCamera, initialConfig).then(onSuccess, onError);
     }
   },
   /* This test case (init-success) *must* follow the preceeding test case
      (init-failure) in order for the desired condition to be verified */
   {
     name: "init-success",
     key: "",
     func: function(test) {
-      function onSuccess(camera, config) {
+      function onSuccess(d) {
         ok(true, "onSuccess called correctly");
-        camera.release();
+        d.camera.release();
         test.next();
       }
       function onError(error) {
         ok(false, "onError called incorrectly: " + error);
         test.next();
       }
       info("Running test: init-success");
-      navigator.mozCameras.getCamera(whichCamera, initialConfig, onSuccess, onError)
+      navigator.mozCameras.getCamera(whichCamera, initialConfig).then(onSuccess, onError)
     }
   }
 ];
 
 var testGenerator = function() {
   for (var i = 0; i < tests.length; ++i ) {
     yield tests[i];
   }
--- a/dom/events/test/test_all_synthetic_events.html
+++ b/dom/events/test/test_all_synthetic_events.html
@@ -71,16 +71,28 @@ const kEventConstructors = {
   CallEvent:                                 { create: function (aName, aProps) {
                                                           return new CallEvent(aName, aProps);
                                                        },
                                              },
   CallGroupErrorEvent:                       { create: function (aName, aProps) {
                                                           return new CallGroupErrorEvent(aName, aProps);
                                                        },
                                              },
+  CameraConfigurationEvent:                  { create: function (aName, aProps) {
+                                                          return new CameraConfigurationEvent(aName, aProps);
+                                                       },
+                                             },
+  CameraFacesDetectedEvent:                  { create: function (aName, aProps) {
+                                                          return new CameraFacesDetectedEvent(aName, aProps);
+                                                       },
+                                             },
+  CameraStateChangeEvent:                    { create: function (aName, aProps) {
+                                                          return new CameraStateChangeEvent(aName, aProps);
+                                                       },
+                                             },
   CFStateChangeEvent:                        { create: function (aName, aProps) {
                                                           return new CFStateChangeEvent(aName, aProps);
                                                        },
                                              },
   CloseEvent:                                { create: function (aName, aProps) {
                                                          return new CloseEvent(aName, aProps);
                                                        },
                                              },
--- a/dom/interfaces/html/nsIDOMHTMLMediaElement.idl
+++ b/dom/interfaces/html/nsIDOMHTMLMediaElement.idl
@@ -3,18 +3,16 @@
 /* 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 "nsIDOMHTMLElement.idl"
 #include "nsIDOMMediaError.idl"
 #include "nsIDOMTimeRanges.idl"
 
-interface nsIDOMMediaStream;
-
 /**
  * The nsIDOMHTMLMediaElement interface is an interface to be implemented by the HTML
  * <audio> and <video> elements.
  *
  * For more information on this interface, please see
  * http://www.whatwg.org/specs/web-apps/current-work/#htmlmediaelement
  *
  * @status UNDER_DEVELOPMENT
@@ -30,17 +28,16 @@ interface nsIDOMMediaStream;
 [uuid(c041d76c-15ce-47ad-b61d-e8755a6db638)]
 interface nsIDOMHTMLMediaElement : nsISupports
 {
   // error state
   readonly attribute nsIDOMMediaError error;
 
   // network state
            attribute DOMString src;
-           attribute nsIDOMMediaStream mozSrcObject;
   readonly attribute DOMString currentSrc;
   const unsigned short NETWORK_EMPTY = 0;
   const unsigned short NETWORK_IDLE = 1;
   const unsigned short NETWORK_LOADING = 2;
   const unsigned short NETWORK_NO_SOURCE = 3;
   readonly attribute unsigned short networkState;
            attribute DOMString preload;
   readonly attribute nsIDOMTimeRanges buffered;
@@ -74,18 +71,16 @@ interface nsIDOMHTMLMediaElement : nsISu
 
   // controls
            attribute boolean controls;
            attribute double volume;
            attribute boolean muted;
            attribute boolean defaultMuted;
 
   // Mozilla extension: stream capture
-  nsIDOMMediaStream mozCaptureStream();
-  nsIDOMMediaStream mozCaptureStreamUntilEnded();
   readonly attribute boolean mozAudioCaptured;
 
   // Mozilla extension: return embedded metadata from the stream as a
   // JSObject with key:value pairs for each tag. This can be used by
   // player interfaces to display the song title, artist, etc.
   [implicit_jscontext]
   jsval mozGetMetadata();
 
--- a/dom/media/bridge/IPeerConnection.idl
+++ b/dom/media/bridge/IPeerConnection.idl
@@ -1,13 +1,12 @@
 #include "nsIThread.idl"
 #include "nsIDOMWindow.idl"
 #include "nsIPropertyBag2.idl"
 
-interface nsIDOMMediaStream;
 interface nsIDOMDataChannel;
 
 /*
  * Manager interface to PeerConnection.js so it is accessible from C++.
  */
 [scriptable, uuid(c2218bd2-2648-4701-8fa6-305d3379e9f8)]
 interface IPeerConnectionManager : nsISupports
 {
--- a/dom/media/moz.build
+++ b/dom/media/moz.build
@@ -12,17 +12,16 @@ if CONFIG['MOZ_WEBRTC']:
         '/media/webrtc/signaling/src/common',
         '/media/webrtc/trunk',
     ]
 
     MOCHITEST_MANIFESTS += ['tests/mochitest/mochitest.ini']
     WEBRTC_SIGNALLING_TEST_MANIFESTS += ['tests/mochitest/steeplechase.ini']
 
 XPIDL_SOURCES += [
-    'nsIDOMMediaStream.idl',
     'nsIDOMNavigatorUserMedia.idl',
     'nsIMediaManager.idl',
 ]
 
 XPIDL_MODULE = 'dom_media'
 
 EXPORTS.mozilla.dom += [
     'GetUserMediaRequest.h',
deleted file mode 100644
--- a/dom/media/nsIDOMMediaStream.idl
+++ /dev/null
@@ -1,27 +0,0 @@
-/* -*- Mode: IDL; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this file,
- * You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-#include "nsISupports.idl"
-
-// undef the GetCurrentTime macro defined in WinBase.h from the MS Platform SDK
-%{C++
-#ifdef GetCurrentTime
-#undef GetCurrentTime
-#endif
-%}
-
-[builtinclass, uuid(3ef760bb-ff19-4dbb-b552-af27ab84b9b8)]
-interface nsIDOMMediaStream : nsISupports
-{
-  /* Placeholder interface only; will be removed after further WebIDL conversion.
-     Do not add anything here. */
-};
-
-[builtinclass, uuid(dd37150a-9823-4605-ac4c-3516629a8aaf)]
-interface nsIDOMLocalMediaStream : nsIDOMMediaStream
-{
-  /* Placeholder interface only; will be removed after further WebIDL conversion.
-     Do not add anything here. */
-};
--- a/dom/media/nsIDOMNavigatorUserMedia.idl
+++ b/dom/media/nsIDOMNavigatorUserMedia.idl
@@ -1,15 +1,14 @@
 /* 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 "nsISupports.idl"
 #include "nsIVariant.idl"
-#include "nsIDOMMediaStream.idl"
 
 [scriptable, builtinclass, uuid(4af2bdb7-1547-4d10-8886-02a78c3c0b83)]
 interface nsIMediaDevice : nsISupports
 {
   readonly attribute DOMString type;
   readonly attribute DOMString name;
   readonly attribute DOMString id;
   readonly attribute DOMString facingMode;
@@ -22,17 +21,17 @@ interface nsIGetUserMediaDevicesSuccessC
   void onSuccess(in nsIVariant devices);
 };
 
 [scriptable, function, uuid(f2a144fc-3534-4761-8c5d-989ae720f89a)]
 interface nsIDOMGetUserMediaSuccessCallback : nsISupports
 {
   /*
    * value must be a nsIDOMBlob if picture is true and a
-   * nsIDOMLocalMediaStream if either audio or video are true.
+   * DOMLocalMediaStream if either audio or video are true.
    */
   void onSuccess(in nsISupports value);
 };
 
 [scriptable, function, uuid(2614bbcf-85cc-43e5-8740-964f52bdc7ca)]
 interface nsIDOMGetUserMediaErrorCallback : nsISupports
 {
   void onError(in DOMString error);
--- a/dom/system/gonk/AudioManager.cpp
+++ b/dom/system/gonk/AudioManager.cpp
@@ -194,22 +194,22 @@ IsDeviceOn(audio_devices_t device)
 static void ProcessDelayedAudioRoute(SwitchState aState)
 {
   if (sSwitchDone)
     return;
   InternalSetAudioRoutes(aState);
   sSwitchDone = true;
 }
 
-static void ProcessDelayedA2dpRoute(audio_policy_dev_state_t aState, const char *aAddress)
+static void ProcessDelayedA2dpRoute(audio_policy_dev_state_t aState, const nsCString aAddress)
 {
   if (sA2dpSwitchDone)
     return;
   AudioSystem::setDeviceConnectionState(AUDIO_DEVICE_OUT_BLUETOOTH_A2DP,
-                                        aState, aAddress);
+                                        aState, aAddress.get());
   String8 cmd("bluetooth_enabled=false");
   AudioSystem::setParameters(0, cmd);
   cmd.setTo("A2dpSuspended=true");
   AudioSystem::setParameters(0, cmd);
   sA2dpSwitchDone = true;
 }
 
 NS_IMPL_ISUPPORTS(AudioManager, nsIAudioManager, nsIObserver)
@@ -275,17 +275,17 @@ AudioManager::HandleBluetoothStatusChang
       int32_t force;
       GetForceForUse(nsIAudioManager::USE_COMMUNICATION, &force);
       if (force == nsIAudioManager::FORCE_BT_SCO)
         SetForceForUse(nsIAudioManager::USE_COMMUNICATION, nsIAudioManager::FORCE_NONE);
     }
   } else if (!strcmp(aTopic, BLUETOOTH_A2DP_STATUS_CHANGED_ID)) {
     if (audioState == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE && sA2dpSwitchDone) {
       MessageLoop::current()->PostDelayedTask(
-        FROM_HERE, NewRunnableFunction(&ProcessDelayedA2dpRoute, audioState, aAddress.get()), 1000);
+        FROM_HERE, NewRunnableFunction(&ProcessDelayedA2dpRoute, audioState, aAddress), 1000);
       sA2dpSwitchDone = false;
     } else {
       AudioSystem::setDeviceConnectionState(AUDIO_DEVICE_OUT_BLUETOOTH_A2DP,
                                             audioState, aAddress.get());
       String8 cmd("bluetooth_enabled=true");
       AudioSystem::setParameters(0, cmd);
       cmd.setTo("A2dpSuspended=false");
       AudioSystem::setParameters(0, cmd);
--- a/dom/telephony/Telephony.cpp
+++ b/dom/telephony/Telephony.cpp
@@ -595,18 +595,18 @@ Telephony::EnumerateCallState(uint32_t a
   nsRefPtr<TelephonyCall> call = GetCallFromEverywhere(aServiceId, aCallIndex);
   if (call) {
     return NS_OK;
   }
 
   // Didn't know anything about this call before now.
   nsRefPtr<TelephonyCallId> id = CreateCallId(aNumber, aNumberPresentation,
                                               aName, aNamePresentation);
-  CreateCall(id, aServiceId, aCallIndex, aCallState,
-             aIsEmergency, aIsConference, aIsSwitchable, aIsMergeable);
+  call = CreateCall(id, aServiceId, aCallIndex, aCallState,
+                    aIsEmergency, aIsConference, aIsSwitchable, aIsMergeable);
 
   return NS_OK;
 }
 
 NS_IMETHODIMP
 Telephony::SupplementaryServiceNotification(uint32_t aServiceId,
                                             int32_t aCallIndex,
                                             uint16_t aNotification)
--- a/dom/tests/mochitest/general/test_interfaces.html
+++ b/dom/tests/mochitest/general/test_interfaces.html
@@ -196,22 +196,28 @@ var interfaceNamesInGlobalScope =
     {name: "BoxObject", xbl: true},
 // IMPORTANT: Do not change this list without review from a DOM peer!
     {name: "CallEvent", b2g: true, pref: "dom.telephony.enabled"},
 // IMPORTANT: Do not change this list without review from a DOM peer!
     {name: "CallGroupErrorEvent", b2g: true, pref: "dom.telephony.enabled"},
 // IMPORTANT: Do not change this list without review from a DOM peer!
     {name: "CameraCapabilities", b2g: true},
 // IMPORTANT: Do not change this list without review from a DOM peer!
+    {name: "CameraConfigurationEvent", b2g: true},
+// IMPORTANT: Do not change this list without review from a DOM peer!
     {name: "CameraControl", b2g: true},
 // IMPORTANT: Do not change this list without review from a DOM peer!
     {name: "CameraDetectedFace", b2g: true, pref: "camera.control.face_detection.enabled"},
 // IMPORTANT: Do not change this list without review from a DOM peer!
+    {name: "CameraFacesDetectedEvent", b2g: true, pref: "camera.control.face_detection.enabled"},
+// IMPORTANT: Do not change this list without review from a DOM peer!
     {name: "CameraManager", b2g: true},
 // IMPORTANT: Do not change this list without review from a DOM peer!
+    {name: "CameraStateChangeEvent", b2g: true},
+// IMPORTANT: Do not change this list without review from a DOM peer!
     "CanvasGradient",
 // IMPORTANT: Do not change this list without review from a DOM peer!
     "CanvasPattern",
 // IMPORTANT: Do not change this list without review from a DOM peer!
     "CanvasRenderingContext2D",
 // IMPORTANT: Do not change this list without review from a DOM peer!
     "CaretPosition",
 // IMPORTANT: Do not change this list without review from a DOM peer!
new file mode 100644
--- /dev/null
+++ b/dom/webidl/CameraConfigurationEvent.webidl
@@ -0,0 +1,20 @@
+/* -*- Mode: IDL; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+[Func="Navigator::HasCameraSupport",
+ Constructor(DOMString type, optional CameraConfigurationEventInit eventInitDict)]
+interface CameraConfigurationEvent : Event
+{
+  readonly attribute CameraMode mode;
+  readonly attribute DOMString recorderProfile;
+  readonly attribute DOMRectReadOnly? previewSize;
+};
+
+dictionary CameraConfigurationEventInit : EventInit
+{
+  CameraMode mode = "picture";
+  DOMString recorderProfile = "cif";
+  DOMRectReadOnly? previewSize = null;
+};
--- a/dom/webidl/CameraControl.webidl
+++ b/dom/webidl/CameraControl.webidl
@@ -230,30 +230,58 @@ interface CameraControl : MediaStream
      value is "auto" if supported. */
   [Throws]
   attribute DOMString       isoMode;
 
   /* the function to call on the camera's shutter event, to trigger
      a shutter sound and/or a visual shutter indicator. */
   attribute CameraShutterCallback? onShutter;
 
+  /* the event dispatched on the camera's shutter event, to trigger
+     a shutter sound and/or a visual shutter indicator.
+
+     contains no event-specific data. */
+  attribute EventHandler onshutter;
+
   /* the function to call when the camera hardware is closed
      by the underlying framework, e.g. when another app makes a more
      recent call to get the camera. */
   attribute CameraClosedCallback? onClosed;
 
+  /* the event dispatched when the camera hardware is closed
+     by the underlying framework, e.g. when another app makes a more
+     recent call to get the camera.
+
+     contains no event-specific data. */
+  attribute EventHandler onclose;
+
   /* the function to call when the recorder changes state, either because
      the recording process encountered an error, or because one of the
      recording limits (see CameraStartRecordingOptions) was reached. */
   attribute CameraRecorderStateChange? onRecorderStateChange;
 
+  /* the event dispatched when the recorder changes state, either because
+     the recording process encountered an error, or because one of the
+     recording limits (see CameraStartRecordingOptions) was reached.
+
+     event type is CameraStateChangeEvent where:
+         'newState' is the new recorder state */
+  attribute EventHandler onrecorderstatechange;
+
   /* the function to call when the viewfinder stops or starts,
      useful for synchronizing other UI elements. */
   attribute CameraPreviewStateChange? onPreviewStateChange;
 
+  /* the event dispatched when the viewfinder stops or starts,
+     useful for synchronizing other UI elements.
+
+     event type is CameraStateChangeEvent where:
+         'newState' is the new preview state */
+  attribute EventHandler onpreviewstatechange;
+
   /* the size of the picture to be returned by a call to takePicture();
      an object with 'height' and 'width' properties that corresponds to
      one of the options returned by capabilities.pictureSizes. */
   [Throws]
   CameraSize getPictureSize();
   [Throws]
   void setPictureSize(optional CameraSize size);
 
@@ -282,17 +310,35 @@ interface CameraControl : MediaStream
   /* the angle, in degrees, that the image sensor is mounted relative
      to the display; e.g. if 'sensorAngle' is 270 degrees (or -90 degrees),
      then the preview stream needs to be rotated +90 degrees to have the
      same orientation as the real world. */
   readonly attribute long   sensorAngle;
 
   /* tell the camera to attempt to focus the image */
   [Throws]
-  void autoFocus(CameraAutoFocusCallback onSuccess, optional CameraErrorCallback onError);
+  Promise<boolean> autoFocus(optional CameraAutoFocusCallback onSuccess,
+                             optional CameraErrorCallback onError);
+
+  /* the event dispatched whenever the focus state changes due to calling
+     autoFocus or due to continuous autofocus.
+
+     if continuous autofocus is supported and focusMode is set to enable it,
+     then this event is dispatched whenever the camera decides to start and
+     stop moving the focus position; it can be used to update a UI element to
+     indicate that the camera is still trying to focus, or has finished. Some
+     platforms do not support this event, in which case the callback is never
+     invoked.
+
+     event type is CameraStateChangeEvent where:
+         'newState' is one of the following states:
+             'focused' if the focus is now set
+             'focusing' if the focus is moving
+             'unfocused' if last attempt to focus failed */
+  attribute EventHandler onfocus;
 
   /* if continuous autofocus is supported and focusMode is set to enable it,
      then this function is called whenever the camera decides to start and
      stop moving the focus position; it can be used to update a UI element to
      indicate that the camera is still trying to focus, or has finished. Some
      platforms do not support this event, in which case the callback is never
      invoked. */
   [Pref="camera.control.autofocus_moving_callback.enabled"]
@@ -304,28 +350,33 @@ interface CameraControl : MediaStream
 
   /* capture an image and return it as a blob to the 'onSuccess' callback;
      if the camera supports it, this may be invoked while the camera is
      already recording video.
 
      invoking this function will stop the preview stream, which must be
      manually restarted (e.g. by calling .play() on it). */
   [Throws]
-  void takePicture(CameraPictureOptions aOptions,
-                   CameraTakePictureCallback onSuccess,
-                   optional CameraErrorCallback onError);
+  Promise<Blob> takePicture(optional CameraPictureOptions aOptions,
+                            optional CameraTakePictureCallback onSuccess,
+                            optional CameraErrorCallback onError);
+
+  /* the event dispatched when a picture is successfully taken; it is of the
+     type BlobEvent, where the data attribute contains the picture. */
+  attribute EventHandler onpicture;
 
-  /* start recording video; 'aOptions' is a
-     CameraStartRecordingOptions object. */
+  /* start recording video; 'aOptions' is a CameraStartRecordingOptions object.
+     If the success/error callbacks are not used, one may determine success by
+     waiting for the recorderstatechange event. */
   [Throws]
-  void startRecording(CameraStartRecordingOptions aOptions,
-                      DeviceStorage storageArea,
-                      DOMString filename,
-                      CameraStartRecordingCallback onSuccess,
-                      optional CameraErrorCallback onError);
+  Promise<void> startRecording(CameraStartRecordingOptions aOptions,
+                               DeviceStorage storageArea,
+                               DOMString filename,
+                               optional CameraStartRecordingCallback onSuccess,
+                               optional CameraErrorCallback onError);
 
   /* stop precording video. */
   [Throws]
   void stopRecording();
 
   /* call in or after the takePicture() onSuccess callback to
      resume the camera preview stream. */
   [Throws]
@@ -336,31 +387,40 @@ interface CameraControl : MediaStream
      (depending on your usage model).
 
      the callbacks are optional, unless you really need to know when
      the hardware is ultimately released.
 
      once this is called, the camera control object is to be considered
      defunct; a new instance will need to be created to access the camera. */
   [Throws]
-  void release(optional CameraReleaseCallback onSuccess,
-               optional CameraErrorCallback onError);
+  Promise<void> release(optional CameraReleaseCallback onSuccess,
+                        optional CameraErrorCallback onError);
 
   /* changes the camera configuration on the fly;
      'configuration' is of type CameraConfiguration.
 
      XXXmikeh the 'configuration' argument needs to be optional, else
      the WebIDL compiler throws: "WebIDL.WebIDLError: error: Dictionary
      argument or union argument containing a dictionary not followed by
      a required argument must be optional"
   */
   [Throws]
-  void setConfiguration(optional CameraConfiguration configuration,
-                        optional CameraSetConfigurationCallback onSuccess,
-                        optional CameraErrorCallback onError);
+  Promise<CameraConfiguration> setConfiguration(optional CameraConfiguration configuration,
+                                                optional CameraSetConfigurationCallback onSuccess,
+                                                optional CameraErrorCallback onError);
+
+  /* the event dispatched when the camera is successfully configured.
+
+     event type is CameraConfigurationEvent where:
+         'mode' is the selected camera mode
+         'recorderProfile' is the selected profile
+         'width' contains the preview width
+         'height' contains the preview height */
+  attribute EventHandler onconfigurationchange;
 
   /* if focusMode is set to either 'continuous-picture' or 'continuous-video',
      then calling autoFocus() will trigger its onSuccess callback immediately
      if the camera was either successfully focused, or if no focus could be
      acquired; if the focus acquisition is still in progress, the onSuccess
      callback will be invoked later, its argument indicating success or
      failure.
 
@@ -452,9 +512,13 @@ partial interface CameraControl
   */
   [Throws, Pref="camera.control.face_detection.enabled"]
   void stopFaceDetection();
 
   /* Callback for faces detected in the preview frame. If no faces are
      detected, the callback is invoked with an empty sequence. */
   [Pref="camera.control.face_detection.enabled"]
   attribute CameraFaceDetectionCallback? onFacesDetected;
+
+  /* CameraFacesDetectedEvent */
+  [Pref="camera.control.face_detection.enabled"]
+  attribute EventHandler onfacesdetected;
 };
new file mode 100644
--- /dev/null
+++ b/dom/webidl/CameraFacesDetectedEvent.webidl
@@ -0,0 +1,18 @@
+/* -*- Mode: IDL; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+[Pref="camera.control.face_detection.enabled",
+ Func="Navigator::HasCameraSupport",
+ Constructor(DOMString type, optional CameraFacesDetectedEventInit eventInitDict)]
+interface CameraFacesDetectedEvent : Event
+{
+  [Pure, Cached]
+  readonly attribute sequence<CameraDetectedFace>? faces;
+};
+
+dictionary CameraFacesDetectedEventInit : EventInit
+{
+  sequence<CameraDetectedFace>? faces = null;
+};
--- a/dom/webidl/CameraManager.webidl
+++ b/dom/webidl/CameraManager.webidl
@@ -31,19 +31,19 @@ callback GetCameraCallback = void (Camer
 
 [Func="nsDOMCameraManager::HasSupport"]
 interface CameraManager
 {
   /* get a camera instance; 'camera' is one of the camera
      identifiers returned by getListOfCameras() below.
   */
   [Throws]
-  void getCamera(DOMString camera,
-                 CameraConfiguration initialConfiguration,
-                 GetCameraCallback callback,
-                 optional CameraErrorCallback errorCallback);
+  Promise<CameraGetPromiseData> getCamera(DOMString camera,
+                                          optional CameraConfiguration initialConfiguration,
+                                          optional GetCameraCallback callback,
+                                          optional CameraErrorCallback errorCallback);
 
   /* return an array of camera identifiers, e.g.
        [ "front", "back" ]
    */
   [Throws]
   sequence<DOMString> getListOfCameras();
 };
new file mode 100644
--- /dev/null
+++ b/dom/webidl/CameraStateChangeEvent.webidl
@@ -0,0 +1,16 @@
+/* -*- Mode: IDL; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+[Func="Navigator::HasCameraSupport",
+ Constructor(DOMString type, optional CameraStateChangeEventInit eventInitDict)]
+interface CameraStateChangeEvent : Event
+{
+  readonly attribute DOMString newState;
+};
+
+dictionary CameraStateChangeEventInit : EventInit
+{
+  DOMString newState = "";
+};
new file mode 100644
--- /dev/null
+++ b/dom/webidl/CameraUtil.webidl
@@ -0,0 +1,12 @@
+/* -*- Mode: IDL; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/.
+ */
+
+dictionary CameraGetPromiseData
+{
+  CameraControl? camera = null;
+  CameraConfiguration configuration;
+};
--- a/dom/webidl/MediaStream.webidl
+++ b/dom/webidl/MediaStream.webidl
@@ -16,17 +16,17 @@
 dictionary MediaStreamConstraints {
     (boolean or MediaTrackConstraints) audio = false;
     (boolean or MediaTrackConstraints) video = false;
     boolean picture = false; // Mozilla legacy
     boolean fake = false;    // for testing
     DOMString? peerIdentity = null;
 };
 
-interface MediaStream {
+interface MediaStream : EventTarget {
     // readonly attribute DOMString    id;
     sequence<AudioStreamTrack> getAudioTracks();
     sequence<VideoStreamTrack> getVideoTracks();
     sequence<MediaStreamTrack> getTracks();
     // MediaStreamTrack           getTrackById (DOMString trackId);
     // void                       addTrack (MediaStreamTrack track);
     // void                       removeTrack (MediaStreamTrack track);
     //         attribute boolean      ended;
--- a/dom/webidl/moz.build
+++ b/dom/webidl/moz.build
@@ -52,16 +52,17 @@ WEBIDL_FILES = [
     'BeforeUnloadEvent.webidl',
     'BiquadFilterNode.webidl',
     'Blob.webidl',
     'BrowserElementDictionaries.webidl',
     'CallsList.webidl',
     'CameraCapabilities.webidl',
     'CameraControl.webidl',
     'CameraManager.webidl',
+    'CameraUtil.webidl',
     'CanvasRenderingContext2D.webidl',
     'CaretPosition.webidl',
     'CDATASection.webidl',
     'ChannelMergerNode.webidl',
     'ChannelSplitterNode.webidl',
     'CharacterData.webidl',
     'ChildNode.webidl',
     'ChromeNotifications.webidl',
@@ -647,16 +648,19 @@ if CONFIG['MOZ_B2G_FM']:
         'FMRadio.webidl',
     ]
 
 GENERATED_EVENTS_WEBIDL_FILES = [
     'AutocompleteErrorEvent.webidl',
     'BlobEvent.webidl',
     'CallEvent.webidl',
     'CallGroupErrorEvent.webidl',
+    'CameraConfigurationEvent.webidl',
+    'CameraFacesDetectedEvent.webidl',
+    'CameraStateChangeEvent.webidl',
     'CFStateChangeEvent.webidl',
     'CloseEvent.webidl',
     'CSSFontFaceLoadEvent.webidl',
     'DataErrorEvent.webidl',
     'DataStoreChangeEvent.webidl',
     'DeviceLightEvent.webidl',
     'DeviceOrientationEvent.webidl',
     'DeviceProximityEvent.webidl',
--- a/media/webrtc/signaling/src/peerconnection/PeerConnectionImpl.cpp
+++ b/media/webrtc/signaling/src/peerconnection/PeerConnectionImpl.cpp
@@ -698,17 +698,17 @@ PeerConnectionImpl::GetFingerprintHexVal
   if (NS_SUCCEEDED(FingerprintSplitHelper(fp, spc))) {
     return fp.substr(spc + 1);
   }
   return "";
 }
 
 
 nsresult
-PeerConnectionImpl::CreateFakeMediaStream(uint32_t aHint, nsIDOMMediaStream** aRetval)
+PeerConnectionImpl::CreateFakeMediaStream(uint32_t aHint, DOMMediaStream** aRetval)
 {
   MOZ_ASSERT(aRetval);
   PC_AUTO_ENTER_API_CALL(false);
 
   bool mute = false;
 
   // Hack to allow you to mute the stream
   if (aHint & MEDIA_STREAM_MUTE) {
--- a/media/webrtc/signaling/src/peerconnection/PeerConnectionImpl.h
+++ b/media/webrtc/signaling/src/peerconnection/PeerConnectionImpl.h
@@ -49,17 +49,16 @@ class AFakePCObserver;
 }
 
 #ifdef USE_FAKE_MEDIA_STREAMS
 class Fake_DOMMediaStream;
 class Fake_MediaStreamTrack;
 #endif
 
 class nsGlobalWindow;
-class nsIDOMMediaStream;
 class nsDOMDataChannel;
 
 namespace mozilla {
 class DataChannel;
 class DtlsIdentity;
 class NrIceCtx;
 class NrIceMediaStream;
 class NrIceStunServer;
@@ -290,17 +289,17 @@ public:
 
   // Get the DTLS identity (local side)
   mozilla::RefPtr<DtlsIdentity> const GetIdentity() const;
   std::string GetFingerprint() const;
   std::string GetFingerprintAlgorithm() const;
   std::string GetFingerprintHexValue() const;
 
   // Create a fake media stream
-  nsresult CreateFakeMediaStream(uint32_t hint, nsIDOMMediaStream** retval);
+  nsresult CreateFakeMediaStream(uint32_t hint, mozilla::DOMMediaStream** retval);
 
   nsPIDOMWindow* GetWindow() const {
     PC_AUTO_ENTER_API_CALL_NO_CHECK();
     return mWindow;
   }
 
   // Initialize PeerConnection from an IceConfiguration object (unit-tests)
   nsresult Initialize(PeerConnectionObserver& aObserver,
--- a/media/webrtc/signaling/src/peerconnection/PeerConnectionMedia.cpp
+++ b/media/webrtc/signaling/src/peerconnection/PeerConnectionMedia.cpp
@@ -290,29 +290,27 @@ nsresult PeerConnectionMedia::Init(const
   // figure out how to report that StartGathering failed. Bug 827982.
   RUN_ON_THREAD(mIceCtx->thread(),
                 WrapRunnable(mIceCtx, &NrIceCtx::StartGathering), NS_DISPATCH_NORMAL);
 
   return NS_OK;
 }
 
 nsresult
-PeerConnectionMedia::AddStream(nsIDOMMediaStream* aMediaStream,
+PeerConnectionMedia::AddStream(DOMMediaStream* aMediaStream,
                                uint32_t hints,
                                uint32_t *stream_id)
 {
   ASSERT_ON_THREAD(mMainThread);
 
   if (!aMediaStream) {
     CSFLogError(logTag, "%s - aMediaStream is NULL", __FUNCTION__);
     return NS_ERROR_FAILURE;
   }
 
-  DOMMediaStream* stream = static_cast<DOMMediaStream*>(aMediaStream);
-
   CSFLogDebug(logTag, "%s: MediaStream: %p", __FUNCTION__, aMediaStream);
 
   // Adding tracks here based on nsDOMMediaStream expectation settings
 #ifdef MOZILLA_INTERNAL_API
   if (!Preferences::GetBool("media.peerconnection.video.enabled", true)) {
     hints &= ~(DOMMediaStream::HINT_CONTENTS_VIDEO);
   }
 #endif
@@ -331,54 +329,52 @@ PeerConnectionMedia::AddStream(nsIDOMMed
 
   for (uint32_t u = 0; u < mLocalSourceStreams.Length(); u++) {
     auto& lss = mLocalSourceStreams[u];
     if (((hints & DOMMediaStream::HINT_CONTENTS_AUDIO) && lss->AudioTrackCount()) ||
         ((hints & DOMMediaStream::HINT_CONTENTS_VIDEO) && lss->VideoTrackCount())) {
       CSFLogError(logTag, "Only one stream of any given type allowed");
       return NS_ERROR_FAILURE;
     }
-    if (stream == lss->GetMediaStream()) {
+    if (aMediaStream == lss->GetMediaStream()) {
       localSourceStream = lss;
       *stream_id = u;
       break;
     }
   }
   if (!localSourceStream) {
-    localSourceStream = new LocalSourceStreamInfo(stream, this);
+    localSourceStream = new LocalSourceStreamInfo(aMediaStream, this);
     mLocalSourceStreams.AppendElement(localSourceStream);
     *stream_id = mLocalSourceStreams.Length() - 1;
   }
 
   if (hints & DOMMediaStream::HINT_CONTENTS_AUDIO) {
     localSourceStream->ExpectAudio(TRACK_AUDIO);
   }
 
   if (hints & DOMMediaStream::HINT_CONTENTS_VIDEO) {
     localSourceStream->ExpectVideo(TRACK_VIDEO);
   }
   return NS_OK;
 }
 
 nsresult
-PeerConnectionMedia::RemoveStream(nsIDOMMediaStream* aMediaStream,
+PeerConnectionMedia::RemoveStream(DOMMediaStream* aMediaStream,
                                   uint32_t hints,
                                   uint32_t *stream_id)
 {
   MOZ_ASSERT(aMediaStream);
   ASSERT_ON_THREAD(mMainThread);
 
-  DOMMediaStream* stream = static_cast<DOMMediaStream*>(aMediaStream);
-
   CSFLogDebug(logTag, "%s: MediaStream: %p",
     __FUNCTION__, aMediaStream);
 
   for (uint32_t u = 0; u < mLocalSourceStreams.Length(); u++) {
     nsRefPtr<LocalSourceStreamInfo> localSourceStream = mLocalSourceStreams[u];
-    if (localSourceStream->GetMediaStream() == stream) {
+    if (localSourceStream->GetMediaStream() == aMediaStream) {
       *stream_id = u;
 
       if (hints & DOMMediaStream::HINT_CONTENTS_AUDIO) {
         localSourceStream->RemoveAudio(TRACK_AUDIO);
       }
       if (hints & DOMMediaStream::HINT_CONTENTS_VIDEO) {
         localSourceStream->RemoveAudio(TRACK_VIDEO);
       }
--- a/media/webrtc/signaling/src/peerconnection/PeerConnectionMedia.h
+++ b/media/webrtc/signaling/src/peerconnection/PeerConnectionMedia.h
@@ -307,21 +307,21 @@ class PeerConnectionMedia : public sigsl
     return mIceStreams[i];
   }
 
   size_t num_ice_media_streams() const {
     return mIceStreams.size();
   }
 
   // Add a stream (main thread only)
-  nsresult AddStream(nsIDOMMediaStream* aMediaStream, uint32_t hints,
+  nsresult AddStream(DOMMediaStream* aMediaStream, uint32_t hints,
                      uint32_t *stream_id);
 
   // Remove a stream (main thread only)
-  nsresult RemoveStream(nsIDOMMediaStream* aMediaStream,
+  nsresult RemoveStream(DOMMediaStream* aMediaStream,
                         uint32_t hints,
                         uint32_t *stream_id);
 
   // Get a specific local stream
   uint32_t LocalStreamsLength()
   {
     return mLocalSourceStreams.Length();
   }
--- a/media/webrtc/signaling/test/FakeMediaStreams.h
+++ b/media/webrtc/signaling/test/FakeMediaStreams.h
@@ -17,17 +17,16 @@
 #include "mozilla/Mutex.h"
 #include "mozilla/RefPtr.h"
 #include "AudioSegment.h"
 #include "MediaSegment.h"
 #include "StreamBuffer.h"
 #include "nsTArray.h"
 #include "nsIRunnable.h"
 #include "nsISupportsImpl.h"
-#include "nsIDOMMediaStream.h"
 
 class nsIDOMWindow;
 
 namespace mozilla {
    class MediaStreamGraph;
    class MediaSegment;
 };
 
@@ -227,17 +226,17 @@ public:
   const Fake_MediaStreamTrack* AsAudioStreamTrack() const
   {
     return mIsVideo? nullptr : this;
   }
 private:
   const bool mIsVideo;
 };
 
-class Fake_DOMMediaStream : public nsIDOMMediaStream
+class Fake_DOMMediaStream : public nsISupports
 {
 protected:
   virtual ~Fake_DOMMediaStream() {
     // Note: memory leak
     mMediaStream->Stop();
   }
 
 public:
--- a/media/webrtc/signaling/test/FakeMediaStreamsImpl.h
+++ b/media/webrtc/signaling/test/FakeMediaStreamsImpl.h
@@ -12,17 +12,17 @@
 
 void LogTime(AsyncLatencyLogger::LatencyLogIndex index, uint64_t b, int64_t c) {}
 void LogLatency(AsyncLatencyLogger::LatencyLogIndex index, uint64_t b, int64_t c) {}
 
 static const int AUDIO_BUFFER_SIZE = 1600;
 static const int NUM_CHANNELS      = 2;
 static const int GRAPH_RATE        = 16000;
 
-NS_IMPL_ISUPPORTS(Fake_DOMMediaStream, nsIDOMMediaStream)
+NS_IMPL_ISUPPORTS0(Fake_DOMMediaStream)
 
 // Fake_MediaStream
 double Fake_MediaStream::StreamTimeToSeconds(mozilla::StreamTime aTime) {
   return static_cast<double>(aTime)/GRAPH_RATE;
 }
 
 mozilla::StreamTime
 Fake_MediaStream::TicksToTimeRoundDown(mozilla::TrackRate aRate,
--- a/media/webrtc/signaling/test/FakePCObserver.h
+++ b/media/webrtc/signaling/test/FakePCObserver.h
@@ -13,17 +13,16 @@
 
 #include "mozilla/Mutex.h"
 #include "AudioSegment.h"
 #include "MediaSegment.h"
 #include "StreamBuffer.h"
 #include "nsTArray.h"
 #include "nsIRunnable.h"
 #include "nsISupportsImpl.h"
-#include "nsIDOMMediaStream.h"
 #include "mozilla/dom/PeerConnectionObserverEnumsBinding.h"
 #include "PeerConnectionImpl.h"
 #include "nsWeakReference.h"
 
 namespace sipcc {
 class PeerConnectionImpl;
 }
 
@@ -75,17 +74,17 @@ public:
   virtual NS_IMETHODIMP OnCreateAnswerError(uint32_t code, const char *msg, ER&) = 0;
   virtual NS_IMETHODIMP OnSetLocalDescriptionSuccess(ER&) = 0;
   virtual NS_IMETHODIMP OnSetRemoteDescriptionSuccess(ER&) = 0;
   virtual NS_IMETHODIMP OnSetLocalDescriptionError(uint32_t code, const char *msg, ER&) = 0;
   virtual NS_IMETHODIMP OnSetRemoteDescriptionError(uint32_t code, const char *msg, ER&) = 0;
   virtual NS_IMETHODIMP NotifyDataChannel(nsIDOMDataChannel *channel, ER&) = 0;
   virtual NS_IMETHODIMP OnStateChange(mozilla::dom::PCObserverStateType state_type, ER&,
                                       void* = nullptr) = 0;
-  virtual NS_IMETHODIMP OnAddStream(nsIDOMMediaStream *stream, ER&) = 0;
+  virtual NS_IMETHODIMP OnAddStream(mozilla::DOMMediaStream *stream, ER&) = 0;
   virtual NS_IMETHODIMP OnRemoveStream(ER&) = 0;
   virtual NS_IMETHODIMP OnAddTrack(ER&) = 0;
   virtual NS_IMETHODIMP OnRemoveTrack(ER&) = 0;
   virtual NS_IMETHODIMP OnReplaceTrackSuccess(ER&) = 0;
   virtual NS_IMETHODIMP OnReplaceTrackError(uint32_t code, const char *msg, ER&) = 0;
   virtual NS_IMETHODIMP OnAddIceCandidateSuccess(ER&) = 0;
   virtual NS_IMETHODIMP OnAddIceCandidateError(uint32_t code, const char *msg, ER&) = 0;
   virtual NS_IMETHODIMP OnIceCandidate(uint16_t level, const char *mid,
--- a/media/webrtc/signaling/test/signaling_unittests.cpp
+++ b/media/webrtc/signaling/test/signaling_unittests.cpp
@@ -264,17 +264,17 @@ public:
   NS_IMETHODIMP OnCreateAnswerSuccess(const char* answer, ER&);
   NS_IMETHODIMP OnCreateAnswerError(uint32_t code, const char *msg, ER&);
   NS_IMETHODIMP OnSetLocalDescriptionSuccess(ER&);
   NS_IMETHODIMP OnSetRemoteDescriptionSuccess(ER&);
   NS_IMETHODIMP OnSetLocalDescriptionError(uint32_t code, const char *msg, ER&);
   NS_IMETHODIMP OnSetRemoteDescriptionError(uint32_t code, const char *msg, ER&);
   NS_IMETHODIMP NotifyDataChannel(nsIDOMDataChannel *channel, ER&);
   NS_IMETHODIMP OnStateChange(PCObserverStateType state_type, ER&, void*);
-  NS_IMETHODIMP OnAddStream(nsIDOMMediaStream *stream, ER&);
+  NS_IMETHODIMP OnAddStream(DOMMediaStream *stream, ER&);
   NS_IMETHODIMP OnRemoveStream(ER&);
   NS_IMETHODIMP OnAddTrack(ER&);
   NS_IMETHODIMP OnRemoveTrack(ER&);
   NS_IMETHODIMP OnReplaceTrackSuccess(ER&);
   NS_IMETHODIMP OnReplaceTrackError(uint32_t code, const char *msg, ER&);
   NS_IMETHODIMP OnAddIceCandidateSuccess(ER&);
   NS_IMETHODIMP OnAddIceCandidateError(uint32_t code, const char *msg, ER&);
   NS_IMETHODIMP OnIceCandidate(uint16_t level, const char *mid, const char *cand, ER&);
@@ -424,33 +424,31 @@ TestObserver::OnStateChange(PCObserverSt
   }
 
   lastStateType = state_type;
   return NS_OK;
 }
 
 
 NS_IMETHODIMP
-TestObserver::OnAddStream(nsIDOMMediaStream *stream, ER&)
+TestObserver::OnAddStream(DOMMediaStream *stream, ER&)
 {
   PR_ASSERT(stream);
 
-  DOMMediaStream *ms = static_cast<DOMMediaStream *>(stream);
-
-  std::cout << name << ": OnAddStream called hints=" << ms->GetHintContents()
+  std::cout << name << ": OnAddStream called hints=" << stream->GetHintContents()
             << " thread=" << PR_GetCurrentThread() << std::endl ;
 
   onAddStreamCalled = true;
 
-  streams.push_back(ms);
+  streams.push_back(stream);
 
   // We know that the media stream is secretly a Fake_SourceMediaStream,
   // so now we can start it pulling from us
   nsRefPtr<Fake_SourceMediaStream> fs =
-    static_cast<Fake_SourceMediaStream *>(ms->GetStream());
+    static_cast<Fake_SourceMediaStream *>(stream->GetStream());
 
   test_utils->sts_target()->Dispatch(
     WrapRunnable(fs, &Fake_SourceMediaStream::Start),
     NS_DISPATCH_NORMAL);
 
   return NS_OK;
 }
 
--- a/mobile/android/base/favicons/Favicons.java
+++ b/mobile/android/base/favicons/Favicons.java
@@ -404,17 +404,17 @@ public class Favicons {
                 isNewTabletEnabled ? R.drawable.new_tablet_default_favicon : R.drawable.favicon;
         defaultFavicon = BitmapFactory.decodeResource(res, defaultFaviconDrawableID);
         if (defaultFavicon == null) {
             throw new IllegalStateException("Null default favicon was returned from the resources system!");
         }
 
         // TODO: Remove this branch when old tablet is removed.
         final int defaultFaviconSizeDimenID =
-                isNewTabletEnabled ? R.dimen.tab_strip_favicon_size : R.dimen.favicon_bg;
+                isNewTabletEnabled ? R.dimen.new_tablet_tab_strip_favicon_size : R.dimen.favicon_bg;
         defaultFaviconSize = res.getDimensionPixelSize(defaultFaviconSizeDimenID);
 
         // Screen-density-adjusted upper limit on favicon size. Favicons larger than this are
         // downscaled to this size or discarded.
         largestFaviconSize = context.getResources().getDimensionPixelSize(R.dimen.favicon_largest_interesting_size);
         faviconsCache = new FaviconCache(FAVICON_CACHE_SIZE_BYTES, largestFaviconSize);
 
         // Initialize page mappings for each of our special pages.
--- a/mobile/android/base/moz.build
+++ b/mobile/android/base/moz.build
@@ -395,20 +395,16 @@ gbjar.sources += [
     'tabs/RemoteTabsSetupPanel.java',
     'tabs/RemoteTabsVerificationPanel.java',
     'tabs/TabCurve.java',
     'tabs/TabsGridLayout.java',
     'tabs/TabsLayoutAdapter.java',
     'tabs/TabsLayoutItemView.java',
     'tabs/TabsListLayout.java',
     'tabs/TabsPanel.java',
-    'tabs/TabStrip.java',
-    'tabs/TabStripAdapter.java',
-    'tabs/TabStripItemView.java',
-    'tabs/TabStripView.java',
     'TabsAccessor.java',
     'Telemetry.java',
     'TelemetryContract.java',
     'TextSelection.java',
     'TextSelectionHandle.java',
     'ThumbnailHelper.java',
     'toolbar/AutocompleteHandler.java',
     'toolbar/BackButton.java',
@@ -508,16 +504,30 @@ if CONFIG['MOZ_ANDROID_SHARE_OVERLAY']:
         'overlays/ui/OverlayDialogButton.java',
         'overlays/ui/OverlayToastHelper.java',
         'overlays/ui/SendTabDeviceListArrayAdapter.java',
         'overlays/ui/SendTabList.java',
         'overlays/ui/SendTabTargetSelectedListener.java',
         'overlays/ui/ShareDialog.java',
     ]
 
+if (CONFIG['MOZ_ANDROID_MAX_SDK_VERSION']):
+    max_sdk_version = int(CONFIG['MOZ_ANDROID_MAX_SDK_VERSION'])
+else:
+    max_sdk_version = 999
+
+if CONFIG['MOZ_ANDROID_NEW_TABLET_UI'] and max_sdk_version >= 11:
+    gbjar.sources += [
+        'tabs/TabStrip.java',
+        'tabs/TabStripAdapter.java',
+        'tabs/TabStripItemView.java',
+        'tabs/TabStripView.java'
+    ]
+    ANDROID_RES_DIRS += [ SRCDIR + '/newtablet/res' ]
+
 gbjar.sources += sync_java_files
 gbjar.generated_sources += sync_generated_java_files
 gbjar.extra_jars = [
     'gecko-R.jar',
     'gecko-mozglue.jar',
     'gecko-thirdparty.jar',
     'gecko-util.jar',
     'sync-thirdparty.jar',
@@ -614,17 +624,18 @@ ANDROID_RES_DIRS += [
 
 ANDROID_GENERATED_RESFILES += [
     'res/raw/suggestedsites.json',
     'res/values/strings.xml',
 ]
 
 for var in ('MOZ_ANDROID_ANR_REPORTER', 'MOZ_LINKER_EXTRACT', 'MOZILLA_OFFICIAL', 'MOZ_DEBUG',
             'MOZ_ANDROID_SEARCH_ACTIVITY', 'MOZ_NATIVE_DEVICES', 'MOZ_ANDROID_MLS_STUMBLER',
-            'MOZ_ANDROID_SHARE_OVERLAY', 'MOZ_ANDROID_DOWNLOADS_INTEGRATION'):
+            'MOZ_ANDROID_SHARE_OVERLAY', 'MOZ_ANDROID_DOWNLOADS_INTEGRATION',
+            'MOZ_ANDROID_NEW_TABLET_UI'):
     if CONFIG[var]:
         DEFINES[var] = 1
 
 for var in ('MOZ_UPDATER', 'MOZ_PKG_SPECIAL'):
     if CONFIG[var]:
         DEFINES[var] = CONFIG[var]
 
 for var in ('ANDROID_PACKAGE_NAME', 'ANDROID_CPU_ARCH', 'CPU_ARCH',
rename from mobile/android/base/resources/color-large-v11/new_tablet_tab_strip_item_title.xml
rename to mobile/android/base/newtablet/res/color-large-v11/new_tablet_tab_strip_item_title.xml
rename from mobile/android/base/resources/drawable-large-hdpi-v11/new_tablet_default_favicon.png
rename to mobile/android/base/newtablet/res/drawable-large-hdpi-v11/new_tablet_default_favicon.png
rename from mobile/android/base/resources/drawable-large-hdpi-v11/new_tablet_ic_menu_back.png
rename to mobile/android/base/newtablet/res/drawable-large-hdpi-v11/new_tablet_ic_menu_back.png
rename from mobile/android/base/resources/drawable-large-hdpi-v11/new_tablet_ic_menu_forward.png
rename to mobile/android/base/newtablet/res/drawable-large-hdpi-v11/new_tablet_ic_menu_forward.png
rename from mobile/android/base/resources/drawable-large-hdpi-v11/new_tablet_ic_menu_reload.png
rename to mobile/android/base/newtablet/res/drawable-large-hdpi-v11/new_tablet_ic_menu_reload.png
rename from mobile/android/base/resources/drawable-large-hdpi-v11/new_tablet_menu.png
rename to mobile/android/base/newtablet/res/drawable-large-hdpi-v11/new_tablet_menu.png
rename from mobile/android/base/resources/drawable-large-hdpi-v11/new_tablet_tabs_count.png
rename to mobile/android/base/newtablet/res/drawable-large-hdpi-v11/new_tablet_tabs_count.png
rename from mobile/android/base/resources/drawable-large-hdpi-v11/new_tablet_tabs_count_foreground.png
rename to mobile/android/base/newtablet/res/drawable-large-hdpi-v11/new_tablet_tabs_count_foreground.png
rename from mobile/android/base/resources/drawable-large-mdpi-v11/new_tablet_default_favicon.png
rename to mobile/android/base/newtablet/res/drawable-large-mdpi-v11/new_tablet_default_favicon.png
rename from mobile/android/base/resources/drawable-large-mdpi-v11/new_tablet_ic_menu_back.png
rename to mobile/android/base/newtablet/res/drawable-large-mdpi-v11/new_tablet_ic_menu_back.png
rename from mobile/android/base/resources/drawable-large-mdpi-v11/new_tablet_ic_menu_forward.png
rename to mobile/android/base/newtablet/res/drawable-large-mdpi-v11/new_tablet_ic_menu_forward.png
rename from mobile/android/base/resources/drawable-large-mdpi-v11/new_tablet_ic_menu_reload.png
rename to mobile/android/base/newtablet/res/drawable-large-mdpi-v11/new_tablet_ic_menu_reload.png
rename from mobile/android/base/resources/drawable-large-mdpi-v11/new_tablet_menu.png
rename to mobile/android/base/newtablet/res/drawable-large-mdpi-v11/new_tablet_menu.png
rename from mobile/android/base/resources/drawable-large-mdpi-v11/new_tablet_tabs_count.png
rename to mobile/android/base/newtablet/res/drawable-large-mdpi-v11/new_tablet_tabs_count.png
rename from mobile/android/base/resources/drawable-large-mdpi-v11/new_tablet_tabs_count_foreground.png
rename to mobile/android/base/newtablet/res/drawable-large-mdpi-v11/new_tablet_tabs_count_foreground.png
rename from mobile/android/base/resources/drawable-large-v11/new_tablet_tab_strip_divider.xml
rename to mobile/android/base/newtablet/res/drawable-large-v11/new_tablet_tab_strip_divider.xml
rename from mobile/android/base/resources/drawable-large-v11/new_tablet_tab_strip_item_bg.xml
rename to mobile/android/base/newtablet/res/drawable-large-v11/new_tablet_tab_strip_item_bg.xml
rename from mobile/android/base/resources/drawable-large-xhdpi-v11/new_tablet_default_favicon.png
rename to mobile/android/base/newtablet/res/drawable-large-xhdpi-v11/new_tablet_default_favicon.png
rename from mobile/android/base/resources/drawable-large-xhdpi-v11/new_tablet_ic_menu_back.png
rename to mobile/android/base/newtablet/res/drawable-large-xhdpi-v11/new_tablet_ic_menu_back.png
rename from mobile/android/base/resources/drawable-large-xhdpi-v11/new_tablet_ic_menu_forward.png
rename to mobile/android/base/newtablet/res/drawable-large-xhdpi-v11/new_tablet_ic_menu_forward.png
rename from mobile/android/base/resources/drawable-large-xhdpi-v11/new_tablet_ic_menu_reload.png
rename to mobile/android/base/newtablet/res/drawable-large-xhdpi-v11/new_tablet_ic_menu_reload.png
rename from mobile/android/base/resources/drawable-large-xhdpi-v11/new_tablet_menu.png
rename to mobile/android/base/newtablet/res/drawable-large-xhdpi-v11/new_tablet_menu.png
rename from mobile/android/base/resources/drawable-large-xhdpi-v11/new_tablet_tabs_count.png
rename to mobile/android/base/newtablet/res/drawable-large-xhdpi-v11/new_tablet_tabs_count.png
rename from mobile/android/base/resources/drawable-large-xhdpi-v11/new_tablet_tabs_count_foreground.png
rename to mobile/android/base/newtablet/res/drawable-large-xhdpi-v11/new_tablet_tabs_count_foreground.png
rename from mobile/android/base/resources/drawable-large-xxhdpi-v11/new_tablet_default_favicon.png
rename to mobile/android/base/newtablet/res/drawable-large-xxhdpi-v11/new_tablet_default_favicon.png
rename from mobile/android/base/resources/drawable-large-xxhdpi-v11/new_tablet_ic_menu_back.png
rename to mobile/android/base/newtablet/res/drawable-large-xxhdpi-v11/new_tablet_ic_menu_back.png
rename from mobile/android/base/resources/drawable-large-xxhdpi-v11/new_tablet_ic_menu_forward.png
rename to mobile/android/base/newtablet/res/drawable-large-xxhdpi-v11/new_tablet_ic_menu_forward.png
rename from mobile/android/base/resources/drawable-large-xxhdpi-v11/new_tablet_ic_menu_reload.png
rename to mobile/android/base/newtablet/res/drawable-large-xxhdpi-v11/new_tablet_ic_menu_reload.png
rename from mobile/android/base/resources/drawable-large-xxhdpi-v11/new_tablet_menu.png
rename to mobile/android/base/newtablet/res/drawable-large-xxhdpi-v11/new_tablet_menu.png
rename from mobile/android/base/resources/drawable-large-xxhdpi-v11/new_tablet_tabs_count.png
rename to mobile/android/base/newtablet/res/drawable-large-xxhdpi-v11/new_tablet_tabs_count.png
rename from mobile/android/base/resources/drawable-large-xxhdpi-v11/new_tablet_tabs_count_foreground.png
rename to mobile/android/base/newtablet/res/drawable-large-xxhdpi-v11/new_tablet_tabs_count_foreground.png
rename from mobile/android/base/resources/layout-large-v11/new_tablet_browser_toolbar.xml
rename to mobile/android/base/newtablet/res/layout-large-v11/new_tablet_browser_toolbar.xml
rename from mobile/android/base/resources/layout-large-v11/new_tablet_tab_strip.xml
rename to mobile/android/base/newtablet/res/layout-large-v11/new_tablet_tab_strip.xml
rename from mobile/android/base/resources/layout-large-v11/new_tablet_tabs_counter.xml
rename to mobile/android/base/newtablet/res/layout-large-v11/new_tablet_tabs_counter.xml
rename from mobile/android/base/resources/layout-large-v11/tab_strip.xml
rename to mobile/android/base/newtablet/res/layout-large-v11/tab_strip.xml
rename from mobile/android/base/resources/layout-large-v11/tab_strip_item.xml
rename to mobile/android/base/newtablet/res/layout-large-v11/tab_strip_item.xml
rename from mobile/android/base/resources/layout-large-v11/tab_strip_item_view.xml
rename to mobile/android/base/newtablet/res/layout-large-v11/tab_strip_item_view.xml
--- a/mobile/android/base/resources/layout-large-v11/tab_strip_item_view.xml
+++ b/mobile/android/base/newtablet/res/layout-large-v11/tab_strip_item_view.xml
@@ -3,17 +3,17 @@
    - 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/. -->
 
 <merge xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:gecko="http://schemas.android.com/apk/res-auto">
 
    <ImageView
         android:id="@+id/favicon"
-        android:layout_width="@dimen/tab_strip_favicon_size"
+        android:layout_width="@dimen/new_tablet_tab_strip_favicon_size"
         android:layout_height="match_parent"
         android:layout_marginRight="9dp"
         android:scaleType="centerInside"
         android:duplicateParentState="true"/>
 
     <org.mozilla.gecko.widget.FadedTextView
         android:id="@+id/title"
         android:layout_width="0dip"
rename from mobile/android/base/resources/drawable-hdpi-v11/ic_menu_back.png
rename to mobile/android/base/resources/drawable-hdpi/ic_menu_back.png
rename from mobile/android/base/resources/drawable-mdpi-v11/ic_menu_back.png
rename to mobile/android/base/resources/drawable-mdpi/ic_menu_back.png
rename from mobile/android/base/resources/drawable-xhdpi-v11/ic_menu_back.png
rename to mobile/android/base/resources/drawable-xhdpi/ic_menu_back.png
copy from mobile/android/base/resources/values/layout.xml
copy to mobile/android/base/resources/drawable/new_tablet_default_favicon.xml
--- a/mobile/android/base/resources/values/layout.xml
+++ b/mobile/android/base/resources/drawable/new_tablet_default_favicon.xml
@@ -1,8 +1,7 @@
 <?xml version="1.0" encoding="utf-8"?>
 <!-- This Source Code Form is subject to the terms of the Mozilla Public
    - License, v. 2.0. If a copy of the MPL was not distributed with this
    - file, You can obtain one at http://mozilla.org/MPL/2.0/. -->
 
-<resources>
-    <item type="layout" name="tabs_layout_item_view">@layout/tabs_item_row</item>
-</resources>
+<bitmap xmlns:android="http://schemas.android.com/apk/res/android"
+        android:src="@null"/>
copy from mobile/android/base/resources/values/layout.xml
copy to mobile/android/base/resources/drawable/new_tablet_ic_menu_forward.xml
--- a/mobile/android/base/resources/values/layout.xml
+++ b/mobile/android/base/resources/drawable/new_tablet_ic_menu_forward.xml
@@ -1,8 +1,7 @@
 <?xml version="1.0" encoding="utf-8"?>
 <!-- This Source Code Form is subject to the terms of the Mozilla Public
    - License, v. 2.0. If a copy of the MPL was not distributed with this
    - file, You can obtain one at http://mozilla.org/MPL/2.0/. -->
 
-<resources>
-    <item type="layout" name="tabs_layout_item_view">@layout/tabs_item_row</item>
-</resources>
+<bitmap xmlns:android="http://schemas.android.com/apk/res/android"
+        android:src="@null"/>
copy from mobile/android/base/resources/values/layout.xml
copy to mobile/android/base/resources/drawable/new_tablet_ic_menu_reload.xml
--- a/mobile/android/base/resources/values/layout.xml
+++ b/mobile/android/base/resources/drawable/new_tablet_ic_menu_reload.xml
@@ -1,8 +1,7 @@
 <?xml version="1.0" encoding="utf-8"?>
 <!-- This Source Code Form is subject to the terms of the Mozilla Public
    - License, v. 2.0. If a copy of the MPL was not distributed with this
    - file, You can obtain one at http://mozilla.org/MPL/2.0/. -->
 
-<resources>
-    <item type="layout" name="tabs_layout_item_view">@layout/tabs_item_row</item>
-</resources>
+<bitmap xmlns:android="http://schemas.android.com/apk/res/android"
+        android:src="@null"/>
copy from mobile/android/base/resources/values/layout.xml
copy to mobile/android/base/resources/drawable/new_tablet_tabs_count.xml
--- a/mobile/android/base/resources/values/layout.xml
+++ b/mobile/android/base/resources/drawable/new_tablet_tabs_count.xml
@@ -1,8 +1,7 @@
 <?xml version="1.0" encoding="utf-8"?>
 <!-- This Source Code Form is subject to the terms of the Mozilla Public
    - License, v. 2.0. If a copy of the MPL was not distributed with this
    - file, You can obtain one at http://mozilla.org/MPL/2.0/. -->
 
-<resources>
-    <item type="layout" name="tabs_layout_item_view">@layout/tabs_item_row</item>
-</resources>
+<bitmap xmlns:android="http://schemas.android.com/apk/res/android"
+        android:src="@null"/>
deleted file mode 100644
--- a/mobile/android/base/resources/layout-large-land-v11/tabs_panel_footer.xml
+++ /dev/null
@@ -1,28 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!-- This Source Code Form is subject to the terms of the Mozilla Public
-   - License, v. 2.0. If a copy of the MPL was not distributed with this
-   - file, You can obtain one at http://mozilla.org/MPL/2.0/. -->
-
-<merge xmlns:android="http://schemas.android.com/apk/res/android">
-
-    <ImageButton android:id="@+id/add_tab"
-                 android:layout_width="@dimen/browser_toolbar_height"
-                 android:layout_height="@dimen/browser_toolbar_height"
-                 android:padding="14dip"
-                 android:src="@drawable/tab_new_level"
-                 android:contentDescription="@string/new_tab"
-                 android:background="@drawable/action_bar_button_inverse"/>
-
-    <View android:layout_width="0dip"
-          android:layout_height="match_parent"
-          android:layout_weight="1.0"/>
-
-    <ImageButton android:id="@+id/menu"
-                 style="@style/UrlBar.ImageButton"
-                 android:padding="@dimen/browser_toolbar_button_padding"
-                 android:src="@drawable/menu_tabs"
-                 android:contentDescription="@string/menu"
-                 android:background="@drawable/action_bar_button_inverse"
-                 android:visibility="gone"/>
-
-</merge>
deleted file mode 100644
--- a/mobile/android/base/resources/layout-large-land-v11/tabs_panel_header.xml
+++ /dev/null
@@ -1,15 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!-- This Source Code Form is subject to the terms of the Mozilla Public
-   - License, v. 2.0. If a copy of the MPL was not distributed with this
-   - file, You can obtain one at http://mozilla.org/MPL/2.0/. -->
-
-<merge xmlns:android="http://schemas.android.com/apk/res/android">
-
-    <org.mozilla.gecko.widget.IconTabWidget android:id="@+id/tab_widget"
-                                            android:layout_width="wrap_content"
-                                            android:layout_height="match_parent"
-                                            android:tabStripEnabled="false"
-                                            android:divider="@drawable/tab_indicator_divider"
-                                            android:layout="@layout/tabs_panel_indicator"/>
-
-</merge>
rename from mobile/android/base/resources/layout-large-land-v11/tabs_panel.xml
rename to mobile/android/base/resources/layout-large-land-v11/tabs_panel_sidebar.xml
--- a/mobile/android/base/resources/layout-large-land-v11/tabs_panel.xml
+++ b/mobile/android/base/resources/layout-large-land-v11/tabs_panel_sidebar.xml
@@ -10,17 +10,24 @@
                     android:layout_width="match_parent"
                     android:layout_height="@dimen/browser_toolbar_height">
 
         <view class="org.mozilla.gecko.tabs.TabsPanel$TabsPanelToolbar"
               android:layout_width="match_parent"
               android:layout_height="match_parent"
               android:background="@color/background_tabs">
 
-            <include layout="@layout/tabs_panel_header"/>
+
+            <org.mozilla.gecko.widget.IconTabWidget android:id="@+id/tab_widget"
+                                                    android:layout_width="wrap_content"
+                                                    android:layout_height="match_parent"
+                                                    android:tabStripEnabled="false"
+                                                    android:divider="@drawable/tab_indicator_divider"
+                                                    android:layout="@layout/tabs_panel_indicator"/>
+
 
         </view>
 
         <View android:layout_width="match_parent"
               android:layout_height="2dp"
               android:layout_alignParentBottom="true"
               android:background="#1A000000"/>
 
@@ -59,17 +66,35 @@
                     android:layout_width="match_parent"
                     android:layout_height="@dimen/browser_toolbar_height">
 
         <view class="org.mozilla.gecko.tabs.TabsPanel$TabsPanelToolbar"
               android:layout_width="match_parent"
               android:layout_height="match_parent"
               android:background="@color/background_tabs">
 
-            <include layout="@layout/tabs_panel_footer"/>
+            <ImageButton android:id="@+id/add_tab"
+                         android:layout_width="@dimen/browser_toolbar_height"
+                         android:layout_height="@dimen/browser_toolbar_height"
+                         android:padding="14dip"
+                         android:src="@drawable/tab_new_level"
+                         android:contentDescription="@string/new_tab"
+                         android:background="@drawable/action_bar_button_inverse"/>
+
+            <View android:layout_width="0dip"
+                  android:layout_height="match_parent"
+                  android:layout_weight="1.0"/>
+
+            <ImageButton android:id="@+id/menu"
+                         style="@style/UrlBar.ImageButton"
+                         android:padding="@dimen/browser_toolbar_button_padding"
+                         android:src="@drawable/menu_tabs"
+                         android:contentDescription="@string/menu"
+                         android:background="@drawable/action_bar_button_inverse"
+                         android:visibility="gone"/>
 
         </view>
 
         <View android:layout_width="match_parent"
               android:layout_height="2dp"
               android:layout_alignParentTop="true"
               android:background="#1A000000"/>
 
rename from mobile/android/base/resources/layout/tabs_panel.xml
rename to mobile/android/base/resources/layout/tabs_panel_default.xml
--- a/mobile/android/base/resources/layout/tabs_panel.xml
+++ b/mobile/android/base/resources/layout/tabs_panel_default.xml
@@ -10,17 +10,41 @@
                     android:layout_width="match_parent"
                     android:layout_height="@dimen/browser_toolbar_height">
 
         <view class="org.mozilla.gecko.tabs.TabsPanel$TabsPanelToolbar"
               android:layout_width="match_parent"
               android:layout_height="match_parent"
               android:background="@color/background_tabs">
 
-            <include layout="@layout/tabs_panel_header"/>
+            <org.mozilla.gecko.widget.IconTabWidget android:id="@+id/tab_widget"
+                                                    android:layout_width="wrap_content"
+                                                    android:layout_height="match_parent"
+                                                    android:tabStripEnabled="false"
+                                                    android:divider="@drawable/tab_indicator_divider"
+                                                    android:layout="@layout/tabs_panel_indicator"/>
+
+            <View android:layout_width="0dip"
+                  android:layout_height="match_parent"
+                  android:layout_weight="1.0"/>
+
+            <ImageButton android:id="@+id/add_tab"
+                         style="@style/UrlBar.ImageButton"
+                         android:padding="@dimen/browser_toolbar_button_padding"
+                         android:src="@drawable/tab_new_level"
+                         android:contentDescription="@string/new_tab"
+                         android:background="@drawable/action_bar_button_inverse"/>
+
+            <ImageButton android:id="@+id/menu"
+                         style="@style/UrlBar.ImageButton"
+                         android:padding="@dimen/browser_toolbar_button_padding"
+                         android:src="@drawable/menu_tabs"
+                         android:contentDescription="@string/menu"
+                         android:background="@drawable/action_bar_button_inverse"
+                         android:visibility="gone"/>
 
         </view>
 
         <View android:layout_width="match_parent"
               android:layout_height="2dp"
               android:layout_alignParentBottom="true"
               android:background="#1A000000"/>
 
deleted file mode 100644
--- a/mobile/android/base/resources/layout/tabs_panel_header.xml
+++ /dev/null
@@ -1,34 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!-- This Source Code Form is subject to the terms of the Mozilla Public
-   - License, v. 2.0. If a copy of the MPL was not distributed with this
-   - file, You can obtain one at http://mozilla.org/MPL/2.0/. -->
-
-<merge xmlns:android="http://schemas.android.com/apk/res/android">
-
-    <org.mozilla.gecko.widget.IconTabWidget android:id="@+id/tab_widget"
-                                            android:layout_width="wrap_content"
-                                            android:layout_height="match_parent"
-                                            android:tabStripEnabled="false"
-                                            android:divider="@drawable/tab_indicator_divider"
-                                            android:layout="@layout/tabs_panel_indicator"/>
-
-    <View android:layout_width="0dip"
-          android:layout_height="match_parent"
-          android:layout_weight="1.0"/>
-
-    <ImageButton android:id="@+id/add_tab"
-                 style="@style/UrlBar.ImageButton"
-                 android:padding="@dimen/browser_toolbar_button_padding"
-                 android:src="@drawable/tab_new_level"
-                 android:contentDescription="@string/new_tab"
-                 android:background="@drawable/action_bar_button_inverse"/>
-
-    <ImageButton android:id="@+id/menu"
-                 style="@style/UrlBar.ImageButton"
-                 android:padding="@dimen/browser_toolbar_button_padding"
-                 android:src="@drawable/menu_tabs"
-                 android:contentDescription="@string/menu"
-                 android:background="@drawable/action_bar_button_inverse"
-                 android:visibility="gone"/>
-
-</merge>
copy from mobile/android/base/resources/values/layout.xml
copy to mobile/android/base/resources/values-large-land-v11/layout.xml
--- a/mobile/android/base/resources/values/layout.xml
+++ b/mobile/android/base/resources/values-large-land-v11/layout.xml
@@ -1,8 +1,8 @@
 <?xml version="1.0" encoding="utf-8"?>
 <!-- This Source Code Form is subject to the terms of the Mozilla Public
    - License, v. 2.0. If a copy of the MPL was not distributed with this
    - file, You can obtain one at http://mozilla.org/MPL/2.0/. -->
 
 <resources>
-    <item type="layout" name="tabs_layout_item_view">@layout/tabs_item_row</item>
+    <item type="layout" name="tabs_panel">@layout/tabs_panel_sidebar</item>
 </resources>
--- a/mobile/android/base/resources/values-large-v11/dimens.xml
+++ b/mobile/android/base/resources/values-large-v11/dimens.xml
@@ -7,19 +7,12 @@
 
     <dimen name="browser_toolbar_height">56dp</dimen>
     <dimen name="browser_toolbar_button_padding">16dp</dimen>
 
     <!-- If you update one of these values, update the other. -->
     <dimen name="back_button_width">42dp</dimen>
     <dimen name="back_button_width_half">21dp</dimen>
 
-    <dimen name="forward_default_offset">-13dip</dimen>
-    <dimen name="new_tablet_forward_default_offset">-6dp</dimen>
-
-    <dimen name="new_tablet_browser_toolbar_menu_item_padding">19dp</dimen>
-
     <dimen name="tabs_counter_size">26sp</dimen>
     <dimen name="panel_grid_view_column_width">200dp</dimen>
 
-    <dimen name="tab_strip_favicon_size">16dp</dimen>
-
 </resources>
--- a/mobile/android/base/resources/values-large-v11/themes.xml
+++ b/mobile/android/base/resources/values-large-v11/themes.xml
@@ -9,13 +9,14 @@
         Base application theme. This could be overridden by GeckoBaseTheme
         in other res/values-XXX/themes.xml.
     -->
     <style name="GeckoBase" parent="@android:style/Theme.Holo.Light">
         <item name="android:windowContentOverlay">@null</item>
         <item name="android:windowActionBar">false</item>
         <item name="android:windowNoTitle">true</item>
         <item name="arrowPopupWidth">400dp</item>
+        <item name="menuItemActionBarStyleNewTablet">@style/Widget.MenuItemActionBar.NewTablet</item>
     </style>
 
     <style name="GeckoStartPane" parent="Gecko.Dialog"/>
     
 </resources>
--- a/mobile/android/base/resources/values/dimens.xml
+++ b/mobile/android/base/resources/values/dimens.xml
@@ -15,16 +15,20 @@
     <!-- favicon_size includes 4dp of right padding. We can't use margin (which would allow us to
          specify the actual size) because that would decrease the size of our hit target. -->
     <dimen name="browser_toolbar_favicon_size">21.33dip</dimen>
     <dimen name="browser_toolbar_shadow_size">2dp</dimen>
 
     <dimen name="new_tablet_tab_strip_height">48dp</dimen>
     <dimen name="new_tablet_tab_strip_item_width">250dp</dimen>
     <dimen name="new_tablet_tab_strip_item_margin">-30dp</dimen>
+    <dimen name="new_tablet_tab_strip_favicon_size">-30dp</dimen>
+    <dimen name="new_tablet_forward_default_offset">-6dp</dimen>
+    <dimen name="new_tablet_browser_toolbar_menu_item_padding">19dp</dimen>
+    <dimen name="forward_default_offset">-13dip</dimen>
 
     <!-- Dimensions used by Favicons and FaviconView -->
     <dimen name="favicon_size_small">16dp</dimen>
     <dimen name="favicon_size_large">32dp</dimen>
     <dimen name="favicon_bg">32dp</dimen>
     <dimen name="favicon_bg_radius">1dp</dimen>
     <!-- Set the upper limit on the size of favicon that will be processed. Favicons larger than
          this will be downscaled to this value. If you need to use larger Favicons (Due to a UI
--- a/mobile/android/base/resources/values/ids.xml
+++ b/mobile/android/base/resources/values/ids.xml
@@ -2,10 +2,11 @@
 <!-- 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/. -->
 
 <resources>
 
     <item type="id" name="guestNotification"/>
     <item type="id" name="original_height"/>
+    <item type="id" name="menu_items"/>
 
 </resources>
--- a/mobile/android/base/resources/values/layout.xml
+++ b/mobile/android/base/resources/values/layout.xml
@@ -1,8 +1,11 @@
 <?xml version="1.0" encoding="utf-8"?>
 <!-- This Source Code Form is subject to the terms of the Mozilla Public
    - License, v. 2.0. If a copy of the MPL was not distributed with this
    - file, You can obtain one at http://mozilla.org/MPL/2.0/. -->
 
 <resources>
+    <item type="layout" name="tabs_panel">@layout/tabs_panel_default</item>
     <item type="layout" name="tabs_layout_item_view">@layout/tabs_item_row</item>
+    <item type="layout" name="new_tablet_browser_toolbar">@null</item>
+    <item type="layout" name="new_tablet_tab_strip">@null</item>
 </resources>
--- a/mobile/android/base/resources/values/themes.xml
+++ b/mobile/android/base/resources/values/themes.xml
@@ -88,17 +88,16 @@
         <item name="android:spinnerStyle">@style/Widget.Spinner</item>
         <item name="android:windowBackground">@android:color/white</item>
         <item name="bookmarksListViewStyle">@style/Widget.BookmarksListView</item>
         <item name="floatingHintEditTextStyle">@style/FloatingHintEditText</item>
         <item name="tabGridLayoutViewStyle">@style/Widget.TabsGridLayout</item>
         <item name="geckoMenuListViewStyle">@style/Widget.GeckoMenuListView</item>
         <item name="homeListViewStyle">@style/Widget.HomeListView</item>
         <item name="menuItemActionBarStyle">@style/Widget.MenuItemActionBar</item>
-        <item name="menuItemActionBarStyleNewTablet">@style/Widget.MenuItemActionBar.NewTablet</item>
         <item name="menuItemActionModeStyle">@style/GeckoActionBar.Button</item>
         <item name="menuItemShareActionButtonStyle">@style/Widget.MenuItemSecondaryActionBar</item>
         <item name="panelGridViewStyle">@style/Widget.PanelGridView</item>
         <item name="topSitesGridItemViewStyle">@style/Widget.TopSitesGridItemView</item>
         <item name="topSitesGridViewStyle">@style/Widget.TopSitesGridView</item>
         <item name="topSitesThumbnailViewStyle">@style/Widget.TopSitesThumbnailView</item>
     </style>
 
--- a/mobile/android/base/tabs/TabStripItemView.java
+++ b/mobile/android/base/tabs/TabStripItemView.java
@@ -64,17 +64,17 @@ public class TabStripItemView extends Th
         tabClipRegion = new Region();
 
         tabPaint = new Paint();
         tabPaint.setAntiAlias(true);
         tabPaint.setColor(0xFFFF0000);
         tabPaint.setStrokeWidth(0.0f);
         tabPaint.setXfermode(new PorterDuffXfermode(Mode.DST_IN));
 
-        faviconSize = getResources().getDimensionPixelSize(R.dimen.tab_strip_favicon_size);
+        faviconSize = getResources().getDimensionPixelSize(R.dimen.new_tablet_tab_strip_favicon_size);
 
         LayoutInflater.from(context).inflate(R.layout.tab_strip_item_view, this);
         setOnClickListener(new View.OnClickListener() {
             @Override
             public void onClick(View v) {
                 if (id < 0) {
                     throw new IllegalStateException("Invalid tab id:" + id);
                 }
--- a/mobile/android/base/tabs/TabsPanel.java
+++ b/mobile/android/base/tabs/TabsPanel.java
@@ -114,17 +114,17 @@ public class TabsPanel extends LinearLay
         setOrientation(LinearLayout.VERTICAL);
 
         mCurrentPanel = Panel.NORMAL_TABS;
 
         mPopupMenu = new GeckoPopupMenu(context);
         mPopupMenu.inflate(R.menu.tabs_menu);
         mPopupMenu.setOnMenuItemClickListener(this);
 
-        LayoutInflater.from(context).inflate(R.layout.tabs_panel, this);
+        inflateLayout(context);
         initialize();
 
         mAppStateListener = new AppStateListener() {
             @Override
             public void onResume() {
                 if (mPanel == mPanelRemote) {
                     // Refresh the remote panel.
                     mPanelRemote.show();
@@ -136,16 +136,25 @@ public class TabsPanel extends LinearLay
                 // Remote panel is already refreshed by chrome refresh.
             }
 
             @Override
             public void onPause() {}
         };
     }
 
+
+    private void inflateLayout(Context context) {
+        if (NewTabletUI.isEnabled(context)) {
+            LayoutInflater.from(context).inflate(R.layout.tabs_panel_default, this);
+        } else {
+            LayoutInflater.from(context).inflate(R.layout.tabs_panel, this);
+        }
+    }
+
     private void initialize() {
         mHeader = (RelativeLayout) findViewById(R.id.tabs_panel_header);
         mPanelsContainer = (PanelViewContainer) findViewById(R.id.tabs_container);
 
         mPanelNormal = (PanelView) findViewById(R.id.normal_tabs);
         mPanelNormal.setTabsPanel(this);
 
         mPanelPrivate = (PanelView) findViewById(R.id.private_tabs_panel);
--- a/mobile/android/confvars.sh
+++ b/mobile/android/confvars.sh
@@ -76,16 +76,22 @@ MOZ_WEBGL_CONFORMANT=1
 
 # Enable the Search Activity in nightly.
 if test "$NIGHTLY_BUILD"; then
   MOZ_ANDROID_SEARCH_ACTIVITY=1
 else
   MOZ_ANDROID_SEARCH_ACTIVITY=
 fi
 
+# Enable the new tablet UI in pre-release builds
+# if the max Android sdk is undefined or at least 11.
+if test ! "$RELEASE_BUILD"; then
+  MOZ_ANDROID_NEW_TABLET_UI=1
+fi
+
 # Enable the share handler in pre-release builds.
 if test ! "$RELEASE_BUILD"; then
   MOZ_ANDROID_SHARE_OVERLAY=1
 fi
 
 # Enable the Mozilla Location Service stumbler in Nightly.
 if test "$NIGHTLY_BUILD"; then
   MOZ_ANDROID_MLS_STUMBLER=1
--- a/netwerk/base/src/nsIOService.cpp
+++ b/netwerk/base/src/nsIOService.cpp
@@ -590,17 +590,18 @@ nsIOService::NewChannelFromURIWithProxyF
     if (NS_FAILED(rv))
         return rv;
 
     nsCOMPtr<nsIProxiedProtocolHandler> pph = do_QueryInterface(handler);
     if (pph)
         rv = pph->NewProxiedChannel(aURI, nullptr, aProxyFlags, aProxyURI, result);
     else
         rv = handler->NewChannel(aURI, result);
-    NS_ENSURE_SUCCESS(rv, rv);
+    if (NS_FAILED(rv))
+        return rv;
 
     // Some extensions override the http protocol handler and provide their own
     // implementation. The channels returned from that implementation doesn't
     // seem to always implement the nsIUploadChannel2 interface, presumably
     // because it's a new interface.
     // Eventually we should remove this and simply require that http channels
     // implement the new interface.
     // See bug 529041
--- a/services/sync/modules/engines.js
+++ b/services/sync/modules/engines.js
@@ -478,17 +478,19 @@ EngineManager.prototype = {
   getAll: function () {
     return [engine for ([name, engine] in Iterator(this._engines))];
   },
 
   /**
    * N.B., does not pay attention to the declined list.
    */
   getEnabled: function () {
-    return this.getAll().filter(function(engine) engine.enabled);
+    return this.getAll()
+               .filter((engine) => engine.enabled)
+               .sort((a, b) => a.syncPriority - b.syncPriority);
   },
 
   get enabledEngineNames() {
     return [e.name for each (e in this.getEnabled())];
   },
 
   persistDeclined: function () {
     Svc.Prefs.set("declinedEngines", [...this._declined].join(","));
@@ -695,16 +697,23 @@ SyncEngine.kRecoveryStrategy = {
   error:  "error"
 };
 
 SyncEngine.prototype = {
   __proto__: Engine.prototype,
   _recordObj: CryptoWrapper,
   version: 1,
 
+  // A relative priority to use when computing an order
+  // for engines to be synced. Higher-priority engines
+  // (lower numbers) are synced first.
+  // It is recommended that a unique value be used for each engine,
+  // in order to guarantee a stable sequence.
+  syncPriority: 0,
+
   // How many records to pull in a single sync. This is primarily to avoid very
   // long first syncs against profiles with many history records.
   downloadLimit: null,
 
   // How many records to pull at one time when specifying IDs. This is to avoid
   // URI length limitations.
   guidFetchBatchSize: DEFAULT_GUID_FETCH_BATCH_SIZE,
   mobileGUIDFetchBatchSize: DEFAULT_MOBILE_GUID_FETCH_BATCH_SIZE,
--- a/services/sync/modules/engines/addons.js
+++ b/services/sync/modules/engines/addons.js
@@ -114,16 +114,18 @@ this.AddonsEngine = function AddonsEngin
 }
 AddonsEngine.prototype = {
   __proto__:              SyncEngine.prototype,
   _storeObj:              AddonsStore,
   _trackerObj:            AddonsTracker,
   _recordObj:             AddonRecord,
   version:                1,
 
+  syncPriority:           5,
+
   _reconciler:            null,
 
   /**
    * Override parent method to find add-ons by their public ID, not Sync GUID.
    */
   _findDupe: function _findDupe(item) {
     let id = item.addonID;
 
--- a/services/sync/modules/engines/bookmarks.js
+++ b/services/sync/modules/engines/bookmarks.js
@@ -198,16 +198,18 @@ this.BookmarksEngine = function Bookmark
 }
 BookmarksEngine.prototype = {
   __proto__: SyncEngine.prototype,
   _recordObj: PlacesItem,
   _storeObj: BookmarksStore,
   _trackerObj: BookmarksTracker,
   version: 2,
 
+  syncPriority: 4,
+
   _sync: function _sync() {
     let engine = this;
     let batchEx = null;
 
     // Try running sync in batch mode
     PlacesUtils.bookmarks.runInBatchMode({
       runBatched: function wrappedSync() {
         try {
--- a/services/sync/modules/engines/forms.js
+++ b/services/sync/modules/engines/forms.js
@@ -102,16 +102,18 @@ this.FormEngine = function FormEngine(se
 }
 FormEngine.prototype = {
   __proto__: SyncEngine.prototype,
   _storeObj: FormStore,
   _trackerObj: FormTracker,
   _recordObj: FormRec,
   applyIncomingBatchSize: FORMS_STORE_BATCH_SIZE,
 
+  syncPriority: 6,
+
   get prefName() "history",
 
   _findDupe: function _findDupe(item) {
     return FormWrapper.getGUID(item.name, item.value);
   }
 };
 
 function FormStore(name, engine) {
--- a/services/sync/modules/engines/history.js
+++ b/services/sync/modules/engines/history.js
@@ -36,17 +36,19 @@ this.HistoryEngine = function HistoryEng
   SyncEngine.call(this, "History", service);
 }
 HistoryEngine.prototype = {
   __proto__: SyncEngine.prototype,
   _recordObj: HistoryRec,
   _storeObj: HistoryStore,
   _trackerObj: HistoryTracker,
   downloadLimit: MAX_HISTORY_DOWNLOAD,
-  applyIncomingBatchSize: HISTORY_STORE_BATCH_SIZE
+  applyIncomingBatchSize: HISTORY_STORE_BATCH_SIZE,
+
+  syncPriority: 7,
 };
 
 function HistoryStore(name, engine) {
   Store.call(this, name, engine);
 
   // Explicitly nullify our references to our cached services so we don't leak
   Svc.Obs.add("places-shutdown", function() {
     for each ([query, stmt] in Iterator(this._stmts)) {
--- a/services/sync/modules/engines/passwords.js
+++ b/services/sync/modules/engines/passwords.js
@@ -31,16 +31,18 @@ this.PasswordEngine = function PasswordE
 }
 PasswordEngine.prototype = {
   __proto__: SyncEngine.prototype,
   _storeObj: PasswordStore,
   _trackerObj: PasswordTracker,
   _recordObj: LoginRec,
   applyIncomingBatchSize: PASSWORDS_STORE_BATCH_SIZE,
 
+  syncPriority: 2,
+
   _syncFinish: function _syncFinish() {
     SyncEngine.prototype._syncFinish.call(this);
 
     // Delete the weave credentials from the server once
     if (!Svc.Prefs.get("deletePwdFxA", false)) {
       try {
         let ids = [];
         for (let host of Utils.getSyncCredentialsHosts()) {
--- a/services/sync/modules/engines/prefs.js
+++ b/services/sync/modules/engines/prefs.js
@@ -36,16 +36,18 @@ this.PrefsEngine = function PrefsEngine(
 }
 PrefsEngine.prototype = {
   __proto__: SyncEngine.prototype,
   _storeObj: PrefStore,
   _trackerObj: PrefTracker,
   _recordObj: PrefRec,
   version: 2,
 
+  syncPriority: 1,
+
   getChangedIDs: function getChangedIDs() {
     // No need for a proper timestamp (no conflict resolution needed).
     let changedIDs = {};
     if (this._tracker.modified)
       changedIDs[PREFS_GUID] = 0;
     return changedIDs;
   },
 
--- a/services/sync/modules/engines/tabs.js
+++ b/services/sync/modules/engines/tabs.js
@@ -40,16 +40,18 @@ this.TabEngine = function TabEngine(serv
   this._resetClient();
 }
 TabEngine.prototype = {
   __proto__: SyncEngine.prototype,
   _storeObj: TabStore,
   _trackerObj: TabTracker,
   _recordObj: TabSetRecord,
 
+  syncPriority: 3,
+
   getChangedIDs: function getChangedIDs() {
     // No need for a proper timestamp (no conflict resolution needed).
     let changedIDs = {};
     if (this._tracker.modified)
       changedIDs[this.service.clientsEngine.localID] = 0;
     return changedIDs;
   },
 
--- a/services/sync/tests/unit/head_helpers.js
+++ b/services/sync/tests/unit/head_helpers.js
@@ -187,8 +187,16 @@ function mockGetWindowEnumerator(url, nu
     hasMoreElements: function () {
       return elements.length;
     },
     getNext: function () {
       return elements.shift();
     },
   };
 }
+
+// Helper that allows checking array equality.
+function do_check_array_eq(a1, a2) {
+  do_check_eq(a1.length, a2.length);
+  for (let i = 0; i < a1.length; ++i) {
+    do_check_eq(a1[i], a2[i]);
+  }
+}
--- a/services/sync/tests/unit/test_enginemanager.js
+++ b/services/sync/tests/unit/test_enginemanager.js
@@ -70,16 +70,33 @@ add_test(function test_basics() {
   do_check_eq(engines.length, 1);
   do_check_eq(engines[0], petrol);
 
   dummy.enabled = true;
   diesel.enabled = true;
   engines = manager.getEnabled();
   do_check_eq(engines.length, 3);
 
+  _("getEnabled() returns enabled engines in sorted order");
+  petrol.syncPriority = 1;
+  dummy.syncPriority = 2;
+  diesel.syncPriority = 3;
+
+  engines = manager.getEnabled();
+
+  do_check_array_eq(engines, [petrol, dummy, diesel]);
+
+  _("Changing the priorities should change the order in getEnabled()");
+
+  dummy.syncPriority = 4;
+
+  engines = manager.getEnabled();
+
+  do_check_array_eq(engines, [petrol, diesel, dummy]);
+
   _("Unregister an engine by name");
   manager.unregister('dummy');
   do_check_eq(manager.get('dummy'), undefined);
   engines = manager.getAll();
   do_check_eq(engines.length, 2);
   do_check_eq(engines.indexOf(dummy), -1);
 
   _("Unregister an engine by value");
--- a/services/sync/tests/unit/test_keys.js
+++ b/services/sync/tests/unit/test_keys.js
@@ -9,23 +9,16 @@ Cu.import("resource://services-sync/util
 
 let collectionKeys = new CollectionKeyManager();
 
 function sha256HMAC(message, key) {
   let h = Utils.makeHMACHasher(Ci.nsICryptoHMAC.SHA256, key);
   return Utils.digestBytes(message, h);
 }
 
-function do_check_array_eq(a1, a2) {
-  do_check_eq(a1.length, a2.length);
-  for (let i = 0; i < a1.length; ++i) {
-    do_check_eq(a1[i], a2[i]);
-  }
-}
-
 function do_check_keypair_eq(a, b) {
   do_check_eq(2, a.length);
   do_check_eq(2, b.length);
   do_check_eq(a[0], b[0]);
   do_check_eq(a[1], b[1]);
 }
 
 function test_time_keyFromString(iterations) {
--- a/toolkit/content/widgets/toolbarbutton.xml
+++ b/toolkit/content/widgets/toolbarbutton.xml
@@ -9,41 +9,41 @@
    xmlns:xul="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"
    xmlns:xbl="http://www.mozilla.org/xbl">
 
   <binding id="toolbarbutton" display="xul:button" role="xul:toolbarbutton"
            extends="chrome://global/content/bindings/button.xml#button-base">
     <resources>
       <stylesheet src="chrome://global/skin/toolbarbutton.css"/>
     </resources>
-    
+
     <content>
       <children includes="observes|template|menupopup|panel|tooltip"/>
       <xul:image class="toolbarbutton-icon" xbl:inherits="validate,src=image,label,consumeanchor"/>
       <xul:label class="toolbarbutton-text" crop="right" flex="1"
                  xbl:inherits="value=label,accesskey,crop,wrap"/>
       <xul:label class="toolbarbutton-multiline-text" flex="1"
                  xbl:inherits="xbl:text=label,accesskey,wrap"/>
     </content>
   </binding>
 
-  <binding id="menu" display="xul:menu" 
+  <binding id="menu" display="xul:menu"
            extends="chrome://global/content/bindings/toolbarbutton.xml#toolbarbutton">
     <content>
       <children includes="observes|template|menupopup|panel|tooltip"/>
       <xul:image class="toolbarbutton-icon" xbl:inherits="validate,src=image,label,type,consumeanchor"/>
       <xul:label class="toolbarbutton-text" crop="right" flex="1"
                  xbl:inherits="value=label,accesskey,crop,dragover-top,wrap"/>
       <xul:label class="toolbarbutton-multiline-text" flex="1"
                  xbl:inherits="xbl:text=label,accesskey,wrap"/>
       <xul:dropmarker anonid="dropmarker" type="menu"
                       class="toolbarbutton-menu-dropmarker" xbl:inherits="disabled,label"/>
     </content>
   </binding>
-  
+
   <binding id="menu-vertical" display="xul:menu"
            extends="chrome://global/content/bindings/toolbarbutton.xml#toolbarbutton">
     <content>
       <children includes="observes|template|menupopup|panel|tooltip"/>
       <xul:hbox flex="1" align="center">
         <xul:vbox flex="1" align="center">
           <xul:image class="toolbarbutton-icon" xbl:inherits="validate,src=image,label,consumeanchor"/>
           <xul:label class="toolbarbutton-text" crop="right" flex="1"
@@ -51,18 +51,18 @@
           <xul:label class="toolbarbutton-multiline-text" flex="1"
                      xbl:inherits="xbl:text=label,accesskey,wrap"/>
         </xul:vbox>
         <xul:dropmarker anonid="dropmarker" type="menu"
                         class="toolbarbutton-menu-dropmarker" xbl:inherits="disabled,label"/>
       </xul:hbox>
     </content>
   </binding>
-  
-  <binding id="menu-button" display="xul:menu" 
+
+  <binding id="menu-button" display="xul:menu"
            extends="chrome://global/content/bindings/button.xml#menu-button-base">
     <resources>
       <stylesheet src="chrome://global/skin/toolbarbutton.css"/>
     </resources>
 
     <content>
       <children includes="observes|template|menupopup|panel|tooltip"/>
       <xul:toolbarbutton class="box-inherit toolbarbutton-menubutton-button"
@@ -75,9 +75,24 @@
   </binding>
 
   <binding id="toolbarbutton-image"
            extends="chrome://global/content/bindings/toolbarbutton.xml#toolbarbutton">
     <content>
       <xul:image class="toolbarbutton-icon" xbl:inherits="src=image"/>
     </content>
   </binding>
+
+  <binding id="toolbarbutton-badged"
+           extends="chrome://global/content/bindings/toolbarbutton.xml#toolbarbutton">
+    <content>
+      <children includes="observes|template|menupopup|panel|tooltip"/>
+      <xul:hbox class="toolbarbutton-badge-container" align="start" pack="end">
+        <xul:hbox class="toolbarbutton-badge" xbl:inherits="badge"/>
+        <xul:image class="toolbarbutton-icon" xbl:inherits="validate,src=image,label"/>
+      </xul:hbox>
+      <xul:label class="toolbarbutton-text" crop="right" flex="1"
+                 xbl:inherits="value=label,accesskey,crop,wrap"/>
+      <xul:label class="toolbarbutton-multiline-text" flex="1"
+                 xbl:inherits="xbl:text=label,accesskey,wrap"/>
+    </content>
+  </binding>
 </bindings>
--- a/toolkit/content/xul.css
+++ b/toolkit/content/xul.css
@@ -133,16 +133,24 @@ toolbarbutton[type="menu"],
 toolbarbutton[type="panel"] {
   -moz-binding: url("chrome://global/content/bindings/toolbarbutton.xml#menu");
 }
 
 toolbarbutton[type="menu-button"] {
   -moz-binding: url("chrome://global/content/bindings/toolbarbutton.xml#menu-button");
 }
 
+toolbarbutton.badged-button {
+  -moz-binding: url("chrome://global/content/bindings/toolbarbutton.xml#toolbarbutton-badged");
+}
+
+toolbarbutton.badged-button .toolbarbutton-badge[badge]:not([badge=""])::after {
+  content: attr(badge);
+}
+
 toolbar[mode="icons"] .toolbarbutton-text,
 toolbar[mode="icons"] .toolbarbutton-multiline-text,
 toolbar[mode="text"] .toolbarbutton-icon {
   display: none;
 }
 
 .toolbarbutton-multiline-text:not([wrap="true"]),
 .toolbarbutton-text[wrap="true"] {
new file mode 100644
--- /dev/null
+++ b/toolkit/devtools/server/docs/protocol.js.md
@@ -0,0 +1,546 @@
+Writing an Actor
+================
+
+A Simple Hello World
+--------------------
+
+Here's a simple Hello World actor.  It is a global actor (not associated with a given browser tab).
+
+    let protocol = require("devtools/server/protocol");
+    let {method, Arg, Option, RetVal} = protocol;
+
+    // This will be called by the framework when you call DebuggerServer.
+    // registerModule(), and adds the actor as a 'helloActor' property
+    // on the root actor.
+    exports.register = function(handle) {
+        handle.addGlobalActor(HelloActor, "helloActor");
+    }
+
+    // This will be called by the framework during shutdown/unload.
+    exports.unregister = function(handle) {
+        handle.removeGlobalActor(HelloActor); // This is optional, all registered actors will be removed automatically
+    }
+
+    // Create the hello actor.  This uses addon-sdk's heritage module
+    // behind the scenes in case you want to understand the class stuff
+    // a bit better.
+
+    let HelloActor = protocol.ActorClass({
+        typeName: "helloWorld", // I'll explain types later, I promise.
+        initialize: function(conn) {
+            protocol.Actor.prototype.initialize.call(this, conn); // This is the worst part of heritage.
+        },
+
+        sayHello: method(function() {
+           return "hello";
+        }, {
+          // The request packet template.  There are no arguments, so
+          // it is empty.  The framework will add the "type" and "to"
+          // request properties.
+          request: {},
+
+          // The response packet template.  The return value of the function
+          // will be plugged in where the RetVal() appears in the template.
+          response: {
+            greeting: RetVal("string") // "string" is the return value type.
+          }
+        }
+    });
+
+This actor now supports a `sayHello` request.  A request/reply will look like this:
+
+    -> { to: <actorID>, type: "sayHello" }
+    <- { from: <actorID>, greeting: "hello" }
+
+Now we can create a client side object.  We call these *front* objects.
+
+Here's the front for the HelloActor:
+
+    let HelloFront = protocol.FrontClass(HelloActor, {
+      initialize: function(client, form) {
+        protocol.Front.prototype.initialize.call(this, client, form);
+      }
+    });
+
+Note that there is no `sayHello` method.  The FrontClass will generate a method on the Front object that matches the method declaration in the Actor class.
+
+The generated methods will return a Promise.  That promise will resolve to the RetVal of the actor method.
+
+So if we have a reference to a HelloFront object, we can issue a `sayHello` request:
+
+  hello.sayHello().then(greeting => {
+    console.log(greeting);
+  });
+
+How do you get an initial reference to the front?  That's a bit tricky, but basically there are two ways:
+
+* Manually
+* Magically
+
+Manually - If you're using a DebuggerClient instance, you can discover the actorID manually and create a Front for it:
+  let hello = HelloFront(this.client, { actorID: <hello actorID> });
+
+Magically - Once you have an initial reference to a protocol.js object, it can return other protocol.js objects and fronts will automatically be created.
+
+Arguments
+---------
+
+`sayHello` has no arguments, so let's add a method that does take arguments:
+
+    echo: method(function(str) {
+        return str + "... " + str + "...";
+    }, {
+      request: { echo: Arg(0, "string") },
+      response: { echoed: RetVal("string") }
+    })
+
+This tells the library to place the 0th argument, which should be a string, in the `echo` property of the request packet.
+
+
+This will generate a request handler whose request and response packets look like this:
+
+    { to: <actorID>, type: "echo", echo: <str> }
+    { from: <actorID>, echoed: <str> }
+
+The client usage should be predictable:
+
+    echo.echo("hello").then(str => { assert(str === "hello... hello...") })
+
+The library tries hard to make using fronts feel like natural javascript (or as natural as you believe promises are, I guess).  When building the response it will put the return value of the function where RetVal() is specified in the response template, and on the client side it will use the value in that position when resolving the promise.
+
+Returning JSON
+--------------
+
+Maybe your response is an object:
+
+    addOneTwice: method(function(a, b) {
+        return { a: a + 1, b: b + 1 };
+    }, {
+        request: { a: Arg(0, "number"), b: Arg(1, "number") },
+        response: { ret: RetVal("json") }
+    });
+
+This will generate a response packet that looks like:
+
+    { from: <actorID>, ret: { a: <number>, b: <number> } }
+
+That's probably unnecessary nesting (if you're sure you won't be returning an object with 'from' as a key!), so you can just replace `response` with:
+
+    response: RetVal("json")
+
+and now your packet will look like:
+
+    { from: <actorID>, a: <number>, b: <number> }
+
+Types and Marshalling
+---------------------
+
+Things have been pretty simple up to this point - all the arguments we've passed in have been javascript primitives.  But for some types (most importantly Actor types, which I'll get to eventually), we can't just copy them into a JSON packet and expect it to work, we need to marshal things ourselves.
+
+Again, the protocol lib tries hard to provide a natural API to actors and clients, and sometime that natural API might involve object APIs. I'm going to use a wickedly contrived example, bear with me.  Let's say I have a small object that contains a number and has a few methods associated with it:
+
+    let Incrementor = function(i) {
+      this.value = value;
+    }
+    Incrementor.prototype = {
+        increment: function() { this.value++ },
+        decrement: function() { this.value-- }
+    };
+
+
+and I want to return it from a backend function:
+
+    getIncrementor: method(function(i) {
+        return new Incrementor(i)
+    }, {
+        request: { number: Arg(0, "number") },
+        response: { value: RetVal("incrementor") } // We'll define "incrementor" below.
+    });
+
+I want that response to look like `{ from: <actorID>, value: <number> }`, but the client side needs to know to return an Incrementor, not a primitive number.  So let's tell the protocol lib about Incrementors:
+
+    protocol.types.addType("incrementor", {
+        // When writing to a protocol packet, just send the value
+        write: (v) => v.value,
+
+        // When reading from a protocol packet, wrap with an Incrementor
+        // object.
+        read: (v) => new Incrementor(v)
+    });
+
+And now our client can use the API as expected:
+
+    front.getIncrementor(5).then(incrementor => {
+        incrementor.increment();
+        assert(incrementor.value === 6);
+    });
+
+You can do the same thing with arguments:
+
+    passIncrementor: method(function(inc) {
+        w.increment();
+        assert(incrementor.value === 6);
+    }, {
+        request: { Arg(0, "incrementor") },
+    });
+
+    front.passIncrementor(new Incrementor(5));
+
+The library provides primitiive `boolean`, `number`, `string`, and `json` types.
+
+Moving right along, let's say you want to pass/return an array of Incrementors.  You can just prepend `array:` to the type name:
+
+    incrementAll: method(function(incrementors) {
+        incrementors.forEach(incrementor => {
+          incrementor.increment();
+        }
+        return incrementors;
+    }, {
+        request: { incrementors: Arg(0, "array:incrementor") },
+        response: { incrementors: RetVal("array:incrementor") }
+    })
+
+Or maybe you want to return a dictionary where one item is a incrementor.  To do this you need to tell the type system which members of the dictionary need custom marshallers:
+
+    protocol.types.addDictType("contrivedObject", {
+        incrementor: "incrementor",
+        incrementorArray: "array:incrementor"
+    });
+
+    reallyContrivedExample: method(function() {
+        return {
+            /* a and b are primitives and so don't need to be called out specifically in addDictType */
+            a: "hello", b: "world",
+            incrementor: new Incrementor(1), incrementorArray: [new Incrementor(2), new Incrementor(3)]
+        }
+    }, {
+        response: RetVal("contrivedObject")
+    });
+
+    front.reallyContrivedExample().then(obj => {
+        assert(obj.a == "hello");
+        assert(obj.b == "world");
+        assert(incrementor.i == 1);
+        assert(incrementorArray[0].i == 2);
+        assert(incrementorArray[1].i == 3);
+    });
+
+Nullables
+---------
+
+If an argument, return value, or dict property can be null/undefined, you can prepend `nullable:` to the type name:
+
+    "nullable:incrementor",  // Can be null/undefined or an incrementor
+    "array:nullable:incrementor", // An array of incrementors that can have holes.
+    "nullable:array:incrementor" // Either null/undefined or an array of incrementors without holes.
+
+
+Actors
+------
+
+Probably the most common objects that need custom martialing are actors themselves.  These are more interesting than the Incrementor object, but by default they're somewhat easy to work with.  Let's add a ChildActor implementation that will be returned by the HelloActor (which is rapidly becoming the OverwhelminglyComplexActor):
+
+    let ChildActor = protocol.ActorClass({
+        actorType: "childActor",
+        initialize: function(conn, id) {
+            protocol.Actor.prototype.initialize.call(this, conn);
+            this.greeting = "hello from " + id;
+        },
+        getGreeting: method(function() {
+            return this.greeting;
+        }, {
+            response: { greeting: RetVal("string") },
+        }
+    });
+
+    let ChildFront = protocol.FrontClass(ChildActor, {
+        initialize: function(client, form) {
+            protocol.Front.prototype.initialize.call(this, client, form);
+        },
+    });
+
+The library will register a marshaller for the actor type itself, using typeName as its tag.
+
+So we can now add the following code to HelloActor:
+
+    getChild: method(function(id) {
+        return ChildActor(this.conn, id);
+    }, {
+        request: { id: Arg(0, "string") },
+        response: { child: RetVal("childActor") }
+    });
+
+    front.getChild("child1").then(childFront => {
+        return childFront.getGreeting();
+    }).then(greeting => {
+        assert(id === "hello from child1");
+    });
+
+The conversation will look like this:
+
+    { to: <actorID>, type: "getChild", id: "child1" }
+    { from: <actorID>, child: { actor: <childActorID> }}
+    { to: <childActorID>, type: "getGreeting" }
+    { from: <childActorID>, greeting: "hello from child1" }
+
+But the ID is the only interesting part of this made-up example.  You're never going to want a reference to a ChildActor without checking its ID.  Making an extra request just to get that id is wasteful.  You really want the first response to look like `{ from: <actorID>, child: { actor: <childActorID>, greeting: "hello from child1" } }`
+
+You can customize the marshalling of an actor by providing a `form` method in the `ChildActor` class:
+
+    form: function() {
+        return {
+            actor: this.actorID,
+            greeting: this.greeting
+        }
+    },
+
+And you can demarshal in the `ChildFront` class by implementing a matching `form` method:
+
+    form: function(form) {
+        this.actorID = form.actor;
+        this.greeting = form.greeting;
+    }
+
+Now you can use the id immediately:
+
+    front.getChild("child1").then(child => { assert(child.greeting === "child1) });
+
+You may come across a situation where you want to customize the output of a `form` method depending on the operation being performed.  For example, imagine that ChildActor is a bit more complex, with a, b, c, and d members:
+
+    ChildActor:
+        form: function() {
+            return {
+                actor: this.actorID,
+                greeting: this.greeting,
+                a: this.a,
+                b: this.b,
+                c: this.c,
+                d: this.d
+            }
+        }
+    ChildFront:
+        form: function(form) {
+            this.actorID = form.actorID;
+            this.id = form.id;
+            this.a = form.a;
+            this.b = form.b;
+            this.c = form.c;
+            this.d = form.d;
+        }
+
+And imagine you want to change 'c' and return the object:
+
+    // Oops!  If a type is going to return references to itself or any other
+    // type that isn't fully registered yet, you need to predeclare the type.
+    types.addActorType("childActor");
+
+    ...
+
+    changeC: method(function(newC) {
+        c = newC;
+        return this;
+    }, {
+        request: { newC: Arg(0) },
+        response: { self: RetVal("childActor") }
+    });
+
+    ...
+
+    childFront.changeC('hello').then(ret => { assert(ret === childFront); assert(childFront.c === "hello") });
+
+Now our response will look like:
+
+    { from: <childActorID>, self: { actor: <childActorID>, greeting: <id>, a: <a>, b: <b>, c: "hello", d: <d> }
+
+But that's wasteful.  Only c changed.  So we can provide a *detail* to the type using `#`:
+
+    response: { self: RetVal("childActor#changec") }
+
+and update our form methods to make use of that data:
+
+    ChildActor:
+    form: function(detail) {
+        if (detail === "changec") {
+            return { actor: this.actorID, c: this.c }
+        }
+        ... // the rest of the form method stays the same.
+    }
+
+    ChildFront:
+    form: function(form, detail) {
+        if (detail === "changec") {
+            this.actorID = form.actor;
+            this.c = form.c;
+            return;
+        }
+        ... // the rest of the form method stays the same.
+    }
+
+Now the packet looks like a much more reasonable `{ from: <childActorID>, self: { actor: <childActorID>, c: "hello" } }`
+
+Lifetimes
+---------
+
+No, I don't want to talk about lifetimes quite yet.
+
+Events
+------
+
+Your actor has great news!
+
+Actors are subclasses of jetpack `EventTarget`, so you can just emit:
+
+    let event = require("sdk/core/event");
+
+    giveGoodNews: method(function(news) {
+        event.emit(this, "good-news", news);
+    }, {
+        request: { news: Arg(0) }
+    });
+
+... but nobody will really care, because that's not going over the protocol.  But you can describe the packet in an `events` member, the same way you would specify a request:
+
+    events: {
+        "good-news": {
+            type: "goodNews", // event target naming and packet naming are at odds, and we want both to be natural!
+            news: Arg(0)
+        }
+    }
+
+And now you can listen to events on a front:
+
+    front.on("good-news", news => {
+        console.log("Got good news: " + news + "\n");
+    });
+    front.giveGoodNews().then(() => { console.log("request returned.") });
+
+You might want to update your front's state when an event is fired, before emitting it against the front.  You can use `preEvent` in the front definition for that:
+
+    countGoodNews: protocol.preEvent("good-news", function(news) {
+        this.amountOfGoodNews++;
+    });
+
+On a somewhat related note, not every method needs to be request/response.  Just like an actor can emit a one-way event, a method can be marked as a one-way request.  Maybe we don't care about giveGoodNews returning anything:
+
+    giveGoodNews: method(function(news) {
+        emit(this, "good-news", news);
+    }, {
+        request: { news: Arg(0, "string") },
+        oneway: true
+    });
+
+Lifetimes
+---------
+
+No, let's talk about custom front methods instead.
+
+Custom Front Methods
+--------------------
+
+You might have some bookkeeping to do before issuing a request.  Let's say you're calling `echo`, but you want to count the number of times you issue that request.  Just use the `custom` tag in your front implementation:
+
+    echo: custom(function(str) {
+        this.numEchos++;
+        return this._echo(str);
+    }, {
+        impl: "_echo"
+    })
+
+This puts the generated implementation in `_echo` instead of `echo`, letting you implement `echo` as needed.  If you leave out the `impl`, it just won't generate the implementation at all.  You're on your own.
+
+Lifetimes
+---------
+
+OK, I can't think of any more ways to put this off.  The remote debugging protocol has the concept of a *parent* for each actor.  This is to make distributed memory management a bit easier.  Basically, any descendents of an actor will be destroyed if the actor is destroyed.
+
+Other than that, the basic protocol makes no guarantees about lifetime.  Each interface defined in the protocol will need to discuss and document its approach to lifetime management (although there are a few common patterns).
+
+The protocol library will maintain the child/parent relationships for you, but it needs some help deciding what the child/parent relationships are.
+
+The default parent of an object is the first object that returns it after it is created.  So to revisit our earlier HelloActor `getChild` implementation:
+
+    getChild: method(function(id) {
+        return new ChildActor(this.conn, id);
+    }, {
+        request: { id: Arg(0) },
+        response: { child: RetVal("childActor") }
+    });
+
+The ChildActor's parent is the HelloActor, because it's the one that created it.
+
+You can customize this behavior in two ways.  The first is by defining a `marshallPool` property in your actor.  Imagine a new ChildActor method:
+
+    getSibling: method(function(id) {
+        return new ChildActor(this.conn, id);
+    }, {
+        request: { id: Arg(0) },
+        response: { child: RetVal("childActor") }
+    });
+
+This creates a new child actor owned by the current child actor.  But in this example we want all actors created by the child to be owned by the HelloActor.  So we can define a `defaultParent` property that makes use of the `parent` proeprty provided by the Actor class:
+
+    get marshallPool() { return this.parent }
+
+The front needs to provide a matching `defaultParent` property that returns an owning front, to make sure the client and server lifetimes stay synced.
+
+For more complex situations, you can define your own lifetime properties.  Take this new pair of HelloActor methods:
+
+    // When the "temp" lifetime is specified, look for the _temporaryParent attribute as the owner.
+    types.addLifetime("temp", "_temporaryParent");
+
+    getTemporaryChild: method(function(id) {
+        if (!this._temporaryParent) {
+            // Create an actor to serve as the parent for all temporary children and explicitly
+            // add it as a child of this actor.
+            this._temporaryParent = this.manage(new Actor(this.conn));
+        }
+        return new ChildActor(this.conn, id);
+    }, {
+        request: { id: Arg(0) },
+        response: {
+            child: RetVal("temp:childActor") // use the lifetime name here to specify the expected lifetime.
+        }
+    });
+
+    clearTemporaryChildren: method(function(id) {
+        if (this._temporaryParent) {
+            this._temporaryParent.destroy();
+            delete this._temporaryParent;
+        }
+    });
+
+This will require some matching work on the front:
+
+    getTemporaryChild: protocol.custom(function(id) {
+        if (!this._temporaryParent) {
+            this._temporaryParent = this.manage(new Front(this.client));
+        }
+        return this._getTemporaryChild(id);
+    }, {
+        impl: "_getTemporaryChild"
+    }),
+
+    clearTemporaryChildren: protocol.custom(function(id) {
+        if (this._temporaryParent) {
+            this._temporaryParent.destroy();
+            delete this._temporaryParent;
+        }
+        return this._clearTemporaryChildren();
+    }, {
+        impl: "_clearTemporaryChildren"
+    })
+
+Telemetry
+---------
+
+You can specify a telemetry probe id in your method spec:
+
+    echo: method(function(str) {
+        return str;
+    }, {
+        request: { str: Arg(0) },
+        response: { str: RetVal() },
+        telemetry: "ECHO"
+    });
+
+... and the time to execute that request will be included as a telemetry probe.
--- a/toolkit/themes/linux/global/toolbarbutton.css
+++ b/toolkit/themes/linux/global/toolbarbutton.css
@@ -100,16 +100,50 @@ toolbarbutton[type="menu-button"][disabl
 }
 
 .toolbarbutton-menubutton-button {
   -moz-box-align: center;
   -moz-box-pack: center;
   -moz-box-orient: vertical;
 }
 
+/* ::::: toolbarbutton badged ::::: */
+
+.toolbarbutton-badge {
+  background-color: #d90000;
+}
+
+.toolbarbutton-badge::after {
+  /* The |content| property is set in the content stylesheet. */
+  font-size: 10px;
+  font-weight: bold;
+  padding: 1px 2px 2px;
+  color: #fff;
+  background-color: inherit;
+  border-radius: 2px;
+  box-shadow: 0 1px 0 hsla(0, 100%, 100%, .2) inset,
+              0 -1px 0 hsla(0, 0%, 0%, .1) inset,
+              0 1px 0 hsla(206, 50%, 10%, .2);
+  position: absolute;
+  top: -4px;
+  right: -2px;
+  min-width: 10px;
+  line-height: 10px;
+  text-align: center;
+}
+
+.toolbarbutton-badge:-moz-locale-dir(rtl)::after {
+  left: -2px;
+  right: auto;
+}
+
+.toolbarbutton-badge-container {
+  position: relative;
+}
+
 /* .......... dropmarker .......... */
 
 .toolbarbutton-menubutton-dropmarker {
   margin: 0 3px;
   -moz-appearance: toolbarbutton-dropdown !important;
   list-style-image: none;
   -moz-image-region: auto;
 }
--- a/toolkit/themes/osx/global/toolbarbutton.css
+++ b/toolkit/themes/osx/global/toolbarbutton.css
@@ -71,16 +71,65 @@ toolbarbutton[type="menu-button"][disabl
 
 .toolbarbutton-menubutton-button {
   -moz-box-align: center;
   -moz-box-pack: center;
   -moz-box-orient: vertical;
   text-shadow: inherit;
 }
 
+/* ::::: toolbarbutton badged ::::: */
+
+.toolbarbutton-badge {
+  background-color: #d90000;
+}
+
+.toolbarbutton-badge::after {
+  /* The |content| property is set in the content stylesheet. */
+  font-size: 9px;
+  padding: 1px 2px 2px;
+  color: #fff;
+  background-color: inherit;
+  border-radius: 2px;
+  box-shadow: 0 1px 0 hsla(0, 100%, 100%, .2) inset,
+              0 -1px 0 hsla(0, 0%, 0%, .1) inset,
+              0 1px 0 hsla(206, 50%, 10%, .2);