Bug 694206 - Add Gonk (B2G) widget backend, r=cjones
authorMichael Wu <mwu@mozilla.com>
Thu, 10 Nov 2011 16:17:46 -0800
changeset 81794 27a6377f1e1735132564c79960707c7825768133
parent 81793 fab0ec1dbd720c1de25ab981a85dcd85cc26bfb1
child 81795 7b278c9ea9c2c3e34292372275629ddc9145c588
push idunknown
push userunknown
push dateunknown
reviewerscjones
bugs694206
milestone11.0a1
Bug 694206 - Add Gonk (B2G) widget backend, r=cjones
Makefile.in
build/Makefile.in
configure.in
docshell/build/nsDocShellModule.cpp
dom/ipc/ContentChild.cpp
dom/ipc/ContentParent.cpp
dom/plugins/base/PluginPRLibrary.cpp
dom/plugins/base/PluginPRLibrary.h
dom/plugins/base/npfunctions.h
dom/plugins/base/nsNPAPIPlugin.cpp
dom/plugins/base/nsNPAPIPluginInstance.cpp
dom/plugins/base/nsNPAPIPluginInstance.h
dom/plugins/base/nsPluginInstanceOwner.cpp
dom/plugins/ipc/PluginLibrary.h
dom/plugins/ipc/PluginModuleParent.cpp
dom/plugins/ipc/PluginModuleParent.h
dom/src/geolocation/nsGeolocation.cpp
embedding/Makefile.in
gfx/cairo/cairo/src/Makefile.in
gfx/src/Makefile.in
gfx/src/nsDeviceContext.cpp
gfx/thebes/GLContextProviderEGL.cpp
gfx/thebes/Makefile.in
image/decoders/Makefile.in
ipc/chromium/src/base/message_loop.cc
ipc/glue/GeckoChildProcessHost.cpp
js/src/configure.in
js/src/jscntxt.cpp
layout/build/nsLayoutModule.cpp
layout/generic/nsObjectFrame.cpp
media/libsydneyaudio/src/Makefile.in
media/libsydneyaudio/src/sydney_audio_gonk.c
memory/mozalloc/Makefile.in
memory/mozutils/Makefile.in
mobile/components/build/nsShellService.cpp
netwerk/build/nsNetModule.cpp
netwerk/protocol/device/Makefile.in
netwerk/protocol/device/nsDeviceChannel.cpp
security/manager/Makefile.in
security/manager/android_stub.h
toolkit/components/downloads/nsDownloadManager.cpp
toolkit/library/libxul-config.mk
toolkit/library/nsStaticXULComponents.cpp
toolkit/mozapps/installer/packager.mk
toolkit/xre/Makefile.in
toolkit/xre/nsAppRunner.cpp
toolkit/xre/nsXREDirProvider.cpp
uriloader/exthandler/Makefile.in
uriloader/exthandler/gonk/nsOSHelperAppService.cpp
uriloader/exthandler/gonk/nsOSHelperAppService.h
uriloader/exthandler/nsExternalHelperAppService.cpp
widget/public/Makefile.in
widget/src/Makefile.in
widget/src/gonk/Makefile.in
widget/src/gonk/nsAppShell.cpp
widget/src/gonk/nsAppShell.h
widget/src/gonk/nsLookAndFeel.cpp
widget/src/gonk/nsLookAndFeel.h
widget/src/gonk/nsScreenManagerGonk.cpp
widget/src/gonk/nsScreenManagerGonk.h
widget/src/gonk/nsWidgetFactory.cpp
widget/src/gonk/nsWindow.cpp
widget/src/gonk/nsWindow.h
widget/src/xpwidgets/Makefile.in
xpcom/base/nsSystemInfo.cpp
xpcom/components/ManifestParser.cpp
xpcom/io/nsLocalFileUnix.cpp
--- a/Makefile.in
+++ b/Makefile.in
@@ -60,17 +60,17 @@ TIERS += base
 #
 tier_base_dirs = \
 	config \
 	build \
 	probes \
 	$(NULL)
 
 ifndef LIBXUL_SDK
-ifeq ($(OS_TARGET),Android)
+ifeq (android,$(MOZ_WIDGET_TOOLKIT))
 tier_base_dirs += other-licenses/android
 endif
 
 tier_base_dirs += memory
 endif
 
 ifdef COMPILE_ENVIRONMENT
 include $(topsrcdir)/$(MOZ_BUILD_APP)/build.mk
--- a/build/Makefile.in
+++ b/build/Makefile.in
@@ -51,17 +51,17 @@ endif
 
 ifeq (WINNT,$(OS_ARCH))
 DIRS = win32
 endif
 
 DIRS += pgo
 
 ifdef ENABLE_TESTS
-ifeq (Android,$(OS_TARGET))
+ifeq (android,$(MOZ_WIDGET_TOOLKIT))
   DIRS += mobile/sutagent/android \
           mobile/sutagent/android/watcher \
           mobile/sutagent/android/ffxcp \
           mobile/sutagent/android/fencp \
           $(NULL)
 endif
 endif
 
--- a/configure.in
+++ b/configure.in
@@ -284,16 +284,66 @@ i?86-*android*)
 arm-android-eabi)
     android_tool_prefix="arm-eabi"
     ;;
 *)
     android_tool_prefix="$target_os"
     ;;
 esac
 
+MOZ_ARG_WITH_STRING(gonk,
+[  --with-gonk=DIR
+               location of gonk dir],
+    gonkdir=$withval)
+
+if test -n "$gonkdir" ; then
+    kernel_name=`uname -s | tr "[[:upper:]]" "[[:lower:]]"`
+    gonk_toolchain="$gonkdir"/prebuilt/$kernel_name-x86/toolchain/arm-eabi-4.4.3
+
+    dnl set up compilers
+    AS="$gonk_toolchain"/bin/"$android_tool_prefix"-as
+    CC="$gonk_toolchain"/bin/"$android_tool_prefix"-gcc
+    CXX="$gonk_toolchain"/bin/"$android_tool_prefix"-g++
+    CPP="$gonk_toolchain"/bin/"$android_tool_prefix"-cpp
+    LD="$gonk_toolchain"/bin/"$android_tool_prefix"-ld
+    AR="$gonk_toolchain"/bin/"$android_tool_prefix"-ar
+    RANLIB="$gonk_toolchain"/bin/"$android_tool_prefix"-ranlib
+    STRIP="$gonk_toolchain"/bin/"$android_tool_prefix"-strip
+
+    STLPORT_CPPFLAGS="-I$gonkdir/ndk/sources/cxx-stl/stlport/stlport/"
+    STLPORT_LIBS="-lstlport"
+
+    CPPFLAGS="-DANDROID -I$gonkdir/bionic/libc/include/ -I$gonkdir/bionic/libc/kernel/common -I$gonkdir/bionic/libc/arch-arm/include -I$gonkdir/bionic/libc/kernel/arch-arm -I$gonkdir/bionic/libm/include -I$gonkdir/frameworks/base/opengl/include -I$gonkdir/frameworks/base/native/include -I$gonkdir/hardware/libhardware/include -I$gonkdir/system/core/include -I$gonkdir/bionic -I$gonkdir/frameworks/base/include $STLPORT_CPPFLAGS $CPPFLAGS"
+    CFLAGS="-mandroid -fno-short-enums -fno-exceptions $CFLAGS"
+    CXXFLAGS="-mandroid -fno-short-enums -fno-exceptions $CXXFLAGS"
+    LIBS="$LIBS $STLPORT_LIBS"
+
+    dnl Add -llog by default, since we use it all over the place.
+    LDFLAGS="-mandroid -L$gonkdir/out/target/product/$GONK_PRODUCT/obj/lib -Wl,-rpath-link=$gonkdir/out/target/product/$GONK_PRODUCT/obj/lib --sysroot=$gonkdir/out/target/product/$GONK_PRODUCT/obj/ -llog $LDFLAGS"
+
+    dnl prevent cross compile section from using these flags as host flags
+    if test -z "$HOST_CPPFLAGS" ; then
+        HOST_CPPFLAGS=" "
+    fi
+    if test -z "$HOST_CFLAGS" ; then
+        HOST_CFLAGS=" "
+    fi
+    if test -z "$HOST_CXXFLAGS" ; then
+        HOST_CXXFLAGS=" "
+    fi
+    if test -z "$HOST_LDFLAGS" ; then
+        HOST_LDFLAGS=" "
+    fi
+
+    AC_DEFINE(ANDROID)
+    CROSS_COMPILE=1
+    MOZ_CHROME_FILE_FORMAT=omni
+    ZLIB_DIR=yes
+    direct_nspr_config=1
+else
 case "$target" in
 *-android*|*-linuxandroid*)
     if test -z "$android_ndk" ; then
         AC_MSG_ERROR([You must specify --with-android-ndk=/path/to/ndk when targeting Android.])
     fi
 
     if test -z "$android_sdk" ; then
         AC_MSG_ERROR([You must specify --with-android-sdk=/path/to/sdk when targeting Android.])
@@ -414,16 +464,18 @@ case "$target" in
     MOZ_CHROME_FILE_FORMAT=omni
     ZLIB_DIR=yes
     ;;
 *-linux*)
     AC_PATH_PROG(OBJCOPY,objcopy)
     ;;
 esac
 
+fi
+
 AC_SUBST(ANDROID_NDK)
 AC_SUBST(ANDROID_TOOLCHAIN)
 AC_SUBST(ANDROID_PLATFORM)
 AC_SUBST(ANDROID_SDK)
 AC_SUBST(ANDROID_PLATFORM_TOOLS)
 AC_SUBST(ANDROID_PACKAGE_NAME)
 AC_SUBST(OBJCOPY)
 
@@ -2381,17 +2433,21 @@ ia64*-hpux*)
     fi
     MOZ_POST_PROGRAM_COMMAND='chatr +s enable'
     AC_DEFINE(NSCAP_DISABLE_DEBUG_PTR_TYPES)
     ;;
 
 *-android*|*-linuxandroid*)
     AC_DEFINE(NO_PW_GECOS)
     no_x=yes
-    _PLATFORM_DEFAULT_TOOLKIT=cairo-android
+    if test -n "$gonkdir"; then
+        _PLATFORM_DEFAULT_TOOLKIT=cairo-gonk
+    else
+        _PLATFORM_DEFAULT_TOOLKIT=cairo-android
+    fi
     TARGET_NSPR_MDCPUCFG='\"md/_linux.cfg\"'
 
     MOZ_GFX_OPTIMIZE_MOBILE=1
     MOZ_OPTIMIZE_FLAGS="-Os -freorder-blocks -fno-reorder-functions"
     ;;
 
 *-*linux*)
     # Note: both GNU_CC and INTEL_CC are set when using Intel's C compiler.
@@ -4767,17 +4823,18 @@ MOZ_ARG_HEADER(Toolkit Options)
     if test "$_DEFAULT_TOOLKIT" = "cairo-windows" \
         -o "$_DEFAULT_TOOLKIT" = "cairo-gtk2" \
         -o "$_DEFAULT_TOOLKIT" = "cairo-gtk2-dfb" \
         -o "$_DEFAULT_TOOLKIT" = "cairo-gtk2-x11" \
         -o "$_DEFAULT_TOOLKIT" = "cairo-qt" \
         -o "$_DEFAULT_TOOLKIT" = "cairo-os2" \
         -o "$_DEFAULT_TOOLKIT" = "cairo-cocoa" \
         -o "$_DEFAULT_TOOLKIT" = "cairo-uikit" \
-        -o "$_DEFAULT_TOOLKIT" = "cairo-android"
+        -o "$_DEFAULT_TOOLKIT" = "cairo-android" \
+        -o "$_DEFAULT_TOOLKIT" = "cairo-gonk"
     then
         dnl nglayout only supports building with one toolkit,
         dnl so ignore everything after the first comma (",").
         MOZ_WIDGET_TOOLKIT=`echo "$_DEFAULT_TOOLKIT" | sed -e "s/,.*$//"`
     else
         AC_MSG_ERROR([You must specify a default toolkit (perhaps $_PLATFORM_DEFAULT_TOOLKIT).])
     fi
 
@@ -4890,16 +4947,25 @@ cairo-android)
     MOZ_WIDGET_TOOLKIT=android
     TK_CFLAGS='$(MOZ_CAIRO_CFLAGS)'
     TK_LIBS='$(MOZ_CAIRO_LIBS)'
     MOZ_WEBGL=1
     MOZ_PDF_PRINTING=1
     MOZ_INSTRUMENT_EVENT_LOOP=1
     ;;
 
+cairo-gonk)
+    AC_DEFINE(MOZ_WIDGET_GONK)
+    MOZ_WIDGET_TOOLKIT=gonk
+    TK_CFLAGS='$(MOZ_CAIRO_CFLAGS)'
+    TK_LIBS='$(MOZ_CAIRO_LIBS)'
+    MOZ_WEBGL=1
+    MOZ_PDF_PRINTING=1
+    ;;
+
 esac
 
 AC_SUBST(MOZ_PDF_PRINTING)
 if test "$MOZ_PDF_PRINTING"; then
    PDF_SURFACE_FEATURE="#define CAIRO_HAS_PDF_SURFACE 1"
    AC_DEFINE(MOZ_PDF_PRINTING)
 fi
 
@@ -7170,17 +7236,19 @@ AC_SUBST(MOZ_UTILS_PROGRAM_LDFLAGS)
 AC_SUBST(WIN32_CRT_LIBS)
 dnl Need to set this for make because NSS doesn't have configure
 AC_SUBST(DLLFLAGS)
 
 dnl We need to wrap dlopen and related functions on Android because we use
 dnl our own linker.
 if test "$OS_TARGET" = Android; then
     WRAP_LDFLAGS="${WRAP_LDFLAGS} -L$_objdir/dist/lib -lmozutils"
-    WRAP_LDFLAGS="${WRAP_LDFLAGS} -Wl,--wrap=dlopen,--wrap=dlclose,--wrap=dlerror,--wrap=dlsym,--wrap=dladdr"
+    if test "$MOZ_WIDGET_TOOLKIT" = android; then
+        WRAP_LDFLAGS="${WRAP_LDFLAGS} -Wl,--wrap=dlopen,--wrap=dlclose,--wrap=dlerror,--wrap=dlsym,--wrap=dladdr"
+    fi
 fi
 
 dnl ========================================================
 dnl = Use malloc wrapper lib
 dnl ========================================================
 MOZ_ARG_ENABLE_BOOL(wrap-malloc,
 [  --enable-wrap-malloc    Wrap malloc calls (gnu linker only)],
     _WRAP_MALLOC=1,
@@ -8851,30 +8919,32 @@ if test "$MOZ_TREE_FREETYPE"; then
    export CPPFLAGS="$CPPFLAGS"
    export CXXFLAGS="$CXXFLAGS"
    export LDFLAGS="$LDFLAGS"
    export CONFIG_FILES="unix-cc.mk:unix-cc.in unix-def.mk:unix-def.in freetype-config freetype2.pc:freetype2.in"
    ac_configure_args="$ac_configure_args --host=$target --disable-shared --with-pic=yes"
    AC_OUTPUT_SUBDIRS(modules/freetype2)
 fi
 
-dnl ========================================================
-dnl = Setup a nice relatively clean build environment for
-dnl = sub-configures.
-dnl ========================================================
-CC="$_SUBDIR_CC"
-CXX="$_SUBDIR_CXX"
-CFLAGS="$_SUBDIR_CFLAGS"
-CPPFLAGS="$_SUBDIR_CPPFLAGS"
-CXXFLAGS="$_SUBDIR_CXXFLAGS"
-LDFLAGS="$_SUBDIR_LDFLAGS"
-HOST_CC="$_SUBDIR_HOST_CC"
-HOST_CFLAGS="$_SUBDIR_HOST_CFLAGS"
-HOST_LDFLAGS="$_SUBDIR_HOST_LDFLAGS"
-RC=
+if test -z "$direct_nspr_config"; then
+    dnl ========================================================
+    dnl = Setup a nice relatively clean build environment for
+    dnl = sub-configures.
+    dnl ========================================================
+    CC="$_SUBDIR_CC"
+    CXX="$_SUBDIR_CXX"
+    CFLAGS="$_SUBDIR_CFLAGS"
+    CPPFLAGS="$_SUBDIR_CPPFLAGS"
+    CXXFLAGS="$_SUBDIR_CXXFLAGS"
+    LDFLAGS="$_SUBDIR_LDFLAGS"
+    HOST_CC="$_SUBDIR_HOST_CC"
+    HOST_CFLAGS="$_SUBDIR_HOST_CFLAGS"
+    HOST_LDFLAGS="$_SUBDIR_HOST_LDFLAGS"
+    RC=
+fi
 
 unset MAKEFILES
 unset CONFIG_FILES
 
 # No need to run subconfigures when building with LIBXUL_SDK_DIR
 if test "$COMPILE_ENVIRONMENT" -a -z "$LIBXUL_SDK_DIR"; then
 
 export WRAP_LDFLAGS
@@ -8913,16 +8983,33 @@ if test -z "$MOZ_NATIVE_NSPR"; then
        NSPR_LIBS=`./nsprpub/config/nspr-config --prefix=$LIBXUL_DIST --exec-prefix=$MOZ_BUILD_ROOT/dist --libdir=$LIBXUL_DIST/lib --libs`
        $PERL -pi.bak -e "s '^NSPR_LIBS\\s*=.*'NSPR_LIBS = $NSPR_LIBS'" config/autoconf.mk
        NSPR_CFLAGS=`./nsprpub/config/nspr-config --prefix=$LIBXUL_DIST --exec-prefix=$MOZ_BUILD_ROOT/dist --includedir=$LIBXUL_DIST/include/nspr --cflags`
        $PERL -pi.bak -e "s '^NSPR_CFLAGS\\s*=.*'NSPR_CFLAGS = $NSPR_CFLAGS'" config/autoconf.mk
     fi
     rm -f config/autoconf.mk.bak
 fi
 
+if test -n "$direct_nspr_config"; then
+    dnl ========================================================
+    dnl = Setup a nice relatively clean build environment for
+    dnl = sub-configures.
+    dnl ========================================================
+    CC="$_SUBDIR_CC"
+    CXX="$_SUBDIR_CXX"
+    CFLAGS="$_SUBDIR_CFLAGS"
+    CPPFLAGS="$_SUBDIR_CPPFLAGS"
+    CXXFLAGS="$_SUBDIR_CXXFLAGS"
+    LDFLAGS="$_SUBDIR_LDFLAGS"
+    HOST_CC="$_SUBDIR_HOST_CC"
+    HOST_CFLAGS="$_SUBDIR_HOST_CFLAGS"
+    HOST_LDFLAGS="$_SUBDIR_HOST_LDFLAGS"
+    RC=
+fi
+
 # Run the SpiderMonkey 'configure' script.
 dist=$MOZ_BUILD_ROOT/dist
 ac_configure_args="$_SUBDIR_CONFIG_ARGS"
 ac_configure_args="$ac_configure_args --enable-threadsafe"
 if test "$BUILD_CTYPES"; then
     # Build js-ctypes on the platforms we can.
     ac_configure_args="$ac_configure_args --enable-ctypes"
 fi
--- a/docshell/build/nsDocShellModule.cpp
+++ b/docshell/build/nsDocShellModule.cpp
@@ -52,20 +52,20 @@
 #include "nsOSHelperAppService.h"
 #include "nsExternalProtocolHandler.h"
 #include "nsPrefetchService.h"
 #include "nsOfflineCacheUpdate.h"
 #include "nsLocalHandlerApp.h"
 #ifdef MOZ_ENABLE_DBUS
 #include "nsDBusHandlerApp.h"
 #endif 
-#if defined(ANDROID) || defined(MOZ_ENABLE_MEEGOTOUCHSHARE)
+#if defined(MOZ_WIDGET_ANDROID) || defined(MOZ_ENABLE_MEEGOTOUCHSHARE)
 #include "nsExternalSharingAppService.h"
 #endif
-#if defined(ANDROID)
+#if defined(MOZ_WIDGET_ANDROID)
 #include "nsExternalURLHandlerService.h"
 #endif
 
 // session history
 #include "nsSHEntry.h"
 #include "nsSHEntryShared.h"
 #include "nsSHistory.h"
 #include "nsSHTransaction.h"
@@ -113,20 +113,20 @@ NS_GENERIC_FACTORY_CONSTRUCTOR(nsExterna
 NS_GENERIC_FACTORY_CONSTRUCTOR_INIT(nsPrefetchService, Init)
 NS_GENERIC_FACTORY_SINGLETON_CONSTRUCTOR(nsOfflineCacheUpdateService,
                                          nsOfflineCacheUpdateService::GetInstance)
 NS_GENERIC_FACTORY_CONSTRUCTOR(nsOfflineCacheUpdate)
 NS_GENERIC_FACTORY_CONSTRUCTOR(PlatformLocalHandlerApp_t)
 #ifdef MOZ_ENABLE_DBUS
 NS_GENERIC_FACTORY_CONSTRUCTOR(nsDBusHandlerApp)
 #endif 
-#if defined(ANDROID) || defined(MOZ_ENABLE_MEEGOTOUCHSHARE)
+#if defined(MOZ_WIDGET_ANDROID) || defined(MOZ_ENABLE_MEEGOTOUCHSHARE)
 NS_GENERIC_FACTORY_CONSTRUCTOR(nsExternalSharingAppService)
 #endif
-#if defined(ANDROID)
+#if defined(MOZ_WIDGET_ANDROID)
 NS_GENERIC_FACTORY_CONSTRUCTOR(nsExternalURLHandlerService)
 #endif
 
 // session history
 NS_GENERIC_FACTORY_CONSTRUCTOR(nsSHEntry)
 NS_GENERIC_FACTORY_CONSTRUCTOR(nsSHTransaction)
 NS_GENERIC_FACTORY_CONSTRUCTOR(nsSHistory)
 
@@ -143,20 +143,20 @@ NS_DEFINE_NAMED_CID(NS_EXTERNALHELPERAPP
 NS_DEFINE_NAMED_CID(NS_EXTERNALPROTOCOLHANDLER_CID);
 NS_DEFINE_NAMED_CID(NS_PREFETCHSERVICE_CID);
 NS_DEFINE_NAMED_CID(NS_OFFLINECACHEUPDATESERVICE_CID);
 NS_DEFINE_NAMED_CID(NS_OFFLINECACHEUPDATE_CID);
 NS_DEFINE_NAMED_CID(NS_LOCALHANDLERAPP_CID);
 #ifdef MOZ_ENABLE_DBUS
 NS_DEFINE_NAMED_CID(NS_DBUSHANDLERAPP_CID);
 #endif
-#if defined(ANDROID) || defined(MOZ_ENABLE_MEEGOTOUCHSHARE)
+#if defined(MOZ_WIDGET_ANDROID) || defined(MOZ_ENABLE_MEEGOTOUCHSHARE)
 NS_DEFINE_NAMED_CID(NS_EXTERNALSHARINGAPPSERVICE_CID);
 #endif
-#if defined(ANDROID)
+#if defined(MOZ_WIDGET_ANDROID)
 NS_DEFINE_NAMED_CID(NS_EXTERNALURLHANDLERSERVICE_CID);
 #endif
 NS_DEFINE_NAMED_CID(NS_SHENTRY_CID);
 NS_DEFINE_NAMED_CID(NS_HISTORYENTRY_CID);
 NS_DEFINE_NAMED_CID(NS_SHTRANSACTION_CID);
 NS_DEFINE_NAMED_CID(NS_SHISTORY_CID);
 NS_DEFINE_NAMED_CID(NS_SHISTORY_INTERNAL_CID);
 NS_DEFINE_NAMED_CID(NS_DOWNLOADHISTORY_CID);
@@ -173,20 +173,20 @@ const mozilla::Module::CIDEntry kDocShel
   { &kNS_EXTERNALPROTOCOLHANDLER_CID, false, NULL, nsExternalProtocolHandlerConstructor },
   { &kNS_PREFETCHSERVICE_CID, false, NULL, nsPrefetchServiceConstructor },
   { &kNS_OFFLINECACHEUPDATESERVICE_CID, false, NULL, nsOfflineCacheUpdateServiceConstructor },
   { &kNS_OFFLINECACHEUPDATE_CID, false, NULL, nsOfflineCacheUpdateConstructor },
   { &kNS_LOCALHANDLERAPP_CID, false, NULL, PlatformLocalHandlerApp_tConstructor },
 #ifdef MOZ_ENABLE_DBUS
   { &kNS_DBUSHANDLERAPP_CID, false, NULL, nsDBusHandlerAppConstructor },
 #endif
-#if defined(ANDROID) || defined(MOZ_ENABLE_MEEGOTOUCHSHARE)
+#if defined(MOZ_WIDGET_ANDROID) || defined(MOZ_ENABLE_MEEGOTOUCHSHARE)
   { &kNS_EXTERNALSHARINGAPPSERVICE_CID, false, NULL, nsExternalSharingAppServiceConstructor },
 #endif
-#if defined(ANDROID)
+#if defined(MOZ_WIDGET_ANDROID)
   { &kNS_EXTERNALURLHANDLERSERVICE_CID, false, NULL, nsExternalURLHandlerServiceConstructor },
 #endif
   { &kNS_SHENTRY_CID, false, NULL, nsSHEntryConstructor },
   { &kNS_HISTORYENTRY_CID, false, NULL, nsSHEntryConstructor },
   { &kNS_SHTRANSACTION_CID, false, NULL, nsSHTransactionConstructor },
   { &kNS_SHISTORY_CID, false, NULL, nsSHistoryConstructor },
   { &kNS_SHISTORY_INTERNAL_CID, false, NULL, nsSHistoryConstructor },
   { &kNS_DOWNLOADHISTORY_CID, false, NULL, nsDownloadHistoryConstructor },
@@ -222,20 +222,20 @@ const mozilla::Module::ContractIDEntry k
   { NS_NETWORK_PROTOCOL_CONTRACTID_PREFIX"default", &kNS_EXTERNALPROTOCOLHANDLER_CID },
   { NS_PREFETCHSERVICE_CONTRACTID, &kNS_PREFETCHSERVICE_CID },
   { NS_OFFLINECACHEUPDATESERVICE_CONTRACTID, &kNS_OFFLINECACHEUPDATESERVICE_CID },
   { NS_OFFLINECACHEUPDATE_CONTRACTID, &kNS_OFFLINECACHEUPDATE_CID },
   { NS_LOCALHANDLERAPP_CONTRACTID, &kNS_LOCALHANDLERAPP_CID },
 #ifdef MOZ_ENABLE_DBUS
   { NS_DBUSHANDLERAPP_CONTRACTID, &kNS_DBUSHANDLERAPP_CID },
 #endif
-#if defined(ANDROID) || defined(MOZ_ENABLE_MEEGOTOUCHSHARE)
+#if defined(MOZ_WIDGET_ANDROID) || defined(MOZ_ENABLE_MEEGOTOUCHSHARE)
   { NS_EXTERNALSHARINGAPPSERVICE_CONTRACTID, &kNS_EXTERNALSHARINGAPPSERVICE_CID },
 #endif
-#if defined(ANDROID)
+#if defined(MOZ_WIDGET_ANDROID)
   { NS_EXTERNALURLHANDLERSERVICE_CONTRACTID, &kNS_EXTERNALURLHANDLERSERVICE_CID },
 #endif
   { NS_SHENTRY_CONTRACTID, &kNS_SHENTRY_CID },
   { NS_HISTORYENTRY_CONTRACTID, &kNS_HISTORYENTRY_CID },
   { NS_SHTRANSACTION_CONTRACTID, &kNS_SHTRANSACTION_CID },
   { NS_SHISTORY_CONTRACTID, &kNS_SHISTORY_CID },
   { NS_SHISTORY_INTERNAL_CONTRACTID, &kNS_SHISTORY_INTERNAL_CID },
   { NS_DOWNLOADHISTORY_CONTRACTID, &kNS_DOWNLOADHISTORY_CID },
--- a/dom/ipc/ContentChild.cpp
+++ b/dom/ipc/ContentChild.cpp
@@ -93,17 +93,17 @@
 
 #ifdef MOZ_PERMISSIONS
 #include "nsPermission.h"
 #include "nsPermissionManager.h"
 #endif
 
 #include "nsDeviceMotion.h"
 
-#if defined(ANDROID)
+#if defined(MOZ_WIDGET_ANDROID)
 #include "APKOpen.h"
 #endif
 
 #ifdef XP_WIN
 #include <process.h>
 #define getpid _getpid
 #endif
 
@@ -267,17 +267,17 @@ ContentChild::Init(MessageLoop* aIOLoop,
     NS_ASSERTION(!sSingleton, "only one ContentChild per child");
 
     Open(aChannel, aParentHandle, aIOLoop);
     sSingleton = this;
 
 #ifdef MOZ_CRASHREPORTER
     SendPCrashReporterConstructor(CrashReporter::CurrentThreadId(),
                                   XRE_GetProcessType());
-#if defined(ANDROID)
+#if defined(MOZ_WIDGET_ANDROID)
     PCrashReporterChild* crashreporter = ManagedPCrashReporterChild()[0];
 
     InfallibleTArray<Mapping> mappings;
     const struct mapping_info *info = getLibraryMapping();
     while (info && info->name) {
         mappings.AppendElement(Mapping(nsDependentCString(info->name),
                                        nsDependentCString(info->file_id),
                                        info->base,
--- a/dom/ipc/ContentParent.cpp
+++ b/dom/ipc/ContentParent.cpp
@@ -101,16 +101,18 @@
 #include "mozilla/Util.h"
 
 #include "nsIMemoryReporter.h"
 #include "nsMemoryReporterManager.h"
 #include "mozilla/dom/PMemoryReportRequestParent.h"
 
 #ifdef ANDROID
 #include "gfxAndroidPlatform.h"
+#endif
+#ifdef MOZ_WIDGET_ANDROID
 #include "AndroidBridge.h"
 #endif
 
 #include "nsIClipboard.h"
 #include "nsWidgetsCID.h"
 #include "nsISupportsPrimitives.h"
 static NS_DEFINE_CID(kCClipboardCID, NS_CLIPBOARD_CID);
 static const char* sClipboardTextFlavors[] = { kUnicodeMime };
@@ -631,17 +633,17 @@ ContentParent::RecvClipboardHasText(bool
     clipboard->HasDataMatchingFlavors(sClipboardTextFlavors, 1, 
                                       nsIClipboard::kGlobalClipboard, hasText);
     return true;
 }
 
 bool
 ContentParent::RecvGetSystemColors(const PRUint32& colorsCount, InfallibleTArray<PRUint32>* colors)
 {
-#ifdef ANDROID
+#ifdef MOZ_WIDGET_ANDROID
     NS_ASSERTION(AndroidBridge::Bridge() != nsnull, "AndroidBridge is not available");
     if (AndroidBridge::Bridge() == nsnull) {
         // Do not fail - the colors won't be right, but it's not critical
         return true;
     }
 
     colors->AppendElements(colorsCount);
 
@@ -650,17 +652,17 @@ ContentParent::RecvGetSystemColors(const
     AndroidBridge::Bridge()->GetSystemColors((AndroidSystemColors*)colors->Elements());
 #endif
     return true;
 }
 
 bool
 ContentParent::RecvGetIconForExtension(const nsCString& aFileExt, const PRUint32& aIconSize, InfallibleTArray<PRUint8>* bits)
 {
-#ifdef ANDROID
+#ifdef MOZ_WIDGET_ANDROID
     NS_ASSERTION(AndroidBridge::Bridge() != nsnull, "AndroidBridge is not available");
     if (AndroidBridge::Bridge() == nsnull) {
         // Do not fail - just no icon will be shown
         return true;
     }
 
     bits->AppendElements(aIconSize * aIconSize * 4);
 
@@ -669,17 +671,17 @@ ContentParent::RecvGetIconForExtension(c
     return true;
 }
 
 bool
 ContentParent::RecvGetShowPasswordSetting(bool* showPassword)
 {
     // default behavior is to show the last password character
     *showPassword = true;
-#ifdef ANDROID
+#ifdef MOZ_WIDGET_ANDROID
     NS_ASSERTION(AndroidBridge::Bridge() != nsnull, "AndroidBridge is not available");
     if (AndroidBridge::Bridge() != nsnull)
         *showPassword = AndroidBridge::Bridge()->GetShowPasswordSetting();
 #endif
     return true;
 }
 
 NS_IMPL_THREADSAFE_ISUPPORTS4(ContentParent,
--- a/dom/plugins/base/PluginPRLibrary.cpp
+++ b/dom/plugins/base/PluginPRLibrary.cpp
@@ -46,25 +46,25 @@
 // gNotOptimized exists so that the compiler will not optimize the alloca
 // below.
 static int gNotOptimized;
 #define CALLING_CONVENTION_HACK void* foo = _alloca(gNotOptimized);
 #else
 #define CALLING_CONVENTION_HACK
 #endif
 
-#ifdef ANDROID
+#ifdef MOZ_WIDGET_ANDROID
 #include "AndroidBridge.h"
 #include "android_npapi.h"
 #include <android/log.h>
 #define ALOG(args...) __android_log_print(ANDROID_LOG_INFO, "GeckoJavaEnv", ## args)
 #endif
 
 namespace mozilla {
-#ifdef ANDROID
+#ifdef MOZ_WIDGET_ANDROID
 nsresult
 PluginPRLibrary::NP_Initialize(NPNetscapeFuncs* bFuncs,
 			       NPPluginFuncs* pFuncs, NPError* error)
 {
   if (mNP_Initialize) {
     *error = mNP_Initialize(bFuncs, pFuncs, GetJNIForThread());
   } else {
     NP_InitializeFunc pfNP_Initialize = (NP_InitializeFunc)
@@ -77,20 +77,26 @@ PluginPRLibrary::NP_Initialize(NPNetscap
 
   // Save pointers to functions that get called through PluginLibrary itself.
   mNPP_New = pFuncs->newp;
   mNPP_GetValue = pFuncs->getvalue;
   mNPP_ClearSiteData = pFuncs->clearsitedata;
   mNPP_GetSitesWithData = pFuncs->getsiteswithdata;
   return NS_OK;
 }
+#elif defined(MOZ_WIDGET_GONK)
+nsresult
+PluginPRLibrary::NP_Initialize(NPNetscapeFuncs* bFuncs, NPError* error)
+{
+  return NS_OK;
+}
 #elif defined(XP_UNIX) && !defined(XP_MACOSX)
 nsresult
 PluginPRLibrary::NP_Initialize(NPNetscapeFuncs* bFuncs,
-			       NPPluginFuncs* pFuncs, NPError* error)
+                               NPPluginFuncs* pFuncs, NPError* error)
 {
   if (mNP_Initialize) {
     *error = mNP_Initialize(bFuncs, pFuncs);
   } else {
     NP_InitializeFunc pfNP_Initialize = (NP_InitializeFunc)
       PR_FindFunctionSymbol(mLibrary, "NP_Initialize");
     if (!pfNP_Initialize)
       return NS_ERROR_FAILURE;
--- a/dom/plugins/base/PluginPRLibrary.h
+++ b/dom/plugins/base/PluginPRLibrary.h
@@ -109,17 +109,17 @@ public:
         mNP_GetEntryPoints = (NP_GetEntryPointsFunc)
             PR_FindFunctionSymbol(mLibrary, "NP_GetEntryPoints");
         if (!mNP_GetEntryPoints)
             return false;
 #endif
         return true;
     }
 
-#if defined(XP_UNIX) && !defined(XP_MACOSX)
+#if defined(XP_UNIX) && !defined(XP_MACOSX) && !defined(MOZ_WIDGET_GONK)
     virtual nsresult NP_Initialize(NPNetscapeFuncs* bFuncs,
                                    NPPluginFuncs* pFuncs, NPError* error);
 #else
     virtual nsresult NP_Initialize(NPNetscapeFuncs* bFuncs,
                                    NPError* error);
 #endif
 
     virtual nsresult NP_Shutdown(NPError* error);
--- a/dom/plugins/base/npfunctions.h
+++ b/dom/plugins/base/npfunctions.h
@@ -43,17 +43,17 @@
 #define NP_LOADDS _System
 #else
 #define NP_LOADDS
 #endif
 
 #include "npapi.h"
 #include "npruntime.h"
 
-#ifdef ANDROID
+#ifdef MOZ_WIDGET_ANDROID
 #include <jni.h>
 #endif
 
 typedef NPError      (* NP_LOADDS NPP_NewProcPtr)(NPMIMEType pluginType, NPP instance, uint16_t mode, int16_t argc, char* argn[], char* argv[], NPSavedData* saved);
 typedef NPError      (* NP_LOADDS NPP_DestroyProcPtr)(NPP instance, NPSavedData** save);
 typedef NPError      (* NP_LOADDS NPP_SetWindowProcPtr)(NPP instance, NPWindow* window);
 typedef NPError      (* NP_LOADDS NPP_NewStreamProcPtr)(NPP instance, NPMIMEType type, NPStream* stream, NPBool seekable, uint16_t* stype);
 typedef NPError      (* NP_LOADDS NPP_DestroyStreamProcPtr)(NPP instance, NPStream* stream, NPReason reason);
@@ -306,17 +306,17 @@ NP_EXPORT(char*)       NP_GetPluginVersi
 typedef const char*    (*NP_GetMIMEDescriptionFunc)(void);
 NP_EXPORT(const char*) NP_GetMIMEDescription(void);
 #ifdef XP_MACOSX
 typedef NPError        (*NP_InitializeFunc)(NPNetscapeFuncs*);
 NP_EXPORT(NPError)     NP_Initialize(NPNetscapeFuncs* bFuncs);
 typedef NPError        (*NP_GetEntryPointsFunc)(NPPluginFuncs*);
 NP_EXPORT(NPError)     NP_GetEntryPoints(NPPluginFuncs* pFuncs);
 #else
-#ifdef ANDROID
+#ifdef MOZ_WIDGET_ANDROID
 typedef NPError    (*NP_InitializeFunc)(NPNetscapeFuncs*, NPPluginFuncs*, JNIEnv* pEnv);
 NP_EXPORT(NPError) NP_Initialize(NPNetscapeFuncs* bFuncs, NPPluginFuncs* pFuncs, JNIEnv* pEnv);
 #else
 typedef NPError    (*NP_InitializeFunc)(NPNetscapeFuncs*, NPPluginFuncs*);
 NP_EXPORT(NPError) NP_Initialize(NPNetscapeFuncs* bFuncs, NPPluginFuncs* pFuncs);
 #endif
 #endif
 typedef NPError        (*NP_ShutdownFunc)(void);
--- a/dom/plugins/base/nsNPAPIPlugin.cpp
+++ b/dom/plugins/base/nsNPAPIPlugin.cpp
@@ -126,17 +126,17 @@ using mozilla::plugins::PluginModulePare
 #ifdef MOZ_X11
 #include "mozilla/X11Util.h"
 #endif
 
 #ifdef XP_WIN
 #include <windows.h>
 #endif
 
-#ifdef ANDROID
+#ifdef MOZ_WIDGET_ANDROID
 #include "ANPBase.h"
 #include "AndroidBridge.h"
 #include <android/log.h>
 #define LOG(args...)  __android_log_print(ANDROID_LOG_INFO, "GeckoPlugins" , ## args)
 #endif
 
 using namespace mozilla;
 using namespace mozilla::plugins::parent;
@@ -483,17 +483,17 @@ nsNPAPIPlugin::CreatePlugin(nsPluginTag 
   if (!plugin)
     return NS_ERROR_OUT_OF_MEMORY;
 
   PluginLibrary* pluginLib = GetNewPluginLibrary(aPluginTag);
   if (!pluginLib) {
     return NS_ERROR_FAILURE;
   }
 
-#if defined(XP_MACOSX) || defined(ANDROID)
+#if defined(XP_MACOSX) || defined(MOZ_WIDGET_ANDROID)
   if (!pluginLib->HasRequiredFunctions()) {
     NS_WARNING("Not all necessary functions exposed by plugin, it will not load.");
     return NS_ERROR_FAILURE;
   }
 #endif
 
   plugin->mLibrary = pluginLib;
   pluginLib->SetPlugin(plugin);
@@ -521,16 +521,17 @@ nsNPAPIPlugin::CreatePlugin(nsPluginTag 
   if (rv != NS_OK || pluginCallError != NPERR_NO_ERROR) {
     return NS_ERROR_FAILURE;
   }
 
   rv = pluginLib->NP_GetEntryPoints(&plugin->mPluginFuncs, &pluginCallError);
   if (rv != NS_OK || pluginCallError != NPERR_NO_ERROR) {
     return NS_ERROR_FAILURE;
   }
+#elif defined(MOZ_WIDGET_GONK)
 #else
   rv = pluginLib->NP_Initialize(&sBrowserFuncs, &plugin->mPluginFuncs, &pluginCallError);
   if (rv != NS_OK || pluginCallError != NPERR_NO_ERROR) {
     return NS_ERROR_FAILURE;
   }
 #endif
 
   *aResult = plugin.forget().get();
@@ -2293,17 +2294,17 @@ NPError NP_CALLBACK
   }
 
   case NPNVsupportsUpdatedCocoaTextInputBool: {
     *(NPBool*)result = true;
     return NPERR_NO_ERROR;
   }
 #endif
 
-#ifdef ANDROID
+#ifdef MOZ_WIDGET_ANDROID
     case kLogInterfaceV0_ANPGetValue: {
       LOG("get log interface");
       ANPLogInterfaceV0 *i = (ANPLogInterfaceV0 *) result;
       InitLogInterface(i);
       return NPERR_NO_ERROR;
     }
 
     case kBitmapInterfaceV0_ANPGetValue: {
@@ -2510,17 +2511,17 @@ NPError NP_CALLBACK
         inst->SetEventModel((NPEventModel)NS_PTR_TO_INT32(result));
         return NPERR_NO_ERROR;
       }
       else {
         return NPERR_GENERIC_ERROR;
       }
     }
 #endif
-#ifdef ANDROID
+#ifdef MOZ_WIDGET_ANDROID
   case kRequestDrawingModel_ANPSetValue:
     if (inst)
       inst->SetDrawingModel(NS_PTR_TO_INT32(result));
     return NPERR_NO_ERROR;
   case kAcceptEvents_ANPSetValue:
     return NPERR_NO_ERROR;
 #endif
     default:
--- a/dom/plugins/base/nsNPAPIPluginInstance.cpp
+++ b/dom/plugins/base/nsNPAPIPluginInstance.cpp
@@ -56,28 +56,28 @@
 #include "nsIScriptContext.h"
 #include "nsDirectoryServiceDefs.h"
 #include "nsJSNPRuntime.h"
 #include "nsPluginStreamListenerPeer.h"
 #include "nsSize.h"
 #include "nsNetCID.h"
 #include "nsIContent.h"
 
-#ifdef ANDROID
+#ifdef MOZ_WIDGET_ANDROID
 #include "ANPBase.h"
 #include <android/log.h>
 #include "android_npapi.h"
 #include "mozilla/CondVar.h"
 #include "AndroidBridge.h"
 #endif
 
 using namespace mozilla;
 using namespace mozilla::plugins::parent;
 
-#ifdef ANDROID
+#ifdef MOZ_WIDGET_ANDROID
 #include <map>
 static std::map<void*, nsNPAPIPluginInstance*> sSurfaceMap;
 #endif
 
 static NS_DEFINE_IID(kIOutputStreamIID, NS_IOUTPUTSTREAM_IID);
 static NS_DEFINE_IID(kIPluginStreamListenerIID, NS_IPLUGINSTREAMLISTENER_IID);
 
 NS_IMPL_THREADSAFE_ISUPPORTS0(nsNPAPIPluginInstance)
@@ -86,17 +86,17 @@ nsNPAPIPluginInstance::nsNPAPIPluginInst
   :
 #ifdef XP_MACOSX
 #ifdef NP_NO_QUICKDRAW
     mDrawingModel(NPDrawingModelCoreGraphics),
 #else
     mDrawingModel(NPDrawingModelQuickDraw),
 #endif
 #endif
-#ifdef ANDROID
+#ifdef MOZ_WIDGET_ANDROID
     mSurface(nsnull),
     mTargetSurface(nsnull),
     mDrawingModel(0),
 #endif
     mRunning(NOT_STARTED),
     mWindowless(false),
     mWindowlessLocal(false),
     mTransparent(false),
@@ -122,33 +122,33 @@ nsNPAPIPluginInstance::nsNPAPIPluginInst
   nsCOMPtr<nsIPrefBranch> prefs(do_GetService(NS_PREFSERVICE_CONTRACTID));
   if (prefs) {
     bool useLayersPref;
     nsresult rv = prefs->GetBoolPref("plugins.use_layers", &useLayersPref);
     if (NS_SUCCEEDED(rv))
       mUsePluginLayersPref = useLayersPref;
   }
 
-#ifdef ANDROID
+#ifdef MOZ_WIDGET_ANDROID
   mTargetSurfaceLock = new Mutex("nsNPAPIPluginInstance::SurfaceLock");
 #endif
 
   PLUGIN_LOG(PLUGIN_LOG_BASIC, ("nsNPAPIPluginInstance ctor: this=%p\n",this));
 }
 
 nsNPAPIPluginInstance::~nsNPAPIPluginInstance()
 {
   PLUGIN_LOG(PLUGIN_LOG_BASIC, ("nsNPAPIPluginInstance dtor: this=%p\n",this));
 
   if (mMIMEType) {
     PR_Free((void *)mMIMEType);
     mMIMEType = nsnull;
   }
 
-#ifdef ANDROID
+#ifdef MOZ_WIDGET_ANDROID
   if (mSurface) {
     sSurfaceMap.erase(mSurface);
   }
 
   if (mTargetSurface) {
     delete mTargetSurface;
     mTargetSurface = nsnull;
   }
@@ -359,17 +359,17 @@ nsNPAPIPluginInstance::InitializePlugin(
     // with a null entry as a separator. This is for 4.x backwards compatibility!
     // see bug 111008 for details
     if (tagtype != nsPluginTagType_Embed) {
       PRUint16 pcount = 0;
       const char* const* pnames = nsnull;
       const char* const* pvalues = nsnull;    
       if (NS_SUCCEEDED(GetParameters(pcount, pnames, pvalues))) {
         // Android expects an empty string as the separator instead of null
-#ifdef ANDROID
+#ifdef MOZ_WIDGET_ANDROID
         NS_ASSERTION(PL_strcmp(values[count], "") == 0, "attribute/parameter array not setup correctly for Android NPAPI plugins");
 #else
         NS_ASSERTION(!values[count], "attribute/parameter array not setup correctly for NPAPI plugins");
 #endif
         if (pcount)
           count += ++pcount; // if it's all setup correctly, then all we need is to
                              // change the count (attrs + PARAM/blank + params)
       }
@@ -742,17 +742,17 @@ void nsNPAPIPluginInstance::SetEventMode
     NS_WARNING("Trying to set event model without a plugin instance owner!");
     return;
   }
 
   owner->SetEventModel(aModel);
 }
 #endif
 
-#if defined(ANDROID)
+#if defined(MOZ_WIDGET_ANDROID)
 void nsNPAPIPluginInstance::SetDrawingModel(PRUint32 aModel)
 {
   mDrawingModel = aModel;
 }
 
 class SurfaceGetter : public nsRunnable {
 public:
   SurfaceGetter(NPPluginFuncs* aPluginFunctions, NPP_t aNPP) : 
@@ -854,17 +854,17 @@ nsNPAPIPluginInstance::FindByJavaSurface
 {
   return sSurfaceMap[aJavaSurface];
 }
 
 #endif
 
 nsresult nsNPAPIPluginInstance::GetDrawingModel(PRInt32* aModel)
 {
-#if defined(XP_MACOSX) || defined(ANDROID)
+#if defined(XP_MACOSX) || defined(MOZ_WIDGET_ANDROID)
   *aModel = (PRInt32)mDrawingModel;
   return NS_OK;
 #else
   return NS_ERROR_FAILURE;
 #endif
 }
 
 nsresult nsNPAPIPluginInstance::IsRemoteDrawingCoreAnimation(bool* aDrawing)
@@ -953,17 +953,17 @@ nsNPAPIPluginInstance::DefineJavaPropert
     return NS_ERROR_FAILURE;
 
   return NS_OK;
 }
 
 nsresult
 nsNPAPIPluginInstance::IsWindowless(bool* isWindowless)
 {
-#ifdef ANDROID
+#ifdef MOZ_WIDGET_ANDROID
   // On android, pre-honeycomb, all plugins are treated as windowless.
   *isWindowless = true;
 #else
   *isWindowless = mWindowless;
 #endif
   return NS_OK;
 }
 
--- a/dom/plugins/base/nsNPAPIPluginInstance.h
+++ b/dom/plugins/base/nsNPAPIPluginInstance.h
@@ -88,17 +88,17 @@ public:
 
   nsresult Initialize(nsIPluginInstanceOwner* aOwner, const char* aMIMEType);
   nsresult Start();
   nsresult Stop();
   nsresult SetWindow(NPWindow* window);
   nsresult NewStreamToPlugin(nsIPluginStreamListener** listener);
   nsresult NewStreamFromPlugin(const char* type, const char* target, nsIOutputStream* *result);
   nsresult Print(NPPrint* platformPrint);
-#ifdef ANDROID
+#ifdef MOZ_WIDGET_ANDROID
   nsresult PostEvent(void* event) { return 0; };
 #endif
   nsresult HandleEvent(void* event, PRInt16* result);
   nsresult GetValueFromPlugin(NPPVariable variable, void* value);
   nsresult GetDrawingModel(PRInt32* aModel);
   nsresult IsRemoteDrawingCoreAnimation(bool* aDrawing);
   nsresult GetJSObject(JSContext *cx, JSObject** outObject);
   nsresult DefineJavaProperties();
@@ -147,17 +147,17 @@ public:
   NPError SetUsesDOMForCursor(bool aUsesDOMForCursor);
   bool UsesDOMForCursor();
 
 #ifdef XP_MACOSX
   void SetDrawingModel(NPDrawingModel aModel);
   void SetEventModel(NPEventModel aModel);
 #endif
 
-#ifdef ANDROID
+#ifdef MOZ_WIDGET_ANDROID
   void SetDrawingModel(PRUint32 aModel);
   void* GetJavaSurface();
 
   gfxImageSurface* LockTargetSurface();
   gfxImageSurface* LockTargetSurface(PRUint32 aWidth, PRUint32 aHeight, gfxASurface::gfxImageFormat aFormat,
                                      NPRect* aRect);
   void UnlockTargetSurface(bool aInvalidate);
 
@@ -225,17 +225,17 @@ protected:
   // The structure used to communicate between the plugin instance and
   // the browser.
   NPP_t mNPP;
 
 #ifdef XP_MACOSX
   NPDrawingModel mDrawingModel;
 #endif
 
-#ifdef ANDROID
+#ifdef MOZ_WIDGET_ANDROID
   PRUint32 mDrawingModel;
 #endif
 
   enum {
     NOT_STARTED,
     RUNNING,
     DESTROYING,
     DESTROYED
@@ -272,17 +272,17 @@ private:
   nsTArray<nsNPAPITimer*> mTimers;
 
   // non-null during a HandleEvent call
   void* mCurrentPluginEvent;
 
   nsCOMPtr<nsIURI> mURI;
 
   bool mUsePluginLayersPref;
-#ifdef ANDROID
+#ifdef MOZ_WIDGET_ANDROID
   void InvalidateTargetRect();
   
   void* mSurface;
   gfxImageSurface *mTargetSurface;
   mozilla::Mutex* mTargetSurfaceLock;
   NPRect mTargetLockRect;
 #endif
 };
--- a/dom/plugins/base/nsPluginInstanceOwner.cpp
+++ b/dom/plugins/base/nsPluginInstanceOwner.cpp
@@ -113,17 +113,17 @@ static NS_DEFINE_CID(kAppShellCID, NS_AP
 
 #ifdef MOZ_WIDGET_GTK2
 #include <gdk/gdk.h>
 #include <gdk/gdkx.h>
 #include <gtk/gtk.h>
 #include "gfxXlibNativeRenderer.h"
 #endif
 
-#ifdef ANDROID
+#ifdef MOZ_WIDGET_ANDROID
 #include "ANPBase.h"
 #include "android_npapi.h"
 #include "AndroidBridge.h"
 using namespace mozilla::dom;
 
 #include <android/log.h>
 #define LOG(args...)  __android_log_print(ANDROID_LOG_INFO, "GeckoPlugins" , ## args)
 #endif
@@ -1275,17 +1275,17 @@ nsresult nsPluginInstanceOwner::EnsureCa
   if (!data.IsEmpty()) {
     mCachedAttrParamNames [nextAttrParamIndex] = ToNewUTF8String(NS_LITERAL_STRING("SRC"));
     mCachedAttrParamValues[nextAttrParamIndex] = ToNewUTF8String(data);
     nextAttrParamIndex++;
   }
 
   // Add PARAM and null separator.
   mCachedAttrParamNames [nextAttrParamIndex] = ToNewUTF8String(NS_LITERAL_STRING("PARAM"));
-#ifdef ANDROID
+#ifdef MOZ_WIDGET_ANDROID
   // Flash expects an empty string on android
   mCachedAttrParamValues[nextAttrParamIndex] = ToNewUTF8String(NS_LITERAL_STRING(""));
 #else
   mCachedAttrParamValues[nextAttrParamIndex] = nsnull;
 #endif
   nextAttrParamIndex++;
 
   // Add PARAM name/value pairs.
@@ -1667,17 +1667,17 @@ void nsPluginInstanceOwner::ScrollPositi
         mInstance->HandleEvent(&scrollEvent, nsnull);
       }
       pluginWidget->EndDrawPlugin();
     }
   }
 #endif
 }
 
-#ifdef ANDROID
+#ifdef MOZ_WIDGET_ANDROID
 void nsPluginInstanceOwner::AddPluginView(const gfxRect& aRect)
 {
   void* javaSurface = mInstance->GetJavaSurface();
 
   if (!javaSurface)
     return;
 
   JNIEnv* env = GetJNIForThread();
@@ -1709,17 +1709,17 @@ void nsPluginInstanceOwner::RemovePlugin
       }
     }
   }
 }
 #endif
 
 nsresult nsPluginInstanceOwner::DispatchFocusToPlugin(nsIDOMEvent* aFocusEvent)
 {
-#ifdef ANDROID
+#ifdef MOZ_WIDGET_ANDROID
   {
     ANPEvent event;
     event.inSize = sizeof(ANPEvent);
     event.eventType = kLifecycle_ANPEventType;
 
     nsAutoString eventType;
     aFocusEvent->GetType(eventType);
     if (eventType.EqualsLiteral("focus")) {
@@ -2522,17 +2522,17 @@ nsEventStatus nsPluginInstanceOwner::Pro
   event.send_event = False;
 
   PRInt16 response = kNPEventNotHandled;
   mInstance->HandleEvent(&pluginEvent, &response);
   if (response == kNPEventHandled)
     rv = nsEventStatus_eConsumeNoDefault;
 #endif
 
-#ifdef ANDROID
+#ifdef MOZ_WIDGET_ANDROID
   // this code supports windowless plugins
   {
     // The plugin needs focus to receive keyboard and touch events
     nsIFocusManager* fm = nsFocusManager::GetFocusManager();
     if (fm) {
       nsCOMPtr<nsIDOMElement> elem = do_QueryInterface(mContent);
       fm->SetFocus(elem, 0);
     }
@@ -2728,17 +2728,17 @@ nsPluginInstanceOwner::PrepareToStop(boo
     // and plugin et al not holding any other references to its
     // parent.
     mWidget->SetParent(nsnull);
 
     mDestroyWidget = true;
   }
 #endif
 
-#ifdef ANDROID
+#ifdef MOZ_WIDGET_ANDROID
   RemovePluginView();
 #endif
 
   // Unregister scroll position listeners
   for (nsIFrame* f = mObjectFrame; f; f = nsLayoutUtils::GetCrossDocParentFrame(f)) {
     nsIScrollableFrame* sf = do_QueryFrame(f);
     if (sf) {
       sf->RemoveScrollPositionListener(this);
@@ -2828,17 +2828,17 @@ void nsPluginInstanceOwner::Paint(const 
   NPEvent pluginEvent;
   pluginEvent.event = WM_PAINT;
   pluginEvent.wParam = (uint32)aHPS;
   pluginEvent.lParam = (uint32)&rectl;
   mInstance->HandleEvent(&pluginEvent, nsnull);
 }
 #endif
 
-#ifdef ANDROID
+#ifdef MOZ_WIDGET_ANDROID
 
 void nsPluginInstanceOwner::Paint(gfxContext* aContext,
                                   const gfxRect& aFrameRect,
                                   const gfxRect& aDirtyRect)
 {
   if (!mInstance || !mObjectFrame)
     return;
 
@@ -3551,29 +3551,29 @@ void nsPluginInstanceOwner::UpdateWindow
   mPluginWindow->y = origin.y;
 
   mPluginWindow->clipRect.left = 0;
   mPluginWindow->clipRect.top = 0;
 
   if (mPluginWindowVisible && mPluginDocumentActiveState) {
     mPluginWindow->clipRect.right = mPluginWindow->width;
     mPluginWindow->clipRect.bottom = mPluginWindow->height;
-#ifdef ANDROID
+#ifdef MOZ_WIDGET_ANDROID
     if (mInstance) {
       ANPEvent event;
       event.inSize = sizeof(ANPEvent);
       event.eventType = kLifecycle_ANPEventType;
       event.data.lifecycle.action = kOnScreen_ANPLifecycleAction;
       mInstance->HandleEvent(&event, nsnull);
     }
 #endif
   } else {
     mPluginWindow->clipRect.right = 0;
     mPluginWindow->clipRect.bottom = 0;
-#ifdef ANDROID
+#ifdef MOZ_WIDGET_ANDROID
     if (mInstance) {
       ANPEvent event;
       event.inSize = sizeof(ANPEvent);
       event.eventType = kLifecycle_ANPEventType;
       event.data.lifecycle.action = kOffScreen_ANPLifecycleAction;
       mInstance->HandleEvent(&event, nsnull);
     }
     RemovePluginView();
--- a/dom/plugins/ipc/PluginLibrary.h
+++ b/dom/plugins/ipc/PluginLibrary.h
@@ -73,17 +73,17 @@ public:
   /**
    * Inform this library about the nsNPAPIPlugin which owns it. This
    * object will hold a weak pointer to the plugin.
    */
   virtual void SetPlugin(nsNPAPIPlugin* plugin) = 0;
 
   virtual bool HasRequiredFunctions() = 0;
 
-#if defined(XP_UNIX) && !defined(XP_MACOSX)
+#if defined(XP_UNIX) && !defined(XP_MACOSX) && !defined(MOZ_WIDGET_GONK)
   virtual nsresult NP_Initialize(NPNetscapeFuncs* bFuncs, NPPluginFuncs* pFuncs, NPError* error) = 0;
 #else
   virtual nsresult NP_Initialize(NPNetscapeFuncs* bFuncs, NPError* error) = 0;
 #endif
   virtual nsresult NP_Shutdown(NPError* error) = 0;
   virtual nsresult NP_GetMIMEDescription(const char** mimeDesc) = 0;
   virtual nsresult NP_GetValue(void *future, NPPVariable aVariable,
                                void *aValue, NPError* error) = 0;
--- a/dom/plugins/ipc/PluginModuleParent.cpp
+++ b/dom/plugins/ipc/PluginModuleParent.cpp
@@ -730,17 +730,17 @@ PluginModuleParent::EndUpdateBackground(
 {
     PluginInstanceParent* i = InstCast(instance);
     if (!i)
         return NS_ERROR_FAILURE;
 
     return i->EndUpdateBackground(aCtx, aRect);
 }
 
-#if defined(XP_UNIX) && !defined(XP_MACOSX)
+#if defined(XP_UNIX) && !defined(XP_MACOSX) && !defined(MOZ_WIDGET_GONK)
 nsresult
 PluginModuleParent::NP_Initialize(NPNetscapeFuncs* bFuncs, NPPluginFuncs* pFuncs, NPError* error)
 {
     PLUGIN_LOG_DEBUG_METHOD;
 
     mNPNIface = bFuncs;
 
     if (mShutdown) {
--- a/dom/plugins/ipc/PluginModuleParent.h
+++ b/dom/plugins/ipc/PluginModuleParent.h
@@ -271,17 +271,17 @@ private:
     virtual nsresult BeginUpdateBackground(NPP instance,
                                            const nsIntRect& aRect,
                                            gfxContext** aCtx);
     NS_OVERRIDE
     virtual nsresult EndUpdateBackground(NPP instance,
                                          gfxContext* aCtx,
                                          const nsIntRect& aRect);
 
-#if defined(XP_UNIX) && !defined(XP_MACOSX)
+#if defined(XP_UNIX) && !defined(XP_MACOSX) && !defined(MOZ_WIDGET_GONK)
     virtual nsresult NP_Initialize(NPNetscapeFuncs* bFuncs, NPPluginFuncs* pFuncs, NPError* error);
 #else
     virtual nsresult NP_Initialize(NPNetscapeFuncs* bFuncs, NPError* error);
 #endif
     virtual nsresult NP_Shutdown(NPError* error);
     virtual nsresult NP_GetMIMEDescription(const char** mimeDesc);
     virtual nsresult NP_GetValue(void *future, NPPVariable aVariable,
                                  void *aValue, NPError* error);
--- a/dom/src/geolocation/nsGeolocation.cpp
+++ b/dom/src/geolocation/nsGeolocation.cpp
@@ -79,17 +79,17 @@
 #ifdef MOZ_MAEMO_LIBLOCATION
 #include "MaemoLocationProvider.h"
 #endif
 
 #ifdef MOZ_ENABLE_QTMOBILITY
 #include "QTMLocationProvider.h"
 #endif
 
-#ifdef ANDROID
+#ifdef MOZ_WIDGET_ANDROID
 #include "AndroidLocationProvider.h"
 #endif
 
 #include "nsIDOMDocument.h"
 #include "nsIDocument.h"
 
 // Some limit to the number of get or watch geolocation requests
 // that a window can make.
@@ -590,17 +590,17 @@ nsresult nsGeolocationService::Init()
 #endif
 
 #ifdef MOZ_ENABLE_QTMOBILITY
   provider = new QTMLocationProvider();
   if (provider)
     mProviders.AppendObject(provider);
 #endif
 
-#ifdef ANDROID
+#ifdef MOZ_WIDGET_ANDROID
   provider = new AndroidLocationProvider();
   if (provider)
     mProviders.AppendObject(provider);
 #endif
   return NS_OK;
 }
 
 nsGeolocationService::~nsGeolocationService()
--- a/embedding/Makefile.in
+++ b/embedding/Makefile.in
@@ -48,13 +48,13 @@ MODULE       = embed
 
 DIRS = base components browser
 
 ifdef ENABLE_TESTS
 XPCSHELL_TESTS = tests/unit
 DIRS += test
 endif
 
-ifeq ($(OS_TARGET),Android)
+ifeq ($(MOZ_WIDGET_TOOLKIT),android)
 DIRS += android
 endif
 
 include $(topsrcdir)/config/rules.mk
--- a/gfx/cairo/cairo/src/Makefile.in
+++ b/gfx/cairo/cairo/src/Makefile.in
@@ -200,17 +200,17 @@ CPPSRCS += cairo-beos-surface.cpp
 EXPORTS_cairo += cairo-beos.h
 endif
 
 ifeq ($(MOZ_WIDGET_TOOLKIT),gtk2)
 CSRCS   += $(PSPDF_BASE_CSRCS) $(PDF_CSRCS) $(PS_CSRCS)
 EXPORTS_cairo += $(PDF_EXPORTS) $(PS_EXPORTS)
 endif
 
-ifeq ($(MOZ_WIDGET_TOOLKIT),android)
+ifneq (,$(filter android gonk,$(MOZ_WIDGET_TOOLKIT)))
 CSRCS   += $(PSPDF_BASE_CSRCS) $(PDF_CSRCS)
 EXPORTS_cairo += $(PDF_EXPORTS)
 endif
 
 ifeq ($(MOZ_WIDGET_TOOLKIT),qt)
 CPPSRCS += cairo-qt-surface.cpp
 CSRCS   += $(PSPDF_BASE_CSRCS) $(PDF_CSRCS) 
 EXPORTS_cairo += cairo-qt.h
--- a/gfx/src/Makefile.in
+++ b/gfx/src/Makefile.in
@@ -104,16 +104,20 @@ CPPSRCS = \
 ifdef MOZ_X11
 CPPSRCS += X11Util.cpp
 endif
 
 ifeq ($(MOZ_WIDGET_TOOLKIT),android)
 CPPSRCS += nsSystemFontsAndroid.cpp
 endif
 
+ifeq ($(MOZ_WIDGET_TOOLKIT),gonk)
+CPPSRCS += nsSystemFontsAndroid.cpp
+endif
+
 ifeq ($(MOZ_WIDGET_TOOLKIT),cocoa)
 CMMSRCS = nsSystemFontsMac.mm
 endif
 
 ifeq ($(MOZ_WIDGET_TOOLKIT),gtk2)
 CPPSRCS += nsSystemFontsGTK2.cpp
 endif
 
--- a/gfx/src/nsDeviceContext.cpp
+++ b/gfx/src/nsDeviceContext.cpp
@@ -71,17 +71,21 @@ static nsSystemFontsOS2 *gSystemFonts = 
 #elif XP_MACOSX
 #include "nsSystemFontsMac.h"
 #include "gfxQuartzSurface.h"
 static nsSystemFontsMac *gSystemFonts = nsnull;
 #elif defined(MOZ_WIDGET_QT)
 #include "nsSystemFontsQt.h"
 #include "gfxPDFSurface.h"
 static nsSystemFontsQt *gSystemFonts = nsnull;
-#elif defined(ANDROID)
+#elif defined(MOZ_WIDGET_ANDROID)
+#include "nsSystemFontsAndroid.h"
+#include "gfxPDFSurface.h"
+static nsSystemFontsAndroid *gSystemFonts = nsnull;
+#elif defined(MOZ_WIDGET_GONK)
 #include "nsSystemFontsAndroid.h"
 #include "gfxPDFSurface.h"
 static nsSystemFontsAndroid *gSystemFonts = nsnull;
 #else
 #error Need to declare gSystemFonts!
 #endif
 
 using namespace mozilla;
--- a/gfx/thebes/GLContextProviderEGL.cpp
+++ b/gfx/thebes/GLContextProviderEGL.cpp
@@ -47,28 +47,33 @@
 #include <gdk/gdkx.h>
 // we're using default display for now
 #define GET_NATIVE_WINDOW(aWidget) (EGLNativeWindowType)GDK_WINDOW_XID((GdkWindow *) aWidget->GetNativeData(NS_NATIVE_WINDOW))
 #elif defined(MOZ_WIDGET_QT)
 #include <QtOpenGL/QGLContext>
 #define GLdouble_defined 1
 // we're using default display for now
 #define GET_NATIVE_WINDOW(aWidget) (EGLNativeWindowType)static_cast<QWidget*>(aWidget->GetNativeData(NS_NATIVE_SHELLWIDGET))->winId()
+#elif defined(MOZ_WIDGET_GONK)
+#define GET_NATIVE_WINDOW(aWidget) ((EGLNativeWindowType)aWidget->GetNativeData(NS_NATIVE_WINDOW))
 #endif
 
 #if defined(MOZ_X11)
 #include <X11/Xlib.h>
 #include <X11/Xutil.h>
 #include "mozilla/X11Util.h"
 #include "gfxXlibSurface.h"
 #endif
 
 #if defined(ANDROID)
 /* from widget */
+#if defined(MOZ_WIDGET_ANDROID)
 #include "AndroidBridge.h"
+#endif
+#include <android/log.h>
 #define EGL_LIB "/system/lib/libEGL.so"
 #define GLES2_LIB "/system/lib/libGLESv2.so"
 #else
 #define EGL_LIB "/usr/lib/libEGL.so"
 #define GLES2_LIB "/usr/lib/libGLESv2.so"
 #endif
 
 typedef void *EGLNativeDisplayType;
@@ -151,16 +156,20 @@ public:
 #include "gfxCrashReporterUtils.h"
 
 #ifdef MOZ_PLATFORM_MAEMO
 static bool gUseBackingSurface = true;
 #else
 static bool gUseBackingSurface = false;
 #endif
 
+#ifdef MOZ_WIDGET_GONK
+extern nsIntRect gScreenBounds;
+#endif
+
 namespace mozilla {
 namespace gl {
 
 typedef int EGLint;
 typedef unsigned int EGLBoolean;
 typedef unsigned int EGLenum;
 typedef void *EGLConfig;
 typedef void *EGLContext;
@@ -295,16 +304,20 @@ public:
     typedef EGLBoolean (GLAPIENTRY * pfnBindTexImage)(EGLDisplay, EGLSurface surface, EGLint buffer);
     pfnBindTexImage fBindTexImage;
     typedef EGLBoolean (GLAPIENTRY * pfnReleaseTexImage)(EGLDisplay, EGLSurface surface, EGLint buffer);
     pfnReleaseTexImage fReleaseTexImage;
     typedef EGLImageKHR (GLAPIENTRY * pfnCreateImageKHR)(EGLDisplay dpy, EGLContext ctx, EGLenum target, EGLClientBuffer buffer, const EGLint *attrib_list);
     pfnCreateImageKHR fCreateImageKHR;
     typedef EGLBoolean (GLAPIENTRY * pfnDestroyImageKHR)(EGLDisplay dpy, EGLImageKHR image);
     pfnDestroyImageKHR fDestroyImageKHR;
+#ifdef MOZ_WIDGET_GONK
+    typedef EGLBoolean (GLAPIENTRY * pfnSetSwapRectangleANDROID)(EGLDisplay dpy, EGLSurface surface, EGLint left, EGLint top, EGLint width, EGLint height);
+    pfnSetSwapRectangleANDROID fSetSwapRectangleANDROID;
+#endif
 
     // New extension which allow us to lock texture and get raw image pointer
     typedef EGLBoolean (GLAPIENTRY * pfnLockSurfaceKHR)(EGLDisplay dpy, EGLSurface surface, const EGLint *attrib_list);
     pfnLockSurfaceKHR fLockSurfaceKHR;
     typedef EGLBoolean (GLAPIENTRY * pfnUnlockSurfaceKHR)(EGLDisplay dpy, EGLSurface surface);
     pfnUnlockSurfaceKHR fUnlockSurfaceKHR;
     typedef EGLBoolean (GLAPIENTRY * pfnQuerySurface)(EGLDisplay dpy, EGLSurface surface, EGLint attribute, EGLint *value);
     pfnQuerySurface fQuerySurface;
@@ -391,16 +404,19 @@ public:
             SYMBOL(GetProcAddress),
             SYMBOL(SwapBuffers),
             SYMBOL(CopyBuffers),
             SYMBOL(QueryString),
             SYMBOL(QueryContext),
             SYMBOL(BindTexImage),
             SYMBOL(ReleaseTexImage),
             SYMBOL(QuerySurface),
+#ifdef MOZ_WIDGET_GONK
+            SYMBOL(SetSwapRectangleANDROID),
+#endif
             { NULL, { NULL } }
         };
 
         if (!LibrarySymbolLoader::LoadSymbols(mEGLLibrary, &earlySymbols[0])) {
             NS_WARNING("Couldn't find required entry points in EGL library (early init)");
             return false;
         }
 
@@ -591,17 +607,17 @@ public:
 
     void DumpEGLConfigs() {
         int nc = 0;
         fGetConfigs(mEGLDisplay, NULL, 0, &nc);
         EGLConfig *ec = new EGLConfig[nc];
         fGetConfigs(mEGLDisplay, ec, nc, &nc);
 
         for (int i = 0; i < nc; ++i) {
-            printf_stderr ("========= EGL Config %d ========\n");
+            printf_stderr ("========= EGL Config %d ========\n", i);
             DumpEGLConfig(ec[i]);
         }
 
         delete [] ec;
     }
 
 private:
     bool mInitialized;
@@ -864,16 +880,17 @@ public:
         default:
             return nsnull;
         }
     }
 
     bool SwapBuffers()
     {
         if (mSurface && !mPlatformContext) {
+            //sEGLLibrary.fSetSwapRectangleANDROID(EGL_DISPLAY(), mSurface, 0, 0, gScreenBounds.width, gScreenBounds.height);
             return sEGLLibrary.fSwapBuffers(EGL_DISPLAY(), mSurface);
         } else {
             return false;
         }
     }
     // GLContext interface - returns Tiled Texture Image in our case
     virtual already_AddRefed<TextureImage>
     CreateTextureImage(const nsIntSize& aSize,
@@ -1869,31 +1886,38 @@ CreateSurfaceForWindow(nsIWidget *aWidge
 {
     EGLSurface surface;
 
 
 #ifdef DEBUG
     sEGLLibrary.DumpEGLConfig(config);
 #endif
 
-#ifdef ANDROID
+#ifdef MOZ_WIDGET_ANDROID
     // On Android, we have to ask Java to make the eglCreateWindowSurface
     // call for us.  See GLHelpers.java for a description of why.
     //
     // We also only have one true "window", so we just use it directly and ignore
     // what was passed in.
     printf_stderr("... requesting window surface from bridge\n");
     surface = mozilla::AndroidBridge::Bridge()->
         CallEglCreateWindowSurface(EGL_DISPLAY(), config,
                                    mozilla::AndroidBridge::Bridge()->SurfaceView());
     printf_stderr("got surface %p\n", surface);
 #else
     surface = sEGLLibrary.fCreateWindowSurface(EGL_DISPLAY(), config, GET_NATIVE_WINDOW(aWidget), 0);
 #endif
 
+#ifdef MOZ_WIDGET_GONK
+    gScreenBounds.x = 0;
+    gScreenBounds.y = 0;
+    sEGLLibrary.fQuerySurface(EGL_DISPLAY(), surface, LOCAL_EGL_WIDTH, &gScreenBounds.width);
+    sEGLLibrary.fQuerySurface(EGL_DISPLAY(), surface, LOCAL_EGL_HEIGHT, &gScreenBounds.height);
+#endif
+
     return surface;
 }
 
 const char*
 GetVendor()
 {
     if (!sEGLLibrary.EnsureInitialized()) {
         return nsnull;
--- a/gfx/thebes/Makefile.in
+++ b/gfx/thebes/Makefile.in
@@ -59,16 +59,24 @@ EXPORTS	= \
 ifeq ($(MOZ_WIDGET_TOOLKIT),android)
 EXPORTS += \
 	gfxAndroidPlatform.h \
 	gfxFT2Fonts.h \
 	gfxFT2FontBase.h \
 	$(NULL)
 endif
 
+ifeq ($(MOZ_WIDGET_TOOLKIT),gonk)
+EXPORTS += \
+	gfxAndroidPlatform.h \
+	gfxFT2Fonts.h \
+	gfxFT2FontBase.h \
+	$(NULL)
+endif
+
 ifeq ($(MOZ_WIDGET_TOOLKIT),cocoa)
 EXPORTS += \
 	gfxPlatformMac.h \
 	gfxQuartzSurface.h \
 	gfxQuartzImageSurface.h \
 	gfxQuartzPDFSurface.h \
 	gfxQuartzNativeDrawing.h \
 	$(NULL)
@@ -237,16 +245,31 @@ CPPSRCS += \
 	gfxFT2FontBase.cpp \
 	gfxFT2Utils.cpp \
 	gfxFT2FontList.cpp \
 	gfxPDFSurface.cpp \
 	nsUnicodeRange.cpp \
 	$(NULL)
 endif
 
+ifeq ($(MOZ_WIDGET_TOOLKIT),gonk)
+EXPORTS	+= \
+	gfxPDFSurface.h \
+	$(NULL)
+CPPSRCS += \
+	gfxAndroidPlatform.cpp \
+	gfxFT2Fonts.cpp \
+	gfxFT2FontBase.cpp \
+	gfxFT2Utils.cpp \
+	gfxFT2FontList.cpp \
+	gfxPDFSurface.cpp \
+	nsUnicodeRange.cpp \
+	$(NULL)
+endif
+
 ifeq ($(MOZ_WIDGET_TOOLKIT),os2)
 CPPSRCS	+=	gfxOS2Fonts.cpp \
 		gfxOS2Platform.cpp \
 		gfxOS2Surface.cpp \
 		nsUnicodeRange.cpp \
 		gfxFontconfigUtils.cpp \
 		$(NULL)
 CPPSRCS +=	gfxPDFSurface.cpp
@@ -349,16 +372,20 @@ else
 GL_PROVIDER = GLX
 endif
 endif
 
 ifeq ($(MOZ_WIDGET_TOOLKIT),android)
 GL_PROVIDER = EGL
 endif
 
+ifeq ($(MOZ_WIDGET_TOOLKIT),gonk)
+GL_PROVIDER = EGL
+endif
+
 # Mac is a special snowflake
 ifeq ($(GL_PROVIDER),CGL)
 CMMSRCS += GLContextProvider$(GL_PROVIDER).mm
 else
 CPPSRCS += GLContextProvider$(GL_PROVIDER).cpp
 endif
 
 # Win32 is a special snowflake, for ANGLE
@@ -375,16 +402,20 @@ DEFINES := $(filter-out -DUNICODE,$(DEFI
 
 CXXFLAGS += $(MOZ_CAIRO_CFLAGS) $(TK_CFLAGS)
 CFLAGS += $(MOZ_CAIRO_CFLAGS) $(TK_CFLAGS)
 
 ifeq ($(MOZ_WIDGET_TOOLKIT),android)
 CXXFLAGS += $(CAIRO_FT_CFLAGS)
 endif
 
+ifeq ($(MOZ_WIDGET_TOOLKIT),gonk)
+CXXFLAGS += $(CAIRO_FT_CFLAGS)
+endif
+
 ifeq ($(MOZ_WIDGET_TOOLKIT),gtk2)
 CXXFLAGS += $(MOZ_PANGO_CFLAGS)
 endif
 
 ifeq ($(MOZ_WIDGET_TOOLKIT),os2)
 CXXFLAGS += $(CAIRO_FT_CFLAGS)
 endif
 
--- a/image/decoders/Makefile.in
+++ b/image/decoders/Makefile.in
@@ -77,15 +77,15 @@ ifeq ($(OS_ARCH),WINNT)
 DIRS = icon/win icon
 endif
 ifeq ($(OS_ARCH),OS2)
 DIRS = icon/os2 icon
 endif
 ifeq (cocoa,$(MOZ_WIDGET_TOOLKIT))
 DIRS = icon/mac icon
 endif
-ifeq ($(OS_TARGET),Android)
+ifeq (android,$(MOZ_WIDGET_TOOLKIT))
 DIRS = icon/android icon
 endif
 
 
 include $(topsrcdir)/config/rules.mk
 
--- a/ipc/chromium/src/base/message_loop.cc
+++ b/ipc/chromium/src/base/message_loop.cc
@@ -22,17 +22,17 @@
 #if defined(OS_LINUX)
 #ifdef MOZ_WIDGET_GTK2
 #include "base/message_pump_glib.h"
 #endif
 #ifdef MOZ_WIDGET_QT
 #include "base/message_pump_qt.h"
 #endif
 #endif
-#ifdef MOZ_WIDGET_ANDROID
+#ifdef ANDROID
 #include "base/message_pump_android.h"
 #endif
 
 #include "MessagePump.h"
 
 using base::Time;
 using base::TimeDelta;
 
--- a/ipc/glue/GeckoChildProcessHost.cpp
+++ b/ipc/glue/GeckoChildProcessHost.cpp
@@ -65,24 +65,24 @@
 #include "mozilla/Omnijar.h"
 #include <sys/stat.h>
 
 #ifdef XP_WIN
 #include "nsIWinTaskbar.h"
 #define NS_TASKBAR_CONTRACTID "@mozilla.org/windows-taskbar;1"
 #endif
 
-#ifdef ANDROID
+#ifdef MOZ_WIDGET_ANDROID
 #include "APKOpen.h"
 #endif
 
 using mozilla::MonitorAutoLock;
 using mozilla::ipc::GeckoChildProcessHost;
 
-#ifdef ANDROID
+#ifdef MOZ_WIDGET_ANDROID
 // Like its predecessor in nsExceptionHandler.cpp, this is
 // the magic number of a file descriptor remapping we must
 // preserve for the child process.
 static const int kMagicAndroidSystemPropFd = 5;
 #endif
 
 static bool
 ShouldHaveDirectoryService()
@@ -441,19 +441,19 @@ GeckoChildProcessHost::PerformAsyncLaunc
     NS_ASSERTION(directoryService, "Expected XPCOM to be available");
     if (directoryService) {
       nsCOMPtr<nsIFile> greDir;
       nsresult rv = directoryService->Get(NS_GRE_DIR, NS_GET_IID(nsIFile), getter_AddRefs(greDir));
       if (NS_SUCCEEDED(rv)) {
         nsCString path;
         greDir->GetNativePath(path);
 # ifdef OS_LINUX
-#  ifdef ANDROID
+#  ifdef MOZ_WIDGET_ANDROID
         path += "/lib";
-#  endif  // ANDROID
+#  endif  // MOZ_WIDGET_ANDROID
         const char *ld_library_path = PR_GetEnv("LD_LIBRARY_PATH");
         nsCString new_ld_lib_path;
         if (ld_library_path && *ld_library_path) {
             new_ld_lib_path.Assign(ld_library_path);
             new_ld_lib_path.AppendLiteral(":");
             new_ld_lib_path.Append(path.get());
             newEnvVars["LD_LIBRARY_PATH"] = new_ld_lib_path.get();
         } else {
@@ -484,17 +484,17 @@ GeckoChildProcessHost::PerformAsyncLaunc
       }
     }
   }
 #endif  // OS_LINUX || OS_MACOSX
 
   FilePath exePath;
   GetPathToBinary(exePath);
 
-#ifdef ANDROID
+#ifdef MOZ_WIDGET_ANDROID
   // The java wrapper unpacks this for us but can't make it executable
   chmod(exePath.value().c_str(), 0700);
   int cacheCount = 0;
   const struct lib_cache_info * cache = getLibraryCache();
   nsCString cacheStr;
   while (cache &&
          cacheCount++ < MAX_LIB_CACHE_ENTRIES &&
          strlen(cache->name)) {
@@ -516,17 +516,17 @@ GeckoChildProcessHost::PerformAsyncLaunc
     mFileMap.push_back(std::pair<int, int>(fd, kMagicAndroidSystemPropFd));
 
     char buf[32];
     char *szptr = strchr(apws, ',');
 
     snprintf(buf, sizeof(buf), "%d%s", kMagicAndroidSystemPropFd, szptr);
     newEnvVars["ANDROID_PROPERTY_WORKSPACE"] = buf;
   }
-#endif  // ANDROID
+#endif  // MOZ_WIDGET_ANDROID
 
   // remap the IPC socket fd to a well-known int, as the OS does for
   // STDOUT_FILENO, for example
   int srcChannelFd, dstChannelFd;
   channel().GetClientFileDescriptorMapping(&srcChannelFd, &dstChannelFd);
   mFileMap.push_back(std::pair<int,int>(srcChannelFd, dstChannelFd));
 
   // no need for kProcessChannelID, the child process inherits the
@@ -584,17 +584,17 @@ GeckoChildProcessHost::PerformAsyncLaunc
   // can't pretend being the child that's forked off.
   std::string mach_connection_name = StringPrintf("org.mozilla.machname.%d",
                                                   base::RandInt(0, std::numeric_limits<int>::max()));
   childArgv.push_back(mach_connection_name.c_str());
 #endif
 
   childArgv.push_back(childProcessType);
 
-#ifdef ANDROID
+#ifdef MOZ_WIDGET_ANDROID
   childArgv.push_back(cacheStr.get());
 #endif
 
   base::LaunchApp(childArgv, mFileMap,
 #if defined(OS_LINUX) || defined(OS_MACOSX)
                   newEnvVars,
 #endif
                   false, &process, arch);
--- a/js/src/configure.in
+++ b/js/src/configure.in
@@ -276,16 +276,70 @@ arm-android-eabi)
 i?86-*android*)
     android_tool_prefix="i686-android-linux"
     ;;
 *)
     android_tool_prefix="$target_os"
     ;;
 esac
 
+MOZ_ARG_WITH_STRING(gonk,
+[  --with-gonk=DIR
+               location of gonk dir],
+    gonkdir=$withval)
+
+if test -n "$gonkdir" ; then
+    kernel_name=`uname -s | tr "[[:upper:]]" "[[:lower:]]"`
+    gonk_toolchain="$gonkdir"/prebuilt/$kernel_name-x86/toolchain/arm-eabi-4.4.3
+
+    dnl set up compilers
+    AS="$gonk_toolchain"/bin/"$android_tool_prefix"-as
+    CC="$gonk_toolchain"/bin/"$android_tool_prefix"-gcc
+    CXX="$gonk_toolchain"/bin/"$android_tool_prefix"-g++
+    CPP="$gonk_toolchain"/bin/"$android_tool_prefix"-cpp
+    LD="$gonk_toolchain"/bin/"$android_tool_prefix"-ld
+    AR="$gonk_toolchain"/bin/"$android_tool_prefix"-ar
+    RANLIB="$gonk_toolchain"/bin/"$android_tool_prefix"-ranlib
+    STRIP="$gonk_toolchain"/bin/"$android_tool_prefix"-strip
+
+    STLPORT_CPPFLAGS="-I$gonkdir/external/stlport/stlport"
+    STLPORT_LIBS="-lstlport"
+
+    CPPFLAGS="-DANDROID -I$gonkdir/bionic/libc/include/ -I$gonkdir/bionic/libc/kernel/common -I$gonkdir/bionic/libc/arch-arm/include -I$gonkdir/bionic/libc/kernel/arch-arm -I$gonkdir/bionic/libm/include -I$gonkdir/frameworks/base/native/include -I$gonkdir/system/core/include -I$gonkdir/bionic $STLPORT_CPPFLAGS $CPPFLAGS"
+    CFLAGS="-mandroid -fno-short-enums -fno-exceptions $CFLAGS"
+    CXXFLAGS="-mandroid -fno-short-enums -fno-exceptions $CXXFLAGS"
+    LIBS="$LIBS $STLPORT_LIBS"
+
+    dnl Add -llog by default, since we use it all over the place.
+    LDFLAGS="-mandroid -L$gonkdir/out/target/product/$GONK_PRODUCT/obj/lib -Wl,-rpath-link=$gonkdir/out/target/product/$GONK_PRODUCT/obj/lib --sysroot=$gonkdir/out/target/product/$GONK_PRODUCT/obj/ -llog $LDFLAGS"
+
+    dnl prevent cross compile section from using these flags as host flags
+    if test -z "$HOST_CPPFLAGS" ; then
+        HOST_CPPFLAGS=" "
+    fi
+    if test -z "$HOST_CFLAGS" ; then
+        HOST_CFLAGS=" "
+    fi
+    if test -z "$HOST_CXXFLAGS" ; then
+        HOST_CXXFLAGS=" "
+    fi
+    if test -z "$HOST_LDFLAGS" ; then
+        HOST_LDFLAGS=" "
+    fi
+
+    # save these for libffi's subconfigure,
+    # which doesn't know how to figure this stuff out on its own
+    ANDROID_CFLAGS="$CFLAGS"
+    ANDROID_CPPFLAGS="$CPPFLAGS"
+    ANDROID_LDFLAGS="$LDFLAGS"
+
+    AC_DEFINE(ANDROID)
+    AC_DEFINE(GONK)
+    CROSS_COMPILE=1
+else
 case "$target" in
 *-android*|*-linuxandroid*)
     if test -z "$android_ndk" ; then
         AC_MSG_ERROR([You must specify --with-android-ndk=/path/to/ndk when targeting Android.])
     fi
 
     if test -z "$android_sdk" ; then
         AC_MSG_ERROR([You must specify --with-android-sdk=/path/to/sdk when targeting Android.])
@@ -398,16 +452,18 @@ case "$target" in
     AC_DEFINE(ANDROID)
     AC_DEFINE_UNQUOTED(ANDROID_VERSION, $android_version)
     AC_SUBST(ANDROID_VERSION)
     CROSS_COMPILE=1
     MOZ_CHROME_FILE_FORMAT=omni
     ;;
 esac
 
+fi
+
 AC_SUBST(ANDROID_NDK)
 AC_SUBST(ANDROID_TOOLCHAIN)
 AC_SUBST(ANDROID_PLATFORM)
 AC_SUBST(ANDROID_SDK)
 AC_SUBST(ANDROID_PLATFORM_TOOLS)
 
 dnl ========================================================
 dnl Checks for compilers.
--- a/js/src/jscntxt.cpp
+++ b/js/src/jscntxt.cpp
@@ -1596,17 +1596,17 @@ JSContext::purge()
         parseMapPool_ = NULL;
     }
 }
 
 #if defined(JS_TRACER) || defined(JS_METHODJIT)
 static bool
 ComputeIsJITBroken()
 {
-#ifndef ANDROID
+#if !defined(ANDROID) || defined(GONK)
     return false;
 #else  // ANDROID
     if (getenv("JS_IGNORE_JIT_BROKENNESS")) {
         return false;
     }
 
     std::string line;
 
--- a/layout/build/nsLayoutModule.cpp
+++ b/layout/build/nsLayoutModule.cpp
@@ -142,17 +142,17 @@ using mozilla::dom::indexedDB::IndexedDa
 #include "nsTextServicesCID.h"
 
 #include "nsScriptSecurityManager.h"
 #include "nsPrincipal.h"
 #include "nsSystemPrincipal.h"
 #include "nsNullPrincipal.h"
 #include "nsNetCID.h"
 #include "nsINodeInfo.h"
-#if defined(ANDROID) || defined(MOZ_PLATFORM_MAEMO)
+#if defined(MOZ_WIDGET_ANDROID) || defined(MOZ_PLATFORM_MAEMO)
 #include "nsHapticFeedback.h"
 #endif
 
 #define NS_EDITORCOMMANDTABLE_CID \
 { 0x4f5e62b8, 0xd659, 0x4156, { 0x84, 0xfc, 0x2f, 0x60, 0x99, 0x40, 0x03, 0x69 }}
 
 #define NS_HAPTICFEEDBACK_CID \
 { 0x1f15dbc8, 0xbfaa, 0x45de, \
@@ -271,22 +271,24 @@ NS_NewXULTreeBuilder(nsISupports* aOuter
 static void Shutdown();
 
 #ifdef MOZ_XTF
 #include "nsIXTFService.h"
 #include "nsIXMLContentBuilder.h"
 #endif
 
 #include "nsGeolocation.h"
+#ifndef MOZ_WIDGET_GONK
 #if defined(XP_UNIX)    || \
     defined(_WINDOWS)   || \
     defined(machintosh) || \
     defined(android)
 #include "nsDeviceMotionSystem.h"
 #endif
+#endif
 #include "nsCSPService.h"
 
 // Transformiix
 /* 5d5d92cd-6bf8-11d9-bf4a-000a95dc234c */
 #define TRANSFORMIIX_NODESET_CID \
 { 0x5d5d92cd, 0x6bf8, 0x11d9, { 0xbf, 0x4a, 0x0, 0x0a, 0x95, 0xdc, 0x23, 0x4c } }
 
 #define TRANSFORMIIX_NODESET_CONTRACTID \
@@ -304,26 +306,28 @@ NS_GENERIC_FACTORY_CONSTRUCTOR_INIT(nsDO
 NS_GENERIC_FACTORY_CONSTRUCTOR(nsFormData)
 NS_GENERIC_FACTORY_CONSTRUCTOR(nsFileDataProtocolHandler)
 NS_GENERIC_FACTORY_CONSTRUCTOR(nsDOMParser)
 NS_GENERIC_FACTORY_SINGLETON_CONSTRUCTOR(nsDOMStorageManager,
                                          nsDOMStorageManager::GetInstance)
 NS_GENERIC_FACTORY_CONSTRUCTOR(nsChannelPolicy)
 NS_GENERIC_FACTORY_SINGLETON_CONSTRUCTOR(IndexedDatabaseManager,
                                          IndexedDatabaseManager::FactoryCreate)
+#ifndef MOZ_WIDGET_GONK
 #if defined(XP_UNIX)    || \
     defined(_WINDOWS)   || \
     defined(machintosh) || \
     defined(android)
 NS_GENERIC_FACTORY_CONSTRUCTOR(nsDeviceMotionSystem)
 #endif
-NS_GENERIC_FACTORY_CONSTRUCTOR_INIT(ThirdPartyUtil, Init)
 #if defined(ANDROID) || defined(MOZ_PLATFORM_MAEMO)
 NS_GENERIC_FACTORY_CONSTRUCTOR(nsHapticFeedback)
 #endif
+#endif
+NS_GENERIC_FACTORY_CONSTRUCTOR_INIT(ThirdPartyUtil, Init)
 
 //-----------------------------------------------------------------------------
 
 // Per bug 209804, it is necessary to observe the "xpcom-shutdown" event and
 // perform shutdown of the layout modules at that time instead of waiting for
 // our module destructor to run.  If we do not do this, then we risk holding
 // references to objects in other component libraries that have already been
 // shutdown (and possibly unloaded if 60709 is ever fixed).
@@ -831,25 +835,27 @@ NS_DEFINE_NAMED_CID(NSCHANNELPOLICY_CID)
 NS_DEFINE_NAMED_CID(NS_SCRIPTSECURITYMANAGER_CID);
 NS_DEFINE_NAMED_CID(NS_PRINCIPAL_CID);
 NS_DEFINE_NAMED_CID(NS_SYSTEMPRINCIPAL_CID);
 NS_DEFINE_NAMED_CID(NS_NULLPRINCIPAL_CID);
 NS_DEFINE_NAMED_CID(NS_SECURITYNAMESET_CID);
 NS_DEFINE_NAMED_CID(THIRDPARTYUTIL_CID);
 NS_DEFINE_NAMED_CID(NS_STRUCTUREDCLONECONTAINER_CID);
 
+#ifndef MOZ_WIDGET_GONK
 #if defined(XP_UNIX)    || \
     defined(_WINDOWS)   || \
     defined(machintosh) || \
     defined(android)
 NS_DEFINE_NAMED_CID(NS_DEVICE_MOTION_CID);
 #endif
 #if defined(ANDROID) || defined(MOZ_PLATFORM_MAEMO)
 NS_DEFINE_NAMED_CID(NS_HAPTICFEEDBACK_CID);
 #endif
+#endif
 
 static const mozilla::Module::CIDEntry kLayoutCIDs[] = {
   XPCONNECT_CIDENTRIES
 #ifdef DEBUG
   { &kNS_FRAME_UTIL_CID, false, NULL, CreateNewFrameUtil },
   { &kNS_LAYOUT_DEBUGGER_CID, false, NULL, CreateNewLayoutDebugger },
 #endif
   { &kNS_FRAMETRAVERSAL_CID, false, NULL, CreateNewFrameTraversal },
@@ -960,25 +966,27 @@ static const mozilla::Module::CIDEntry k
   { &kNS_PARENTPROCESSMESSAGEMANAGER_CID, false, NULL, CreateParentMessageManager },
   { &kNS_CHILDPROCESSMESSAGEMANAGER_CID, false, NULL, CreateChildMessageManager },
   { &kNSCHANNELPOLICY_CID, false, NULL, nsChannelPolicyConstructor },
   { &kNS_SCRIPTSECURITYMANAGER_CID, false, NULL, Construct_nsIScriptSecurityManager },
   { &kNS_PRINCIPAL_CID, false, NULL, nsPrincipalConstructor },
   { &kNS_SYSTEMPRINCIPAL_CID, false, NULL, nsSystemPrincipalConstructor },
   { &kNS_NULLPRINCIPAL_CID, false, NULL, nsNullPrincipalConstructor },
   { &kNS_SECURITYNAMESET_CID, false, NULL, nsSecurityNameSetConstructor },
+#ifndef MOZ_WIDGET_GONK
 #if defined(XP_UNIX)    || \
     defined(_WINDOWS)   || \
     defined(machintosh) || \
     defined(android)
   { &kNS_DEVICE_MOTION_CID, false, NULL, nsDeviceMotionSystemConstructor },
 #endif
 #if defined(ANDROID) || defined(MOZ_PLATFORM_MAEMO)
   { &kNS_HAPTICFEEDBACK_CID, false, NULL, nsHapticFeedbackConstructor },
 #endif
+#endif
   { &kTHIRDPARTYUTIL_CID, false, NULL, ThirdPartyUtilConstructor },
   { &kNS_STRUCTUREDCLONECONTAINER_CID, false, NULL, nsStructuredCloneContainerConstructor },
   { NULL }
 };
 
 static const mozilla::Module::ContractIDEntry kLayoutContracts[] = {
   XPCONNECT_CONTRACTS
   { "@mozilla.org/layout/xul-boxobject;1", &kNS_BOXOBJECT_CID },
@@ -1087,25 +1095,27 @@ static const mozilla::Module::ContractID
   { NS_CHILDPROCESSMESSAGEMANAGER_CONTRACTID, &kNS_CHILDPROCESSMESSAGEMANAGER_CID },
   { NSCHANNELPOLICY_CONTRACTID, &kNSCHANNELPOLICY_CID },
   { NS_SCRIPTSECURITYMANAGER_CONTRACTID, &kNS_SCRIPTSECURITYMANAGER_CID },
   { NS_GLOBAL_CHANNELEVENTSINK_CONTRACTID, &kNS_SCRIPTSECURITYMANAGER_CID },
   { NS_PRINCIPAL_CONTRACTID, &kNS_PRINCIPAL_CID },
   { NS_SYSTEMPRINCIPAL_CONTRACTID, &kNS_SYSTEMPRINCIPAL_CID },
   { NS_NULLPRINCIPAL_CONTRACTID, &kNS_NULLPRINCIPAL_CID },
   { NS_SECURITYNAMESET_CONTRACTID, &kNS_SECURITYNAMESET_CID },
+#ifndef MOZ_WIDGET_GONK
 #if defined(XP_UNIX)    || \
     defined(_WINDOWS)   || \
     defined(machintosh) || \
     defined(android)
   { NS_DEVICE_MOTION_CONTRACTID, &kNS_DEVICE_MOTION_CID },
 #endif
 #if defined(ANDROID) || defined(MOZ_PLATFORM_MAEMO)
   { "@mozilla.org/widget/hapticfeedback;1", &kNS_HAPTICFEEDBACK_CID },
 #endif
+#endif
   { THIRDPARTYUTIL_CONTRACTID, &kTHIRDPARTYUTIL_CID },
   { NS_STRUCTUREDCLONECONTAINER_CONTRACTID, &kNS_STRUCTUREDCLONECONTAINER_CID },
   { NULL }
 };
 
 static const mozilla::Module::CategoryEntry kLayoutCategories[] = {
   XPCONNECT_CATEGORIES
   { JAVASCRIPT_GLOBAL_CONSTRUCTOR_CATEGORY, "Image", NS_HTMLIMGELEMENT_CONTRACTID },
--- a/layout/generic/nsObjectFrame.cpp
+++ b/layout/generic/nsObjectFrame.cpp
@@ -1700,17 +1700,17 @@ nsObjectFrame::BuildLayer(nsDisplayListB
   return layer.forget();
 }
 
 void
 nsObjectFrame::PaintPlugin(nsDisplayListBuilder* aBuilder,
                            nsRenderingContext& aRenderingContext,
                            const nsRect& aDirtyRect, const nsRect& aPluginRect)
 {
-#if defined(ANDROID)
+#if defined(MOZ_WIDGET_ANDROID)
   if (mInstanceOwner) {
     NPWindow *window;
     mInstanceOwner->GetWindow(window);
 
     gfxRect frameGfxRect =
       PresContext()->AppUnitsToGfxUnits(aPluginRect);
     gfxRect dirtyGfxRect =
       PresContext()->AppUnitsToGfxUnits(aDirtyRect);
--- a/media/libsydneyaudio/src/Makefile.in
+++ b/media/libsydneyaudio/src/Makefile.in
@@ -46,17 +46,21 @@ LIBRARY_NAME	= sydneyaudio
 FORCE_STATIC_LIB= 1
 
 ifneq (,$(filter DragonFly FreeBSD GNU GNU_% NetBSD OpenBSD,$(OS_ARCH)))
 CSRCS		= \
 		sydney_audio_oss.c \
 		$(NULL)
 endif
 
-ifeq ($(OS_TARGET),Android)
+ifeq ($(MOZ_WIDGET_TOOLKIT),gonk)
+CSRCS		= \
+		sydney_audio_gonk.c \
+		$(NULL)
+else ifeq ($(MOZ_WIDGET_TOOLKIT),android)
 CSRCS		= \
 		sydney_audio_android.c \
 		$(NULL)
 else ifeq ($(OS_ARCH),Linux)
 CSRCS		= \
 		sydney_audio_alsa.c \
 		$(NULL)
 endif
new file mode 100644
--- /dev/null
+++ b/media/libsydneyaudio/src/sydney_audio_gonk.c
@@ -0,0 +1,315 @@
+/* ***** BEGIN LICENSE BLOCK *****
+ * Version: MPL 1.1/GPL 2.0/LGPL 2.1
+ *
+ * The contents of this file are subject to the Mozilla Public License Version
+ * 1.1 (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ * http://www.mozilla.org/MPL/
+ *
+ * Software distributed under the License is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+ * for the specific language governing rights and limitations under the
+ * License.
+ *
+ * The Initial Developer of the Original Code is
+ * CSIRO
+ * Portions created by the Initial Developer are Copyright (C) 2007
+ * the Initial Developer. All Rights Reserved.
+ *
+ * Contributor(s): Michael Martin
+ *                 Michael Wu <mwu@mozilla.com>
+ *
+ * Alternatively, the contents of this file may be used under the terms of
+ * either the GNU General Public License Version 2 or later (the "GPL"), or
+ * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
+ * in which case the provisions of the GPL or the LGPL are applicable instead
+ * of those above. If you wish to allow use of your version of this file only
+ * under the terms of either the GPL or the LGPL, and not to allow others to
+ * use your version of this file under the terms of the MPL, indicate your
+ * decision by deleting the provisions above and replace them with the notice
+ * and other provisions required by the GPL or the LGPL. If you do not delete
+ * the provisions above, a recipient may use your version of this file under
+ * the terms of any one of the MPL, the GPL or the LGPL.
+ *
+ * ***** END LICENSE BLOCK ***** *
+ */
+
+#include <stdlib.h>
+#include <time.h>
+#include "sydney_audio.h"
+
+#include "android/log.h"
+
+#ifndef ALOG
+#if defined(DEBUG) || defined(FORCE_ALOG)
+#define ALOG(args...)  __android_log_print(ANDROID_LOG_INFO, "Gecko - SYDNEY_AUDIO" , ## args)
+#else
+#define ALOG(args...)
+#endif
+#endif 
+
+/* Gonk implementation based on sydney_audio_mac.c */
+/* XXX This is temporary until we figure out a way to hook ALSA up */
+
+#define NANOSECONDS_IN_MILLISECOND 1000000
+#define MILLISECONDS_PER_SECOND    1000
+
+struct sa_stream {
+  unsigned int rate;
+  unsigned int channels;
+  unsigned int isPaused;
+
+  int64_t lastStartTime;
+  int64_t timePlaying;
+  int64_t amountWritten;
+  unsigned int bufferSize;
+};
+
+/*
+ * -----------------------------------------------------------------------------
+ * Startup and shutdown functions
+ * -----------------------------------------------------------------------------
+ */
+
+int
+sa_stream_create_pcm(
+  sa_stream_t      ** _s,
+  const char        * client_name,
+  sa_mode_t           mode,
+  sa_pcm_format_t     format,
+  unsigned  int       rate,
+  unsigned  int       channels
+) {
+
+  /*
+   * Make sure we return a NULL stream pointer on failure.
+   */
+  if (_s == NULL) {
+    return SA_ERROR_INVALID;
+  }
+  *_s = NULL;
+
+  if (mode != SA_MODE_WRONLY) {
+    return SA_ERROR_NOT_SUPPORTED;
+  }
+  if (format != SA_PCM_FORMAT_S16_NE) {
+    return SA_ERROR_NOT_SUPPORTED;
+  }
+  if (channels != 1 && channels != 2) {
+    return SA_ERROR_NOT_SUPPORTED;
+  }
+
+  /*
+   * Allocate the instance and required resources.
+   */
+  sa_stream_t *s;
+  if ((s = malloc(sizeof(sa_stream_t))) == NULL) {
+    return SA_ERROR_OOM;
+  }
+
+  s->rate        = rate;
+  s->channels    = channels;
+  s->isPaused    = 0;
+
+  s->lastStartTime = 0;
+  s->timePlaying = 0;
+  s->amountWritten = 0;
+
+  s->bufferSize = rate * channels;
+
+  *_s = s;
+  return SA_SUCCESS;
+}
+
+
+int
+sa_stream_open(sa_stream_t *s) {
+
+  if (s == NULL) {
+    return SA_ERROR_NO_INIT;
+  }
+
+  return SA_ERROR_NO_DEVICE;
+}
+
+
+int
+sa_stream_destroy(sa_stream_t *s) {
+
+  if (s == NULL) {
+    return SA_ERROR_NO_INIT;
+  }
+// XXX
+  return SA_SUCCESS;
+}
+
+
+/*
+ * -----------------------------------------------------------------------------
+ * Data read and write functions
+ * -----------------------------------------------------------------------------
+ */
+
+int
+sa_stream_write(sa_stream_t *s, const void *data, size_t nbytes) {
+
+  if (s == NULL) {
+    return SA_ERROR_NO_INIT;
+  }
+  if (nbytes == 0) {
+    return SA_SUCCESS;
+  }
+// XXX
+  return SA_SUCCESS;
+}
+
+
+/*
+ * -----------------------------------------------------------------------------
+ * General query and support functions
+ * -----------------------------------------------------------------------------
+ */
+
+int
+sa_stream_get_write_size(sa_stream_t *s, size_t *size) {
+
+  if (s == NULL) {
+    return SA_ERROR_NO_INIT;
+  }
+
+// XXX
+  return SA_SUCCESS;
+}
+
+
+int
+sa_stream_get_position(sa_stream_t *s, sa_position_t position, int64_t *pos) {
+
+  if (s == NULL) {
+    return SA_ERROR_NO_INIT;
+  }
+
+// XXX
+  return SA_SUCCESS;
+}
+
+
+int
+sa_stream_pause(sa_stream_t *s) {
+
+  if (s == NULL) {
+    return SA_ERROR_NO_INIT;
+  }
+
+// XXX
+  return SA_SUCCESS;
+}
+
+
+int
+sa_stream_resume(sa_stream_t *s) {
+
+  if (s == NULL) {
+    return SA_ERROR_NO_INIT;
+  }
+
+// XXX
+  return SA_SUCCESS;
+}
+
+
+int
+sa_stream_drain(sa_stream_t *s)
+{
+  if (s == NULL) {
+    return SA_ERROR_NO_INIT;
+  }
+
+// XXX
+  return SA_SUCCESS;
+}
+
+
+/*
+ * -----------------------------------------------------------------------------
+ * Extension functions
+ * -----------------------------------------------------------------------------
+ */
+
+int
+sa_stream_set_volume_abs(sa_stream_t *s, float vol) {
+
+  if (s == NULL) {
+    return SA_ERROR_NO_INIT;
+  }
+
+// XXX
+  return SA_SUCCESS;
+}
+
+/*
+ * -----------------------------------------------------------------------------
+ * Unsupported functions
+ * -----------------------------------------------------------------------------
+ */
+#define UNSUPPORTED(func)   func { return SA_ERROR_NOT_SUPPORTED; }
+
+UNSUPPORTED(int sa_stream_create_opaque(sa_stream_t **s, const char *client_name, sa_mode_t mode, const char *codec))
+UNSUPPORTED(int sa_stream_set_write_lower_watermark(sa_stream_t *s, size_t size))
+UNSUPPORTED(int sa_stream_set_read_lower_watermark(sa_stream_t *s, size_t size))
+UNSUPPORTED(int sa_stream_set_write_upper_watermark(sa_stream_t *s, size_t size))
+UNSUPPORTED(int sa_stream_set_read_upper_watermark(sa_stream_t *s, size_t size))
+UNSUPPORTED(int sa_stream_set_channel_map(sa_stream_t *s, const sa_channel_t map[], unsigned int n))
+UNSUPPORTED(int sa_stream_set_xrun_mode(sa_stream_t *s, sa_xrun_mode_t mode))
+UNSUPPORTED(int sa_stream_set_non_interleaved(sa_stream_t *s, int enable))
+UNSUPPORTED(int sa_stream_set_dynamic_rate(sa_stream_t *s, int enable))
+UNSUPPORTED(int sa_stream_set_driver(sa_stream_t *s, const char *driver))
+UNSUPPORTED(int sa_stream_start_thread(sa_stream_t *s, sa_event_callback_t callback))
+UNSUPPORTED(int sa_stream_stop_thread(sa_stream_t *s))
+UNSUPPORTED(int sa_stream_change_device(sa_stream_t *s, const char *device_name))
+UNSUPPORTED(int sa_stream_change_read_volume(sa_stream_t *s, const int32_t vol[], unsigned int n))
+UNSUPPORTED(int sa_stream_change_write_volume(sa_stream_t *s, const int32_t vol[], unsigned int n))
+UNSUPPORTED(int sa_stream_change_rate(sa_stream_t *s, unsigned int rate))
+UNSUPPORTED(int sa_stream_change_meta_data(sa_stream_t *s, const char *name, const void *data, size_t size))
+UNSUPPORTED(int sa_stream_change_user_data(sa_stream_t *s, const void *value))
+UNSUPPORTED(int sa_stream_set_adjust_rate(sa_stream_t *s, sa_adjust_t direction))
+UNSUPPORTED(int sa_stream_set_adjust_nchannels(sa_stream_t *s, sa_adjust_t direction))
+UNSUPPORTED(int sa_stream_set_adjust_pcm_format(sa_stream_t *s, sa_adjust_t direction))
+UNSUPPORTED(int sa_stream_set_adjust_watermarks(sa_stream_t *s, sa_adjust_t direction))
+UNSUPPORTED(int sa_stream_get_mode(sa_stream_t *s, sa_mode_t *access_mode))
+UNSUPPORTED(int sa_stream_get_codec(sa_stream_t *s, char *codec, size_t *size))
+UNSUPPORTED(int sa_stream_get_pcm_format(sa_stream_t *s, sa_pcm_format_t *format))
+UNSUPPORTED(int sa_stream_get_rate(sa_stream_t *s, unsigned int *rate))
+UNSUPPORTED(int sa_stream_get_nchannels(sa_stream_t *s, int *nchannels))
+UNSUPPORTED(int sa_stream_get_user_data(sa_stream_t *s, void **value))
+UNSUPPORTED(int sa_stream_get_write_lower_watermark(sa_stream_t *s, size_t *size))
+UNSUPPORTED(int sa_stream_get_read_lower_watermark(sa_stream_t *s, size_t *size))
+UNSUPPORTED(int sa_stream_get_write_upper_watermark(sa_stream_t *s, size_t *size))
+UNSUPPORTED(int sa_stream_get_read_upper_watermark(sa_stream_t *s, size_t *size))
+UNSUPPORTED(int sa_stream_get_channel_map(sa_stream_t *s, sa_channel_t map[], unsigned int *n))
+UNSUPPORTED(int sa_stream_get_xrun_mode(sa_stream_t *s, sa_xrun_mode_t *mode))
+UNSUPPORTED(int sa_stream_get_non_interleaved(sa_stream_t *s, int *enabled))
+UNSUPPORTED(int sa_stream_get_dynamic_rate(sa_stream_t *s, int *enabled))
+UNSUPPORTED(int sa_stream_get_driver(sa_stream_t *s, char *driver_name, size_t *size))
+UNSUPPORTED(int sa_stream_get_device(sa_stream_t *s, char *device_name, size_t *size))
+UNSUPPORTED(int sa_stream_get_read_volume(sa_stream_t *s, int32_t vol[], unsigned int *n))
+UNSUPPORTED(int sa_stream_get_write_volume(sa_stream_t *s, int32_t vol[], unsigned int *n))
+UNSUPPORTED(int sa_stream_get_meta_data(sa_stream_t *s, const char *name, void*data, size_t *size))
+UNSUPPORTED(int sa_stream_get_adjust_rate(sa_stream_t *s, sa_adjust_t *direction))
+UNSUPPORTED(int sa_stream_get_adjust_nchannels(sa_stream_t *s, sa_adjust_t *direction))
+UNSUPPORTED(int sa_stream_get_adjust_pcm_format(sa_stream_t *s, sa_adjust_t *direction))
+UNSUPPORTED(int sa_stream_get_adjust_watermarks(sa_stream_t *s, sa_adjust_t *direction))
+UNSUPPORTED(int sa_stream_get_state(sa_stream_t *s, sa_state_t *state))
+UNSUPPORTED(int sa_stream_get_event_error(sa_stream_t *s, sa_error_t *error))
+UNSUPPORTED(int sa_stream_get_event_notify(sa_stream_t *s, sa_notify_t *notify))
+UNSUPPORTED(int sa_stream_read(sa_stream_t *s, void *data, size_t nbytes))
+UNSUPPORTED(int sa_stream_read_ni(sa_stream_t *s, unsigned int channel, void *data, size_t nbytes))
+UNSUPPORTED(int sa_stream_write_ni(sa_stream_t *s, unsigned int channel, const void *data, size_t nbytes))
+UNSUPPORTED(int sa_stream_pwrite(sa_stream_t *s, const void *data, size_t nbytes, int64_t offset, sa_seek_t whence))
+UNSUPPORTED(int sa_stream_pwrite_ni(sa_stream_t *s, unsigned int channel, const void *data, size_t nbytes, int64_t offset, sa_seek_t whence))
+UNSUPPORTED(int sa_stream_get_read_size(sa_stream_t *s, size_t *size))
+UNSUPPORTED(int sa_stream_get_volume_abs(sa_stream_t *s, float *vol))
+UNSUPPORTED(int sa_stream_get_min_write(sa_stream_t *s, size_t *size))
+
+const char *sa_strerror(int code) { return NULL; }
+
--- a/memory/mozalloc/Makefile.in
+++ b/memory/mozalloc/Makefile.in
@@ -46,18 +46,23 @@ include $(DEPTH)/config/autoconf.mk
 VISIBILITY_FLAGS=
 STL_FLAGS	=
 ifdef _MSC_VER
 STL_FLAGS	= -D_HAS_EXCEPTIONS=0
 endif
 
 MODULE		= mozalloc
 LIBRARY_NAME	= mozalloc
+DIST_INSTALL 	= 1
+
+ifeq (gonk,$(MOZ_WIDGET_TOOLKIT))
+FORCE_STATIC_LIB= 1
+else
 FORCE_SHARED_LIB= 1
-DIST_INSTALL 	= 1
+endif
 
 ifeq (,$(filter-out OS2,$(OS_ARCH)))
 # The strndup declaration in string.h is in an ifdef __USE_GNU section
 DEFINES		+= -D_GNU_SOURCE
 endif
 
 EXPORTS_NAMESPACES 	= mozilla
 EXPORTS_mozilla 	=			\
--- a/memory/mozutils/Makefile.in
+++ b/memory/mozutils/Makefile.in
@@ -75,20 +75,23 @@ GARBAGE += mozutils.def
 LDFLAGS += -ENTRY:DllMain
 
 ifneq (,$(filter -DEFAULTLIB:mozcrt,$(MOZ_UTILS_LDFLAGS)))
 # Don't install the import library if we use mozcrt
 NO_INSTALL_IMPORT_LIBRARY = 1
 endif
 endif
 
-ifeq (Android, $(OS_TARGET))
+ifeq (android, $(MOZ_WIDGET_TOOLKIT))
 # Add Android linker
 EXTRA_DSO_LDOPTS += $(ZLIB_LIBS)
 SHARED_LIBRARY_LIBS += $(call EXPAND_LIBNAME_PATH,android,$(DEPTH)/other-licenses/android)
+endif
+
+ifeq (Android, $(OS_TARGET))
 WRAP_LDFLAGS =
 endif
 
 include $(topsrcdir)/config/rules.mk
 
 ifdef MOZ_MEMORY
 ifeq (Darwin,$(OS_TARGET))
 LDFLAGS += -init _jemalloc_darwin_init
--- a/mobile/components/build/nsShellService.cpp
+++ b/mobile/components/build/nsShellService.cpp
@@ -43,17 +43,17 @@
 #include <dbus/dbus.h>
 #endif
 
 #ifdef MOZ_WIDGET_QT
 #include <QtGui/QApplication>
 #include <QtGui/QWidget>
 #endif
 
-#ifdef ANDROID
+#ifdef MOZ_WIDGET_ANDROID
 #include "AndroidBridge.h"
 #endif
 
 #include "nsShellService.h"
 #include "nsString.h"
 
 NS_IMPL_ISUPPORTS1(nsShellService, nsIShellService)
 
@@ -87,15 +87,15 @@ nsShellService::SwitchTask()
 }
 
 NS_IMETHODIMP
 nsShellService::CreateShortcut(const nsAString& aTitle, const nsAString& aURI, const nsAString& aIconData, const nsAString& aIntent)
 {
   if (!aTitle.Length() || !aURI.Length() || !aIconData.Length())
     return NS_ERROR_FAILURE;
 
-#if ANDROID
+#if MOZ_WIDGET_ANDROID
   mozilla::AndroidBridge::Bridge()->CreateShortcut(aTitle, aURI, aIconData, aIntent);
   return NS_OK;
 #else
   return NS_ERROR_NOT_IMPLEMENTED;
 #endif
 }
--- a/netwerk/build/nsNetModule.cpp
+++ b/netwerk/build/nsNetModule.cpp
@@ -359,17 +359,17 @@ NS_GENERIC_FACTORY_CONSTRUCTOR_INIT(nsNo
 #include "nsNetworkLinkService.h"
 NS_GENERIC_FACTORY_CONSTRUCTOR_INIT(nsNetworkLinkService, Init)
 #elif defined(MOZ_ENABLE_LIBCONIC)
 #include "nsMaemoNetworkLinkService.h"
 NS_GENERIC_FACTORY_CONSTRUCTOR_INIT(nsMaemoNetworkLinkService, Init)
 #elif defined(MOZ_ENABLE_QTNETWORK)
 #include "nsQtNetworkLinkService.h"
 NS_GENERIC_FACTORY_CONSTRUCTOR_INIT(nsQtNetworkLinkService, Init)
-#elif defined(ANDROID)
+#elif defined(MOZ_WIDGET_ANDROID)
 #include "nsAndroidNetworkLinkService.h"
 NS_GENERIC_FACTORY_CONSTRUCTOR(nsAndroidNetworkLinkService)
 #endif
 
 ///////////////////////////////////////////////////////////////////////////////
 
 #ifdef NECKO_PROTOCOL_ftp
 #include "nsFTPDirListingConv.h"
@@ -796,17 +796,17 @@ NS_DEFINE_NAMED_CID(NS_WEBSOCKETSSLPROTO
 #if defined(XP_WIN)
 NS_DEFINE_NAMED_CID(NS_NETWORK_LINK_SERVICE_CID);
 #elif defined(MOZ_WIDGET_COCOA)
 NS_DEFINE_NAMED_CID(NS_NETWORK_LINK_SERVICE_CID);
 #elif defined(MOZ_ENABLE_LIBCONIC)
 NS_DEFINE_NAMED_CID(NS_NETWORK_LINK_SERVICE_CID);
 #elif defined(MOZ_ENABLE_QTNETWORK)
 NS_DEFINE_NAMED_CID(NS_NETWORK_LINK_SERVICE_CID);
-#elif defined(ANDROID)
+#elif defined(MOZ_WIDGET_ANDROID)
 NS_DEFINE_NAMED_CID(NS_NETWORK_LINK_SERVICE_CID);
 #endif
 NS_DEFINE_NAMED_CID(NS_SERIALIZATION_HELPER_CID);
 NS_DEFINE_NAMED_CID(NS_REDIRECTCHANNELREGISTRAR_CID);
 
 static const mozilla::Module::CIDEntry kNeckoCIDs[] = {
     { &kNS_IOSERVICE_CID, false, NULL, nsIOServiceConstructor },
     { &kNS_STREAMTRANSPORTSERVICE_CID, false, NULL, nsStreamTransportServiceConstructor },
@@ -929,17 +929,17 @@ static const mozilla::Module::CIDEntry k
 #if defined(XP_WIN)
     { &kNS_NETWORK_LINK_SERVICE_CID, false, NULL, nsNotifyAddrListenerConstructor },
 #elif defined(MOZ_WIDGET_COCOA)
     { &kNS_NETWORK_LINK_SERVICE_CID, false, NULL, nsNetworkLinkServiceConstructor },
 #elif defined(MOZ_ENABLE_LIBCONIC)
     { &kNS_NETWORK_LINK_SERVICE_CID, false, NULL, nsMaemoNetworkLinkServiceConstructor },
 #elif defined(MOZ_ENABLE_QTNETWORK)
     { &kNS_NETWORK_LINK_SERVICE_CID, false, NULL, nsQtNetworkLinkServiceConstructor },
-#elif defined(ANDROID)
+#elif defined(MOZ_WIDGET_ANDROID)
     { &kNS_NETWORK_LINK_SERVICE_CID, false, NULL, nsAndroidNetworkLinkServiceConstructor },
 #endif
     { &kNS_SERIALIZATION_HELPER_CID, false, NULL, nsSerializationHelperConstructor },
     { &kNS_REDIRECTCHANNELREGISTRAR_CID, false, NULL, RedirectChannelRegistrarConstructor },
     { NULL }
 };
 
 static const mozilla::Module::ContractIDEntry kNeckoContracts[] = {
@@ -1067,17 +1067,17 @@ static const mozilla::Module::ContractID
 #if defined(XP_WIN)
     { NS_NETWORK_LINK_SERVICE_CONTRACTID, &kNS_NETWORK_LINK_SERVICE_CID },
 #elif defined(MOZ_WIDGET_COCOA)
     { NS_NETWORK_LINK_SERVICE_CONTRACTID, &kNS_NETWORK_LINK_SERVICE_CID },
 #elif defined(MOZ_ENABLE_LIBCONIC)
     { NS_NETWORK_LINK_SERVICE_CONTRACTID, &kNS_NETWORK_LINK_SERVICE_CID },
 #elif defined(MOZ_ENABLE_QTNETWORK)
     { NS_NETWORK_LINK_SERVICE_CONTRACTID, &kNS_NETWORK_LINK_SERVICE_CID },
-#elif defined(ANDROID)
+#elif defined(MOZ_WIDGET_ANDROID)
     { NS_NETWORK_LINK_SERVICE_CONTRACTID, &kNS_NETWORK_LINK_SERVICE_CID },
 #endif
     { NS_SERIALIZATION_HELPER_CONTRACTID, &kNS_SERIALIZATION_HELPER_CID },
     { NS_REDIRECTCHANNELREGISTRAR_CONTRACTID, &kNS_REDIRECTCHANNELREGISTRAR_CID },
     { NULL }
 };
 
 static const mozilla::Module kNeckoModule = {
--- a/netwerk/protocol/device/Makefile.in
+++ b/netwerk/protocol/device/Makefile.in
@@ -46,17 +46,17 @@ LIBRARY_NAME = nkdevice_s
 FORCE_STATIC_LIB = 1
 LIBXUL_LIBRARY = 1
 
 CPPSRCS = \
   nsDeviceChannel.cpp \
   nsDeviceProtocolHandler.cpp \
   $(NULL)
 
-ifeq (Android,$(OS_TARGET))
+ifeq (android,$(MOZ_WIDGET_TOOLKIT))
 CPPSRCS += AndroidCaptureProvider.cpp \
            CameraStreamImpl.cpp \
            $(NULL)
 
 EXPORTS_NAMESPACES = mozilla/net
 
 EXPORTS_mozilla/net += \
   CameraStreamImpl.h  \
--- a/netwerk/protocol/device/nsDeviceChannel.cpp
+++ b/netwerk/protocol/device/nsDeviceChannel.cpp
@@ -36,17 +36,17 @@
  * ***** END LICENSE BLOCK ***** */
 
 #include "plstr.h"
 #include "nsComponentManagerUtils.h"
 #include "nsDeviceChannel.h"
 #include "nsDeviceCaptureProvider.h"
 #include "mozilla/Preferences.h"
 
-#ifdef ANDROID
+#ifdef MOZ_WIDGET_ANDROID
 #include "AndroidCaptureProvider.h"
 #endif
 
 // Copied from image/decoders/icon/nsIconURI.cpp
 // takes a string like ?size=32&contentType=text/html and returns a new string
 // containing just the attribute values. i.e you could pass in this string with
 // an attribute name of "size=", this will return 32
 // Assumption: attribute pairs are separated by &
@@ -135,17 +135,17 @@ nsDeviceChannel::OpenContentStream(bool 
     captureParams.width = buffer.ToInteger(&err);
     if (!captureParams.width)
       captureParams.width = 640;
     extractAttributeValue(spec.get(), "height=", buffer);
     captureParams.height = buffer.ToInteger(&err);
     if (!captureParams.height)
       captureParams.height = 480;
     captureParams.bpp = 32;
-#ifdef ANDROID
+#ifdef MOZ_WIDGET_ANDROID
     capture = GetAndroidCaptureProvider();
 #endif
   } else if (kNotFound != spec.Find(NS_LITERAL_CSTRING("type=video/x-raw-yuv"),
                                     true,
                                     0,
                                     -1)) {
     type.AssignLiteral("video/x-raw-yuv");
     SetContentType(type);
@@ -159,17 +159,17 @@ nsDeviceChannel::OpenContentStream(bool 
       captureParams.width = 640;
     extractAttributeValue(spec.get(), "height=", buffer);
     captureParams.height = buffer.ToInteger(&err);
     if (!captureParams.height)
       captureParams.height = 480;
     captureParams.bpp = 32;
     captureParams.timeLimit = 0;
     captureParams.frameLimit = 60000;
-#ifdef ANDROID
+#ifdef MOZ_WIDGET_ANDROID
     // only enable if "device.camera.enabled" is true.
     if (mozilla::Preferences::GetBool("device.camera.enabled", false) == true)
       capture = GetAndroidCaptureProvider();
 #endif
   } else {
     return NS_ERROR_NOT_IMPLEMENTED;
   }
 
--- a/security/manager/Makefile.in
+++ b/security/manager/Makefile.in
@@ -255,18 +255,24 @@ DEFAULT_GMAKE_FLAGS += \
 	$(NULL)
 
 # Android has pthreads integrated into -lc, so OS_PTHREAD is set to nothing
 ifeq ($(OS_TARGET), Android)
 DEFAULT_GMAKE_FLAGS += \
 	OS_RELEASE="2.6" \
 	OS_PTHREAD= \
 	STANDARDS_CFLAGS="-std=gnu89" \
-	ARCHFLAG="$(CFLAGS) -DCHECK_FORK_GETPID -DRTLD_NOLOAD=0 -DANDROID_VERSION=$(ANDROID_VERSION) -include $(ABS_topsrcdir)/security/manager/android_stub.h" \
 	$(NULL)
+
+ifeq ($(MOZ_WIDGET_TOOLKIT),android)
+DEFAULT_GMAKE_FLAGS += ARCHFLAG="$(CFLAGS) -DCHECK_FORK_GETPID -DRTLD_NOLOAD=0 -DANDROID_VERSION=$(ANDROID_VERSION) -include $(ABS_topsrcdir)/security/manager/android_stub.h"
+else
+DEFAULT_GMAKE_FLAGS += ARCHFLAG="$(CFLAGS) -DCHECK_FORK_GETPID -DRTLD_NOLOAD=0 -include $(ABS_topsrcdir)/security/manager/android_stub.h"
+endif
+
 endif
 endif
 
 ifdef WRAP_LDFLAGS
 DEFAULT_GMAKE_FLAGS += \
 	LDFLAGS="$(LDFLAGS) $(WRAP_LDFLAGS)" \
 	DSO_LDOPTS="-shared $(LDFLAGS) $(WRAP_LDFLAGS)" \
 	$(NULL)
--- a/security/manager/android_stub.h
+++ b/security/manager/android_stub.h
@@ -36,25 +36,27 @@
 
 /* This file allows NSS to build by stubbing out
  * features that aren't provided by Android/Bionic */
 
 #ifndef ANDROID_STUB_H
 #define ANDROID_STUB_H
 
 #include "dlfcn.h"
+#ifdef ANDROID_VERSION
 #if ANDROID_VERSION < 8
 /* because dladdr isn't supported in android 2.1 and older.
  * however, it exists in the android repos so.. maybe someday. */
 typedef struct {
   char *dli_fname;
 } Dl_info;
 
 #define dladdr(foo, bar) 0
 #endif
+#endif
 
 /* sysinfo is defined but not implemented.
  * we may be able to implement it ourselves. */
 #define _SYS_SYSINFO_H_
 
 #include <sys/cdefs.h>
 #include <linux/kernel.h>
 
--- a/toolkit/components/downloads/nsDownloadManager.cpp
+++ b/toolkit/components/downloads/nsDownloadManager.cpp
@@ -78,17 +78,17 @@
 #include "nsDownloadScanner.h"
 #endif
 #endif
 
 #ifdef XP_MACOSX
 #include <CoreFoundation/CoreFoundation.h>
 #endif
 
-#ifdef ANDROID
+#ifdef MOZ_WIDGET_ANDROID
 #include "AndroidBridge.h"
 #endif
 
 using namespace mozilla;
 
 #define DOWNLOAD_MANAGER_BUNDLE "chrome://mozapps/locale/downloads/downloads.properties"
 #define DOWNLOAD_MANAGER_ALERT_ICON "chrome://mozapps/skin/downloads/downloadIcon.png"
 #define PREF_BDM_SHOWALERTONCOMPLETE "browser.download.manager.showAlertOnComplete"
@@ -1173,17 +1173,17 @@ nsDownloadManager::GetDefaultDownloadsDi
     // As maemo does not follow the XDG "standard" (as usually desktop
     // Linux distros do) neither has a working $HOME/Desktop folder
     // for us to fallback into, "$HOME/MyDocs/.documents/" is the folder
     // we found most apropriate to be the default target folder for downloads
     // on the platform.
     rv = dirService->Get(NS_UNIX_XDG_DOCUMENTS_DIR,
                          NS_GET_IID(nsILocalFile),
                          getter_AddRefs(downloadDir));
-#elif defined(ANDROID)
+#elif defined(MOZ_WIDGET_ANDROID)
     // Android doesn't have a $HOME directory, and by default we only have
     // write access to /data/data/org.mozilla.{$APP} and /sdcard
     char* downloadDirPath = getenv("DOWNLOADS_DIRECTORY");
     if (downloadDirPath) {
       rv = NS_NewNativeLocalFile(nsDependentCString(downloadDirPath),
                                  true, getter_AddRefs(downloadDir));
       NS_ENSURE_SUCCESS(rv, rv);
     }
@@ -2249,17 +2249,17 @@ nsDownload::SetState(DownloadState aStat
               alerts->ShowAlertNotification(
                   NS_LITERAL_STRING(DOWNLOAD_MANAGER_ALERT_ICON), title,
                   message, !removeWhenDone, EmptyString(), mDownloadManager,
                   EmptyString());
             }
         }
       }
 
-#if defined(XP_WIN) || defined(XP_MACOSX) || defined(ANDROID)
+#if defined(XP_WIN) || defined(XP_MACOSX) || defined(MOZ_WIDGET_ANDROID)
       nsCOMPtr<nsIFileURL> fileURL = do_QueryInterface(mTarget);
       nsCOMPtr<nsIFile> file;
       nsAutoString path;
 
       if (fileURL &&
           NS_SUCCEEDED(fileURL->GetFile(getter_AddRefs(file))) &&
           file &&
           NS_SUCCEEDED(file->GetPath(path))) {
@@ -2283,17 +2283,17 @@ nsDownload::SetState(DownloadState aStat
         CFStringRef observedObject = ::CFStringCreateWithCString(kCFAllocatorDefault,
                                                  NS_ConvertUTF16toUTF8(path).get(),
                                                  kCFStringEncodingUTF8);
         CFNotificationCenterRef center = ::CFNotificationCenterGetDistributedCenter();
         ::CFNotificationCenterPostNotification(center, CFSTR("com.apple.DownloadFileFinished"),
                                                observedObject, NULL, TRUE);
         ::CFRelease(observedObject);
 #endif
-#ifdef ANDROID
+#ifdef MOZ_WIDGET_ANDROID
         nsCOMPtr<nsIMIMEInfo> mimeInfo;
         nsCAutoString contentType;
         GetMIMEInfo(getter_AddRefs(mimeInfo));
 
         if (mimeInfo)
           mimeInfo->GetMIMEType(contentType);
 
         mozilla::AndroidBridge::Bridge()->ScanMedia(path, contentType);
--- a/toolkit/library/libxul-config.mk
+++ b/toolkit/library/libxul-config.mk
@@ -212,17 +212,17 @@ COMPONENT_LIBS += cookie permissions
 DEFINES += -DMOZ_PERMISSIONS
 endif
 
 ifdef MOZ_UNIVERSALCHARDET
 COMPONENT_LIBS += universalchardet
 DEFINES += -DMOZ_UNIVERSALCHARDET
 endif
 
-ifeq (,$(filter android qt os2 cocoa windows,$(MOZ_WIDGET_TOOLKIT)))
+ifeq (,$(filter android gonk qt os2 cocoa windows,$(MOZ_WIDGET_TOOLKIT)))
 ifdef MOZ_XUL
 COMPONENT_LIBS += fileview
 DEFINES += -DMOZ_FILEVIEW
 endif
 endif
 
 ifdef MOZ_PLACES
 COMPONENT_LIBS += \
@@ -256,16 +256,20 @@ ifneq (,$(filter windows os2 mac cocoa g
 DEFINES += -DICON_DECODER
 COMPONENT_LIBS += imgicon
 endif
 
 ifeq ($(MOZ_WIDGET_TOOLKIT),android)
 COMPONENT_LIBS += widget_android
 endif
 
+ifeq ($(MOZ_WIDGET_TOOLKIT),gonk)
+COMPONENT_LIBS += widget_gonk
+endif
+
 STATIC_LIBS += thebes ycbcr
 
 ifeq ($(MOZ_WIDGET_TOOLKIT),android)
 STATIC_LIBS += profiler
 endif
 
 STATIC_LIBS += angle
 
@@ -360,8 +364,12 @@ endif
 
 ifeq (,$(filter-out cocoa android,$(MOZ_WIDGET_TOOLKIT)))
 EXTRA_DSO_LDOPTS += $(MOZ_SKIA_LIBS)
 endif
 
 ifeq (android,$(MOZ_WIDGET_TOOLKIT))
 OS_LIBS += -lGLESv2
 endif
+
+ifeq (gonk,$(MOZ_WIDGET_TOOLKIT))
+OS_LIBS += -lui
+endif
--- a/toolkit/library/nsStaticXULComponents.cpp
+++ b/toolkit/library/nsStaticXULComponents.cpp
@@ -72,16 +72,18 @@
 #elif defined(XP_OS2)
 #  define WIDGET_MODULES MODULE(nsWidgetOS2Module)
 #elif defined(MOZ_WIDGET_GTK2)
 #  define WIDGET_MODULES MODULE(nsWidgetGtk2Module)
 #elif defined(MOZ_WIDGET_QT)
 #  define WIDGET_MODULES MODULE(nsWidgetQtModule)
 #elif defined(MOZ_WIDGET_ANDROID)
 #  define WIDGET_MODULES MODULE(nsWidgetAndroidModule)
+#elif defined(MOZ_WIDGET_GONK)
+#  define WIDGET_MODULES MODULE(nsWidgetGonkModule)
 #else
 #  error Unknown widget module.
 #endif
 
 #ifdef ICON_DECODER
 #define ICON_MODULE MODULE(nsIconDecoderModule)
 #else
 #define ICON_MODULE
--- a/toolkit/mozapps/installer/packager.mk
+++ b/toolkit/mozapps/installer/packager.mk
@@ -51,17 +51,17 @@ ifeq (,$(filter-out OS2 WINNT, $(OS_ARCH
 MOZ_PKG_FORMAT  = ZIP
 else
 ifeq (,$(filter-out SunOS, $(OS_ARCH)))
    MOZ_PKG_FORMAT  = BZ2
 else
    ifeq (,$(filter-out gtk2 qt, $(MOZ_WIDGET_TOOLKIT)))
       MOZ_PKG_FORMAT  = BZ2
    else
-      ifeq (Android,$(OS_TARGET))
+      ifeq (android,$(MOZ_WIDGET_TOOLKIT))
           MOZ_PKG_FORMAT = APK
       else
           MOZ_PKG_FORMAT = TGZ
       endif
    endif
 endif
 endif
 endif
--- a/toolkit/xre/Makefile.in
+++ b/toolkit/xre/Makefile.in
@@ -123,17 +123,17 @@ CMMSRCS += MacAutoreleasePool.mm
 CPPSRCS += nsCommandLineServiceMac.cpp
 ENABLE_CXX_EXCEPTIONS = 1
 endif
 
 ifdef MOZ_X11
 CPPSRCS += nsX11ErrorHandler.cpp
 endif
 
-ifeq ($(OS_TARGET),Android)
+ifeq ($(MOZ_WIDGET_TOOLKIT),android)
 CPPSRCS += nsAndroidStartup.cpp
 DEFINES += -DANDROID_PACKAGE_NAME='"$(ANDROID_PACKAGE_NAME)"'
 endif
 
 SHARED_LIBRARY_LIBS += ../profile/$(LIB_PREFIX)profile_s.$(LIB_SUFFIX)
 
 ifdef MOZ_ENABLE_XREMOTE
 SHARED_LIBRARY_LIBS += $(DEPTH)/widget/src/xremoteclient/$(LIB_PREFIX)xremote_client_s.$(LIB_SUFFIX)
--- a/toolkit/xre/nsAppRunner.cpp
+++ b/toolkit/xre/nsAppRunner.cpp
@@ -212,17 +212,17 @@ using mozilla::unused;
 #define NS_CRASHREPORTER_CONTRACTID "@mozilla.org/toolkit/crash-reporter;1"
 #include "nsIPrefService.h"
 #endif
 
 #include "base/command_line.h"
 
 #include "mozilla/FunctionTimer.h"
 
-#ifdef ANDROID
+#ifdef MOZ_WIDGET_ANDROID
 #include "AndroidBridge.h"
 #endif
 
 extern PRUint32 gRestartMode;
 extern void InstallSignalHandlers(const char *ProgramName);
 #include "nsX11ErrorHandler.h"
 
 #define FILE_COMPATIBILITY_INFO NS_LITERAL_CSTRING("compatibility.ini")
@@ -1602,17 +1602,17 @@ static nsresult LaunchChild(nsINativeApp
 #else
     gRestartArgc = 1;
     gRestartArgv[gRestartArgc] = nsnull;
 #endif
   }
 
   SaveToEnv("MOZ_LAUNCHED_CHILD=1");
 
-#if defined(ANDROID)
+#if defined(MOZ_WIDGET_ANDROID)
   mozilla::AndroidBridge::Bridge()->ScheduleRestart();
 #else
 #if defined(XP_MACOSX)
   CommandLineServiceMac::SetupMacCommandLine(gRestartArgc, gRestartArgv, true);
   PRUint32 restartMode = 0;
   restartMode = gRestartMode;
   LaunchChildMac(gRestartArgc, gRestartArgv, restartMode);
 #else
@@ -1653,17 +1653,17 @@ static nsresult LaunchChild(nsINativeApp
 
   PRInt32 exitCode;
   PRStatus failed = PR_WaitProcess(process, &exitCode);
   if (failed || exitCode)
     return NS_ERROR_FAILURE;
 #endif // XP_OS2 series
 #endif // WP_WIN
 #endif // WP_MACOSX
-#endif // ANDROID
+#endif // MOZ_WIDGET_ANDROID
 
   return NS_ERROR_LAUNCHED_CHILD_PROCESS;
 }
 
 static const char kProfileProperties[] =
   "chrome://mozapps/locale/profile/profileSelection.properties";
 
 static nsresult
--- a/toolkit/xre/nsXREDirProvider.cpp
+++ b/toolkit/xre/nsXREDirProvider.cpp
@@ -1060,16 +1060,19 @@ nsXREDirProvider::GetUserDataDirectoryHo
     PTIB ptib;
     char appDir[CCHMAXPATH];
 
     DosGetInfoBlocks(&ptib, &ppib);
     DosQueryModuleName(ppib->pib_hmte, CCHMAXPATH, appDir);
     *strrchr(appDir, '\\') = '\0';
     rv = NS_NewNativeLocalFile(nsDependentCString(appDir), true, getter_AddRefs(localDir));
   }
+#elif defined(MOZ_WIDGET_GONK)
+  rv = NS_NewNativeLocalFile(NS_LITERAL_CSTRING("/data/b2g"), PR_TRUE,
+                             getter_AddRefs(localDir));
 #elif defined(XP_UNIX)
   const char* homeDir = getenv("HOME");
   if (!homeDir || !*homeDir)
     return NS_ERROR_FAILURE;
 
   rv = NS_NewNativeLocalFile(nsDependentCString(homeDir), true,
                              getter_AddRefs(localDir));
 #else
--- a/uriloader/exthandler/Makefile.in
+++ b/uriloader/exthandler/Makefile.in
@@ -55,21 +55,25 @@ ifeq ($(MOZ_WIDGET_TOOLKIT),windows)
 OSDIR		= win
 else
 ifeq ($(MOZ_WIDGET_TOOLKIT),cocoa)
 OSDIR		= mac
 else
 ifeq ($(MOZ_WIDGET_TOOLKIT),android)
 OSDIR		= android
 else
+ifeq ($(MOZ_WIDGET_TOOLKIT),gonk)
+OSDIR		= gonk
+else
 OSDIR		= unix
 endif
 endif
 endif
 endif
+endif
 
 VPATH		:= $(srcdir) $(srcdir)/$(OSDIR)
 
 MODULE = exthandler
 LIBRARY_NAME    = exthandler_s
 LIBXUL_LIBRARY  = 1
 
 
new file mode 100644
--- /dev/null
+++ b/uriloader/exthandler/gonk/nsOSHelperAppService.cpp
@@ -0,0 +1,63 @@
+/* -*- Mode: c++; c-basic-offset: 4; tab-width: 20; indent-tabs-mode: nil; -*-
+ * ***** BEGIN LICENSE BLOCK *****
+ * Version: MPL 1.1/GPL 2.0/LGPL 2.1
+ *
+ * The contents of this file are subject to the Mozilla Public License Version
+ * 1.1 (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ * http://www.mozilla.org/MPL/
+ *
+ * Software distributed under the License is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+ * for the specific language governing rights and limitations under the
+ * License.
+ *
+ * The Original Code is Mozilla Gonk code.
+ *
+ * The Initial Developer of the Original Code is Mozilla Foundation.
+ * Portions created by the Initial Developer are Copyright (C) 2011
+ * the Initial Developer. All Rights Reserved.
+ *
+ * Contributor(s):
+ *   Michael Wu <mwu@mozilla.com>
+ *
+ * Alternatively, the contents of this file may be used under the terms of
+ * either the GNU General Public License Version 2 or later (the "GPL"), or
+ * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
+ * in which case the provisions of the GPL or the LGPL are applicable instead
+ * of those above. If you wish to allow use of your version of this file only
+ * under the terms of either the GPL or the LGPL, and not to allow others to
+ * use your version of this file under the terms of the MPL, indicate your
+ * decision by deleting the provisions above and replace them with the notice
+ * and other provisions required by the GPL or the LGPL. If you do not delete
+ * the provisions above, a recipient may use your version of this file under
+ * the terms of any one of the MPL, the GPL or the LGPL.
+ *
+ * ***** END LICENSE BLOCK ***** */
+
+#include "nsOSHelperAppService.h"
+
+nsOSHelperAppService::nsOSHelperAppService() : nsExternalHelperAppService()
+{
+}
+
+nsOSHelperAppService::~nsOSHelperAppService()
+{
+}
+
+already_AddRefed<nsIMIMEInfo>
+nsOSHelperAppService::GetMIMEInfoFromOS(const nsACString& aMIMEType,
+                                        const nsACString& aFileExt,
+                                        bool* aFound)
+{
+    *aFound = false;
+    return nsnull;
+}
+
+nsresult
+nsOSHelperAppService::OSProtocolHandlerExists(const char* aScheme,
+                                              bool* aExists)
+{
+    *aExists = false;
+    return NS_OK;
+}
new file mode 100644
--- /dev/null
+++ b/uriloader/exthandler/gonk/nsOSHelperAppService.h
@@ -0,0 +1,60 @@
+/* -*- Mode: c++; c-basic-offset: 4; tab-width: 20; indent-tabs-mode: nil; -*-
+ * ***** BEGIN LICENSE BLOCK *****
+ * Version: MPL 1.1/GPL 2.0/LGPL 2.1
+ *
+ * The contents of this file are subject to the Mozilla Public License Version
+ * 1.1 (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ * http://www.mozilla.org/MPL/
+ *
+ * Software distributed under the License is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+ * for the specific language governing rights and limitations under the
+ * License.
+ *
+ * The Original Code is Mozilla Gonk code.
+ *
+ * The Initial Developer of the Original Code is Mozilla Foundation.
+ * Portions created by the Initial Developer are Copyright (C) 2011
+ * the Initial Developer. All Rights Reserved.
+ *
+ * Contributor(s):
+ *   Michael Wu <mwu@mozilla.com>
+ *
+ * Alternatively, the contents of this file may be used under the terms of
+ * either the GNU General Public License Version 2 or later (the "GPL"), or
+ * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
+ * in which case the provisions of the GPL or the LGPL are applicable instead
+ * of those above. If you wish to allow use of your version of this file only
+ * under the terms of either the GPL or the LGPL, and not to allow others to
+ * use your version of this file under the terms of the MPL, indicate your
+ * decision by deleting the provisions above and replace them with the notice
+ * and other provisions required by the GPL or the LGPL. If you do not delete
+ * the provisions above, a recipient may use your version of this file under
+ * the terms of any one of the MPL, the GPL or the LGPL.
+ *
+ * ***** END LICENSE BLOCK ***** */
+
+#ifndef nsOSHelperAppService_h
+#define nsOSHelperAppService_h
+
+#include "nsCExternalHandlerService.h"
+#include "nsExternalHelperAppService.h"
+
+class nsOSHelperAppService : public nsExternalHelperAppService
+{
+public:
+    nsOSHelperAppService();
+    virtual ~nsOSHelperAppService();
+
+    virtual already_AddRefed<nsIMIMEInfo>
+    GetMIMEInfoFromOS(const nsACString& aMIMEType,
+                      const nsACString& aFileExt,
+                      bool* aFound);
+
+    virtual NS_HIDDEN_(nsresult)
+    OSProtocolHandlerExists(const char* aScheme,
+                            bool* aExists);
+};
+
+#endif /* nsOSHelperAppService_h */
--- a/uriloader/exthandler/nsExternalHelperAppService.cpp
+++ b/uriloader/exthandler/nsExternalHelperAppService.cpp
@@ -142,17 +142,17 @@
 
 #include "ContentChild.h"
 #include "nsXULAppAPI.h"
 #include "nsPIDOMWindow.h"
 #include "nsIDocShellTreeOwner.h"
 #include "nsIDocShellTreeItem.h"
 #include "ExternalHelperAppChild.h"
 
-#ifdef ANDROID
+#ifdef MOZ_WIDGET_ANDROID
 #include "AndroidBridge.h"
 #endif
 
 #include "mozilla/Preferences.h"
 
 using namespace mozilla;
 
 // Buffer file writes in 32kb chunks
@@ -480,17 +480,17 @@ static nsExtraMimeTypeEntry extraMimeEnt
   { APPLICATION_OCTET_STREAM, "exe,com,bin", "Binary File" },
 #endif
   { APPLICATION_GZIP2, "gz", "gzip" },
   { "application/x-arj", "arj", "ARJ file" },
   { "application/rtf", "rtf", "Rich Text Format File" },
   { APPLICATION_XPINSTALL, "xpi", "XPInstall Install" },
   { APPLICATION_POSTSCRIPT, "ps,eps,ai", "Postscript File" },
   { APPLICATION_XJAVASCRIPT, "js", "Javascript Source File" },
-#ifdef ANDROID
+#ifdef MOZ_WIDGET_ANDROID
   { "application/vnd.android.package-archive", "apk", "Android Package" },
 #endif
   { IMAGE_ART, "art", "ART Image" },
   { IMAGE_BMP, "bmp", "BMP Image" },
   { IMAGE_GIF, "gif", "GIF Image" },
   { IMAGE_ICO, "ico,cur", "ICO Image" },
   { IMAGE_JPG, "jpeg,jpg,jfif,pjpeg,pjp", "JPEG Image" },
   { IMAGE_PNG, "png", "PNG Image" },
--- a/widget/public/Makefile.in
+++ b/widget/public/Makefile.in
@@ -83,17 +83,17 @@ EXPORTS		+= \
 		nsIPrintDialogService.h \
 		$(NULL)
 endif
 
 ifeq ($(MOZ_WIDGET_TOOLKIT),os2)
 EXPORTS		+= nsIDragSessionOS2.h
 endif
 
-ifeq ($(MOZ_WIDGET_TOOLKIT),android)
+ifneq (,$(filter android gonk,$(MOZ_WIDGET_TOOLKIT)))
 EXPORTS		+= \
 		nsIPrintDialogService.h \
 		$(NULL)
 endif
 
 ifneq (,$(filter qt gtk2,$(MOZ_WIDGET_TOOLKIT)))
 EXPORTS		+= \
 		nsIDragSessionGTK.h \
--- a/widget/src/Makefile.in
+++ b/widget/src/Makefile.in
@@ -41,17 +41,17 @@ srcdir		= @srcdir@
 VPATH		= @srcdir@
 
 include $(DEPTH)/config/autoconf.mk
 
 MODULE  = widget
 
 DIRS		= shared xpwidgets
 
-ifneq (,$(filter os2 cocoa qt android,$(MOZ_WIDGET_TOOLKIT)))
+ifneq (,$(filter os2 cocoa qt android gonk,$(MOZ_WIDGET_TOOLKIT)))
 DIRS		+= $(MOZ_WIDGET_TOOLKIT)
 endif
 
 ifeq ($(MOZ_WIDGET_TOOLKIT),windows)
 DIRS		+= windows build
 endif
 
 #
new file mode 100644
--- /dev/null
+++ b/widget/src/gonk/Makefile.in
@@ -0,0 +1,75 @@
+# ***** BEGIN LICENSE BLOCK *****
+# Version: MPL 1.1/GPL 2.0/LGPL 2.1
+#
+# The contents of this file are subject to the Mozilla Public License Version
+# 1.1 (the "License"); you may not use this file except in compliance with
+# the License. You may obtain a copy of the License at
+# http://www.mozilla.org/MPL/
+#
+# Software distributed under the License is distributed on an "AS IS" basis,
+# WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+# for the specific language governing rights and limitations under the
+# License.
+#
+# The Original Code is mozilla.org code.
+#
+# The Initial Developer of the Original Code is
+#   Mozilla Foundation
+# Portions created by the Initial Developer are Copyright (C) 2009-2011
+# the Initial Developer. All Rights Reserved.
+#
+# Contributor(s):
+#   Vladimir Vukicevic <vladimir@pobox.com>
+#
+# Alternatively, the contents of this file may be used under the terms of
+# either the GNU General Public License Version 2 or later (the "GPL"), or
+# the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
+# in which case the provisions of the GPL or the LGPL are applicable instead
+# of those above. If you wish to allow use of your version of this file only
+# under the terms of either the GPL or the LGPL, and not to allow others to
+# use your version of this file under the terms of the MPL, indicate your
+# decision by deleting the provisions above and replace them with the notice
+# and other provisions required by the GPL or the LGPL. If you do not delete
+# the provisions above, a recipient may use your version of this file under
+# the terms of any one of the MPL, the GPL or the LGPL.
+#
+# ***** END LICENSE BLOCK *****
+
+DEPTH           = ../../..
+topsrcdir       = @top_srcdir@
+srcdir          = @srcdir@
+VPATH           = @srcdir@
+
+include $(DEPTH)/config/autoconf.mk
+
+MODULE          = widget
+LIBRARY_NAME    = widget_gonk
+EXPORT_LIBRARY  = 1
+IS_COMPONENT    = 1
+MODULE_NAME     = nsWidgetGonkModule
+GRE_MODULE      = 1
+LIBXUL_LIBRARY  = 1
+
+
+CPPSRCS	= \
+	nsAppShell.cpp \
+	nsWidgetFactory.cpp \
+	nsWindow.cpp \
+	nsLookAndFeel.cpp \
+	nsScreenManagerGonk.cpp \
+	$(NULL)
+
+SHARED_LIBRARY_LIBS = ../xpwidgets/libxpwidgets_s.a
+
+include $(topsrcdir)/config/rules.mk
+
+DEFINES += -D_IMPL_NS_WIDGET
+
+LOCAL_INCLUDES += \
+	-I$(topsrcdir)/widget/src/xpwidgets \
+	-I$(topsrcdir)/widget/src/shared \
+	-I$(topsrcdir)/dom/system/android \
+	-I$(srcdir) \
+	$(NULL)
+
+include $(topsrcdir)/ipc/chromium/chromium-config.mk
new file mode 100644
--- /dev/null
+++ b/widget/src/gonk/nsAppShell.cpp
@@ -0,0 +1,473 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
+/* vim: set ts=4 sw=4 sts=4 tw=80 et: */
+/* ***** BEGIN LICENSE BLOCK *****
+ * Version: MPL 1.1/GPL 2.0/LGPL 2.1
+ *
+ * The contents of this file are subject to the Mozilla Public License Version
+ * 1.1 (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ * http://www.mozilla.org/MPL/
+ *
+ * Software distributed under the License is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+ * for the specific language governing rights and limitations under the
+ * License.
+ *
+ * The Original Code is Gonk.
+ *
+ * The Initial Developer of the Original Code is
+ * the Mozilla Foundation.
+ * Portions created by the Initial Developer are Copyright (C) 2011
+ * the Initial Developer. All Rights Reserved.
+ *
+ * Contributor(s):
+ *   Michael Wu <mwu@mozilla.com>
+ *
+ * Alternatively, the contents of this file may be used under the terms of
+ * either the GNU General Public License Version 2 or later (the "GPL"), or
+ * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
+ * in which case the provisions of the GPL or the LGPL are applicable instead
+ * of those above. If you wish to allow use of your version of this file only
+ * under the terms of either the GPL or the LGPL, and not to allow others to
+ * use your version of this file under the terms of the MPL, indicate your
+ * decision by deleting the provisions above and replace them with the notice
+ * and other provisions required by the GPL or the LGPL. If you do not delete
+ * the provisions above, a recipient may use your version of this file under
+ * the terms of any one of the MPL, the GPL or the LGPL.
+ *
+ * ***** END LICENSE BLOCK ***** */
+
+#define _GNU_SOURCE
+
+#include <dirent.h>
+#include <fcntl.h>
+#include <linux/input.h>
+#include <signal.h>
+#include <sys/epoll.h>
+#include <sys/ioctl.h>
+#include <sys/types.h>
+#include <sys/param.h>
+#include <sys/stat.h>
+#include <unistd.h>
+
+#include "nsAppShell.h"
+#include "nsGkAtoms.h"
+#include "nsGUIEvent.h"
+#include "nsWindow.h"
+#include "nsIObserverService.h"
+#include "mozilla/Services.h"
+
+#include "android/log.h"
+
+#ifndef ABS_MT_TOUCH_MAJOR
+// Taken from include/linux/input.h
+// XXX update the bionic input.h so we don't have to do this!
+#define ABS_MT_TOUCH_MAJOR      0x30    /* Major axis of touching ellipse */
+#define ABS_MT_TOUCH_MINOR      0x31    /* Minor axis (omit if circular) */
+#define ABS_MT_WIDTH_MAJOR      0x32    /* Major axis of approaching ellipse */
+#define ABS_MT_WIDTH_MINOR      0x33    /* Minor axis (omit if circular) */
+#define ABS_MT_ORIENTATION      0x34    /* Ellipse orientation */
+#define ABS_MT_POSITION_X       0x35    /* Center X ellipse position */
+#define ABS_MT_POSITION_Y       0x36    /* Center Y ellipse position */
+#define ABS_MT_TOOL_TYPE        0x37    /* Type of touching device */
+#define ABS_MT_BLOB_ID          0x38    /* Group a set of packets as a blob */
+#define ABS_MT_TRACKING_ID      0x39    /* Unique ID of initiated contact */
+#define ABS_MT_PRESSURE         0x3a    /* Pressure on contact area */
+#define SYN_MT_REPORT           2
+#endif
+
+#define LOG(args...)  __android_log_print(ANDROID_LOG_INFO, "Gonk" , ## args)
+
+using namespace mozilla;
+
+bool gDrawRequest = false;
+static nsAppShell *gAppShell = NULL;
+static int epollfd = 0;
+static int signalfds[2] = {0};
+
+namespace mozilla {
+
+bool ProcessNextEvent()
+{
+    return gAppShell->ProcessNextNativeEvent(true);
+}
+
+void NotifyEvent()
+{
+    gAppShell->NotifyNativeEvent();
+}
+
+}
+
+static void
+pipeHandler(int fd, FdHandler *data)
+{
+    ssize_t len;
+    do {
+        char tmp[32];
+        len = read(fd, tmp, sizeof(tmp));
+    } while (len > 0);
+}
+
+static
+PRUint64 timevalToMS(const struct timeval &time)
+{
+    return time.tv_sec * 1000 + time.tv_usec / 1000;
+}
+
+static void
+sendMouseEvent(PRUint32 msg, struct timeval *time, int x, int y)
+{
+    nsMouseEvent event(true, msg, NULL,
+                       nsMouseEvent::eReal, nsMouseEvent::eNormal);
+
+    event.refPoint.x = x;
+    event.refPoint.y = y;
+    event.time = timevalToMS(*time);
+    event.isShift = false;
+    event.isControl = false;
+    event.isMeta = false;
+    event.isAlt = false;
+    event.button = nsMouseEvent::eLeftButton;
+    if (msg != NS_MOUSE_MOVE)
+        event.clickCount = 1;
+
+    nsWindow::DispatchInputEvent(event);
+    //LOG("Dispatched type %d at %dx%d", msg, x, y);
+}
+
+static void
+multitouchHandler(int fd, FdHandler *data)
+{
+    // The Linux's input documentation (Documentation/input/input.txt)
+    // says that we'll always read a multiple of sizeof(input_event) bytes here.
+    input_event events[16];
+    int event_count = read(fd, events, sizeof(events));
+    if (event_count < 0) {
+        LOG("Error reading in multitouchHandler");
+        return;
+    }
+    MOZ_ASSERT(event_count % sizeof(input_event) == 0);
+
+    event_count /= sizeof(struct input_event);
+
+    for (int i = 0; i < event_count; i++) {
+        input_event *event = &events[i];
+
+        if (event->type == EV_ABS) {
+            if (data->mtState == FdHandler::MT_IGNORE)
+                continue;
+            if (data->mtState == FdHandler::MT_START)
+                data->mtState = FdHandler::MT_COLLECT;
+
+            switch (event->code) {
+            case ABS_MT_TOUCH_MAJOR:
+                data->mtMajor = event->value;
+                break;
+            case ABS_MT_TOUCH_MINOR:
+            case ABS_MT_WIDTH_MAJOR:
+            case ABS_MT_WIDTH_MINOR:
+            case ABS_MT_ORIENTATION:
+            case ABS_MT_TOOL_TYPE:
+            case ABS_MT_BLOB_ID:
+            case ABS_MT_TRACKING_ID:
+            case ABS_MT_PRESSURE:
+                break;
+            case ABS_MT_POSITION_X:
+                data->mtX = event->value;
+                break;
+            case ABS_MT_POSITION_Y:
+                data->mtY = event->value;
+                break;
+            default:
+                LOG("Got unknown event type 0x%04x with code 0x%04x and value %d",
+                    event->type, event->code, event->value);
+            }
+        } else if (event->type == EV_SYN) {
+            switch (event->code) {
+            case SYN_MT_REPORT:
+                if (data->mtState == FdHandler::MT_COLLECT)
+                    data->mtState = FdHandler::MT_IGNORE;
+                break;
+            case SYN_REPORT:
+                if ((!data->mtMajor || data->mtState == FdHandler::MT_START)) {
+                    sendMouseEvent(NS_MOUSE_BUTTON_UP, &event->time,
+                                   data->mtX, data->mtY);
+                    data->mtDown = false;
+                    //LOG("Up mouse event");
+                } else if (!data->mtDown) {
+                    sendMouseEvent(NS_MOUSE_BUTTON_DOWN, &event->time,
+                                   data->mtX, data->mtY);
+                    data->mtDown = true;
+                    //LOG("Down mouse event");
+                } else {
+                    sendMouseEvent(NS_MOUSE_MOVE, &event->time,
+                                   data->mtX, data->mtY);
+                    data->mtDown = true;
+                }
+                data->mtState = FdHandler::MT_START;
+                break;
+            default:
+                LOG("Got unknown event type 0x%04x with code 0x%04x and value %d",
+                    event->type, event->code, event->value);
+            }
+        } else
+            LOG("Got unknown event type 0x%04x with code 0x%04x and value %d",
+                event->type, event->code, event->value);
+    }
+}
+
+static void
+sendKeyEventWithMsg(PRUint32 keyCode, PRUint32 msg, const struct timeval &time)
+{
+    nsKeyEvent event(true, msg, NULL);
+    event.keyCode = keyCode;
+    event.time = timevalToMS(time);
+    nsWindow::DispatchInputEvent(event);
+}
+
+static void
+sendKeyEvent(PRUint32 keyCode, bool keyDown, const struct timeval &time)
+{
+    sendKeyEventWithMsg(keyCode, keyDown ? NS_KEY_DOWN : NS_KEY_UP, time);
+    if (keyDown) {
+        // Send a key press event right after the key down event.
+        sendKeyEventWithMsg(keyCode, NS_KEY_PRESS, time);
+    }
+}
+
+static void
+sendSpecialKeyEvent(nsIAtom *command, const struct timeval &time)
+{
+    nsCommandEvent event(true, nsGkAtoms::onAppCommand, command, NULL);
+    event.time = timevalToMS(time);
+    nsWindow::DispatchInputEvent(event);
+}
+
+static int screenFd = -1;
+static bool sScreenOn = true;
+
+static void
+handlePowerKeyPressed()
+{
+    if (screenFd == -1) {
+        screenFd = open("/sys/power/state", O_RDWR);
+        if (screenFd < 0) {
+            LOG("Unable to open /sys/power/state.");
+            return;
+        }
+    }
+
+    // No idea why the screen-off string is "mem" rather than "off".
+    const char *state = sScreenOn ? "mem" : "on";
+    if (write(screenFd, state, strlen(state)) < 0) {
+        LOG("Unable to write to /sys/power/state.");
+        return;
+    }
+
+    sScreenOn = !sScreenOn;
+}
+
+static void
+keyHandler(int fd, FdHandler *data)
+{
+    input_event events[16];
+    ssize_t bytesRead = read(fd, events, sizeof(events));
+    if (bytesRead < 0) {
+        LOG("Error reading in keyHandler");
+        return;
+    }
+    MOZ_ASSERT(bytesRead % sizeof(input_event) == 0);
+
+    for (unsigned int i = 0; i < bytesRead / sizeof(struct input_event); i++) {
+        const input_event &e = events[i];
+
+        if (e.type == EV_SYN) {
+            // Ignore this event; it just signifies that a key was pressed.
+            continue;
+        }
+
+        if (e.type != EV_KEY) {
+            LOG("Got unknown key event type. type 0x%04x code 0x%04x value %d",
+                e.type, e.code, e.value);
+            continue;
+        }
+
+        if (e.value != 0 && e.value != 1) {
+            LOG("Got unknown key event value. type 0x%04x code 0x%04x value %d",
+                e.type, e.code, e.value);
+            continue;
+        }
+
+        if (!sScreenOn && e.code != KEY_POWER) {
+            LOG("Ignoring key event, because the screen is off. "
+                "type 0x%04x code 0x%04x value %d",
+                e.type, e.code, e.value);
+            continue;
+        }
+
+        bool pressed = e.value == 1;
+        const char* upOrDown = pressed ? "pressed" : "released";
+        switch (e.code) {
+        case KEY_BACK:
+            sendKeyEvent(NS_VK_ESCAPE, pressed, e.time);
+            break;
+        case KEY_MENU:
+            if (!pressed)
+                sendSpecialKeyEvent(nsGkAtoms::Menu, e.time);
+            break;
+        case KEY_SEARCH:
+            if (pressed)
+                sendSpecialKeyEvent(nsGkAtoms::Search, e.time);
+            break;
+        case KEY_HOME:
+            sendKeyEvent(NS_VK_HOME, pressed, e.time);
+            break;
+        case KEY_POWER:
+            LOG("Power key %s", upOrDown);
+            // Ideally, we'd send a NS_VK_SLEEP event here and let the front-end
+            // sort out what to do.  But for now, let's just turn off the screen
+            // ourselves.
+            if (pressed)
+                handlePowerKeyPressed();
+            break;
+        case KEY_VOLUMEUP:
+            if (pressed)
+                sendSpecialKeyEvent(nsGkAtoms::VolumeUp, e.time);
+            break;
+        case KEY_VOLUMEDOWN:
+            if (pressed)
+                sendSpecialKeyEvent(nsGkAtoms::VolumeDown, e.time);
+            break;
+        default:
+            LOG("Got unknown key event code. type 0x%04x code 0x%04x value %d",
+                e.type, e.code, e.value);
+        }
+    }
+}
+
+nsAppShell::nsAppShell()
+    : mNativeCallbackRequest(false)
+    , mHandlers()
+{
+    gAppShell = this;
+}
+
+nsAppShell::~nsAppShell()
+{
+    gAppShell = NULL;
+}
+
+nsresult
+nsAppShell::Init()
+{
+    epoll_event event = {
+        EPOLLIN,
+        { 0 }
+    };
+
+    nsresult rv = nsBaseAppShell::Init();
+    NS_ENSURE_SUCCESS(rv, rv);
+
+    epollfd = epoll_create(16);
+    NS_ENSURE_TRUE(epollfd >= 0, NS_ERROR_UNEXPECTED);
+
+    int ret = pipe2(signalfds, O_NONBLOCK);
+    NS_ENSURE_FALSE(ret, NS_ERROR_UNEXPECTED);
+
+    FdHandler *handler = mHandlers.AppendElement();
+    handler->fd = signalfds[0];
+    handler->func = pipeHandler;
+    event.data.u32 = mHandlers.Length() - 1;
+    ret = epoll_ctl(epollfd, EPOLL_CTL_ADD, signalfds[0], &event);
+    NS_ENSURE_FALSE(ret, NS_ERROR_UNEXPECTED);
+
+    DIR *dir = opendir("/dev/input");
+    NS_ENSURE_TRUE(dir, NS_ERROR_UNEXPECTED);
+
+#define BITSET(bit, flags) (flags[bit >> 3] & (1 << (bit & 0x7)))
+
+    struct dirent *entry;
+    while ((entry = readdir(dir))) {
+        char entryName[64];
+        char entryPath[MAXPATHLEN];
+        if (snprintf(entryPath, sizeof(entryPath),
+                     "/dev/input/%s", entry->d_name) < 0) {
+            LOG("Couldn't generate path while enumerating input devices!");
+            continue;
+        }
+        int fd = open(entryPath, O_RDONLY);
+        if (ioctl(fd, EVIOCGNAME(sizeof(entryName)), entryName) >= 0)
+            LOG("Found device %s - %s", entry->d_name, entryName);
+        else
+            continue;
+
+        FdHandlerCallback handlerFunc = NULL;
+
+        char flags[(NS_MAX(ABS_MAX, KEY_MAX) + 1) / 8];
+        if (ioctl(fd, EVIOCGBIT(EV_ABS, sizeof(flags)), flags) >= 0 &&
+            BITSET(ABS_MT_POSITION_X, flags)) {
+
+            LOG("Found absolute input device");
+            handlerFunc = multitouchHandler;
+        } else if (ioctl(fd, EVIOCGBIT(EV_KEY, sizeof(flags)), flags) >= 0) {
+            LOG("Found key input device");
+            handlerFunc = keyHandler;
+        }
+
+        // Register the handler, if we have one.
+        if (!handlerFunc)
+            continue;
+
+        handler = mHandlers.AppendElement();
+        handler->fd = fd;
+        handler->func = handlerFunc;
+        event.data.u32 = mHandlers.Length() - 1;
+        if (epoll_ctl(epollfd, EPOLL_CTL_ADD, fd, &event))
+            LOG("Failed to add fd to epoll fd");
+    }
+
+    return rv;
+}
+
+void
+nsAppShell::ScheduleNativeEventCallback()
+{
+    mNativeCallbackRequest = true;
+    NotifyEvent();
+}
+
+bool
+nsAppShell::ProcessNextNativeEvent(bool mayWait)
+{
+    epoll_event events[16] = {{ 0 }};
+
+    int event_count;
+    if ((event_count = epoll_wait(epollfd, events, 16,  mayWait ? -1 : 0)) <= 0)
+        return true;
+
+    for (int i = 0; i < event_count; i++)
+        mHandlers[events[i].data.u32].run();
+
+    // NativeEventCallback always schedules more if it needs it
+    // so we can coalesce these.
+    // See the implementation in nsBaseAppShell.cpp for more info
+    if (mNativeCallbackRequest) {
+        mNativeCallbackRequest = false;
+        NativeEventCallback();
+    }
+
+    if (gDrawRequest) {
+        gDrawRequest = false;
+        nsWindow::DoDraw();
+    }
+
+    return true;
+}
+
+void
+nsAppShell::NotifyNativeEvent()
+{
+    write(signalfds[1], "w", 1);
+}
+
new file mode 100644
--- /dev/null
+++ b/widget/src/gonk/nsAppShell.h
@@ -0,0 +1,94 @@
+/* ***** BEGIN LICENSE BLOCK *****
+ * Version: MPL 1.1/GPL 2.0/LGPL 2.1
+ *
+ * The contents of this file are subject to the Mozilla Public License Version
+ * 1.1 (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ * http://www.mozilla.org/MPL/
+ *
+ * Software distributed under the License is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+ * for the specific language governing rights and limitations under the
+ * License.
+ *
+ * The Original Code is Gonk.
+ *
+ * The Initial Developer of the Original Code is
+ * the Mozilla Foundation.
+ * Portions created by the Initial Developer are Copyright (C) 2011
+ * the Initial Developer. All Rights Reserved.
+ *
+ * Contributor(s):
+ *   Michael Wu <mwu@mozilla.com>
+ *
+ * Alternatively, the contents of this file may be used under the terms of
+ * either the GNU General Public License Version 2 or later (the "GPL"), or
+ * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
+ * in which case the provisions of the GPL or the LGPL are applicable instead
+ * of those above. If you wish to allow use of your version of this file only
+ * under the terms of either the GPL or the LGPL, and not to allow others to
+ * use your version of this file under the terms of the MPL, indicate your
+ * decision by deleting the provisions above and replace them with the notice
+ * and other provisions required by the GPL or the LGPL. If you do not delete
+ * the provisions above, a recipient may use your version of this file under
+ * the terms of any one of the MPL, the GPL or the LGPL.
+ *
+ * ***** END LICENSE BLOCK ***** */
+
+#ifndef nsAppShell_h
+#define nsAppShell_h
+
+#include "nsBaseAppShell.h"
+
+namespace mozilla {
+bool ProcessNextEvent();
+void NotifyEvent();
+}
+
+extern bool gDrawRequest;
+
+class FdHandler;
+typedef void(*FdHandlerCallback)(int, FdHandler *);
+
+class FdHandler {
+public:
+    FdHandler() : mtState(MT_START), mtDown(false) { }
+
+    int fd;
+    FdHandlerCallback func;
+    enum mtStates {
+        MT_START,
+        MT_COLLECT,
+        MT_IGNORE
+    } mtState;
+    int mtX, mtY;
+    int mtMajor;
+    bool mtDown;
+
+    void run()
+    {
+        func(fd, this);
+    }
+};
+
+class nsAppShell : public nsBaseAppShell {
+public:
+    nsAppShell();
+
+    nsresult Init();
+    virtual bool ProcessNextNativeEvent(bool maywait);
+
+    void NotifyNativeEvent();
+
+protected:
+    virtual ~nsAppShell();
+
+    virtual void ScheduleNativeEventCallback();
+
+    // This is somewhat racy but is perfectly safe given how the callback works
+    bool mNativeCallbackRequest;
+    nsTArray<FdHandler> mHandlers;
+};
+
+#endif /* nsAppShell_h */
+
new file mode 100644
--- /dev/null
+++ b/widget/src/gonk/nsLookAndFeel.cpp
@@ -0,0 +1,319 @@
+/* -*- Mode: C++; tab-width: 20; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
+/* ***** BEGIN LICENSE BLOCK *****
+ * Version: MPL 1.1/GPL 2.0/LGPL 2.1
+ *
+ * The contents of this file are subject to the Mozilla Public License Version
+ * 1.1 (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ * http://www.mozilla.org/MPL/
+ *
+ * Software distributed under the License is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+ * for the specific language governing rights and limitations under the
+ * License.
+ *
+ * The Original Code is mozilla.org code.
+ *
+ * The Initial Developer of the Original Code is
+ *   Mozilla Foundation
+ * Portions created by the Initial Developer are Copyright (C) 2010
+ * the Initial Developer. All Rights Reserved.
+ *
+ * Contributor(s):
+ *   Vladimir Vukicevic <vladimir@pobox.com>
+ *
+ * Alternatively, the contents of this file may be used under the terms of
+ * either the GNU General Public License Version 2 or later (the "GPL"), or
+ * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
+ * in which case the provisions of the GPL or the LGPL are applicable instead
+ * of those above. If you wish to allow use of your version of this file only
+ * under the terms of either the GPL or the LGPL, and not to allow others to
+ * use your version of this file under the terms of the MPL, indicate your
+ * decision by deleting the provisions above and replace them with the notice
+ * and other provisions required by the GPL or the LGPL. If you do not delete
+ * the provisions above, a recipient may use your version of this file under
+ * the terms of any one of the MPL, the GPL or the LGPL.
+ *
+ * ***** END LICENSE BLOCK ***** */
+
+#include "nsLookAndFeel.h"
+
+nsLookAndFeel::nsLookAndFeel()
+    : nsXPLookAndFeel()
+{
+}
+
+nsLookAndFeel::~nsLookAndFeel()
+{
+}
+
+nsresult
+nsLookAndFeel::NativeGetColor(ColorID aID, nscolor &aColor)
+{
+    nsresult rv = NS_OK;
+
+#define BASE_ACTIVE_COLOR     NS_RGB(0xaa,0xaa,0xaa)
+#define BASE_NORMAL_COLOR     NS_RGB(0xff,0xff,0xff)
+#define BASE_SELECTED_COLOR   NS_RGB(0xaa,0xaa,0xaa)
+#define BG_ACTIVE_COLOR       NS_RGB(0xff,0xff,0xff)
+#define BG_INSENSITIVE_COLOR  NS_RGB(0xaa,0xaa,0xaa)
+#define BG_NORMAL_COLOR       NS_RGB(0xff,0xff,0xff)
+#define BG_PRELIGHT_COLOR     NS_RGB(0xee,0xee,0xee)
+#define BG_SELECTED_COLOR     NS_RGB(0x99,0x99,0x99)
+#define DARK_NORMAL_COLOR     NS_RGB(0x88,0x88,0x88)
+#define FG_INSENSITIVE_COLOR  NS_RGB(0x44,0x44,0x44)
+#define FG_NORMAL_COLOR       NS_RGB(0x00,0x00,0x00)
+#define FG_PRELIGHT_COLOR     NS_RGB(0x77,0x77,0x77)
+#define FG_SELECTED_COLOR     NS_RGB(0xaa,0xaa,0xaa)
+#define LIGHT_NORMAL_COLOR    NS_RGB(0xaa,0xaa,0xaa)
+#define TEXT_ACTIVE_COLOR     NS_RGB(0x99,0x99,0x99)
+#define TEXT_NORMAL_COLOR     NS_RGB(0x00,0x00,0x00)
+#define TEXT_SELECTED_COLOR   NS_RGB(0x00,0x00,0x00)
+
+    switch (aID) {
+        // These colors don't seem to be used for anything anymore in Mozilla
+        // (except here at least TextSelectBackground and TextSelectForeground)
+        // The CSS2 colors below are used.
+    case eColorID_WindowBackground:
+        aColor = BASE_NORMAL_COLOR;
+        break;
+    case eColorID_WindowForeground:
+        aColor = TEXT_NORMAL_COLOR;
+        break;
+    case eColorID_WidgetBackground:
+        aColor = BG_NORMAL_COLOR;
+        break;
+    case eColorID_WidgetForeground:
+        aColor = FG_NORMAL_COLOR;
+        break;
+    case eColorID_WidgetSelectBackground:
+        aColor = BG_SELECTED_COLOR;
+        break;
+    case eColorID_WidgetSelectForeground:
+        aColor = FG_SELECTED_COLOR;
+        break;
+    case eColorID_Widget3DHighlight:
+        aColor = NS_RGB(0xa0,0xa0,0xa0);
+        break;
+    case eColorID_Widget3DShadow:
+        aColor = NS_RGB(0x40,0x40,0x40);
+        break;
+    case eColorID_TextBackground:
+        // not used?
+        aColor = BASE_NORMAL_COLOR;
+        break;
+    case eColorID_TextForeground: 
+        // not used?
+        aColor = TEXT_NORMAL_COLOR;
+        break;
+    case eColorID_TextSelectBackground:
+    case eColorID_IMESelectedRawTextBackground:
+    case eColorID_IMESelectedConvertedTextBackground:
+        // still used
+        aColor = BASE_SELECTED_COLOR;
+        break;
+    case eColorID_TextSelectForeground:
+    case eColorID_IMESelectedRawTextForeground:
+    case eColorID_IMESelectedConvertedTextForeground:
+        // still used
+        aColor = TEXT_SELECTED_COLOR;
+        break;
+    case eColorID_IMERawInputBackground:
+    case eColorID_IMEConvertedTextBackground:
+        aColor = NS_TRANSPARENT;
+        break;
+    case eColorID_IMERawInputForeground:
+    case eColorID_IMEConvertedTextForeground:
+        aColor = NS_SAME_AS_FOREGROUND_COLOR;
+        break;
+    case eColorID_IMERawInputUnderline:
+    case eColorID_IMEConvertedTextUnderline:
+        aColor = NS_SAME_AS_FOREGROUND_COLOR;
+        break;
+    case eColorID_IMESelectedRawTextUnderline:
+    case eColorID_IMESelectedConvertedTextUnderline:
+        aColor = NS_TRANSPARENT;
+        break;
+    case eColorID_SpellCheckerUnderline:
+      aColor = NS_RGB(0xff, 0, 0);
+      break;
+
+        // css2  http://www.w3.org/TR/REC-CSS2/ui.html#system-colors
+    case eColorID_activeborder:
+        // active window border
+        aColor = BG_NORMAL_COLOR;
+        break;
+    case eColorID_activecaption:
+        // active window caption background
+        aColor = BG_NORMAL_COLOR;
+        break;
+    case eColorID_appworkspace:
+        // MDI background color
+        aColor = BG_NORMAL_COLOR;
+        break;
+    case eColorID_background:
+        // desktop background
+        aColor = BG_NORMAL_COLOR;
+        break;
+    case eColorID_captiontext:
+        // text in active window caption, size box, and scrollbar arrow box (!)
+        aColor = FG_NORMAL_COLOR;
+        break;
+    case eColorID_graytext:
+        // disabled text in windows, menus, etc.
+        aColor = FG_INSENSITIVE_COLOR;
+        break;
+    case eColorID_highlight:
+        // background of selected item
+        aColor = BASE_SELECTED_COLOR;
+        break;
+    case eColorID_highlighttext:
+        // text of selected item
+        aColor = TEXT_SELECTED_COLOR;
+        break;
+    case eColorID_inactiveborder:
+        // inactive window border
+        aColor = BG_NORMAL_COLOR;
+        break;
+    case eColorID_inactivecaption:
+        // inactive window caption
+        aColor = BG_INSENSITIVE_COLOR;
+        break;
+    case eColorID_inactivecaptiontext:
+        // text in inactive window caption
+        aColor = FG_INSENSITIVE_COLOR;
+        break;
+    case eColorID_infobackground:
+        // tooltip background color
+        aColor = BG_NORMAL_COLOR;
+        break;
+    case eColorID_infotext:
+        // tooltip text color
+        aColor = TEXT_NORMAL_COLOR;
+        break;
+    case eColorID_menu:
+        // menu background
+        aColor = BG_NORMAL_COLOR;
+        break;
+    case eColorID_menutext:
+        // menu text
+        aColor = TEXT_NORMAL_COLOR;
+        break;
+    case eColorID_scrollbar:
+        // scrollbar gray area
+        aColor = BG_ACTIVE_COLOR;
+        break;
+
+    case eColorID_threedface:
+    case eColorID_buttonface:
+        // 3-D face color
+        aColor = BG_NORMAL_COLOR;
+        break;
+
+    case eColorID_buttontext:
+        // text on push buttons
+        aColor = TEXT_NORMAL_COLOR;
+        break;
+
+    case eColorID_buttonhighlight:
+        // 3-D highlighted edge color
+    case eColorID_threedhighlight:
+        // 3-D highlighted outer edge color
+        aColor = LIGHT_NORMAL_COLOR;
+        break;
+
+    case eColorID_threedlightshadow:
+        // 3-D highlighted inner edge color
+        aColor = BG_NORMAL_COLOR;
+        break;
+
+    case eColorID_buttonshadow:
+        // 3-D shadow edge color
+    case eColorID_threedshadow:
+        // 3-D shadow inner edge color
+        aColor = DARK_NORMAL_COLOR;
+        break;
+
+    case eColorID_threeddarkshadow:
+        // 3-D shadow outer edge color
+        aColor = NS_RGB(0,0,0);
+        break;
+
+    case eColorID_window:
+    case eColorID_windowframe:
+        aColor = BG_NORMAL_COLOR;
+        break;
+
+    case eColorID_windowtext:
+        aColor = FG_NORMAL_COLOR;
+        break;
+
+    case eColorID__moz_eventreerow:
+    case eColorID__moz_field:
+        aColor = BASE_NORMAL_COLOR;
+        break;
+    case eColorID__moz_fieldtext:
+        aColor = TEXT_NORMAL_COLOR;
+        break;
+    case eColorID__moz_dialog:
+        aColor = BG_NORMAL_COLOR;
+        break;
+    case eColorID__moz_dialogtext:
+        aColor = FG_NORMAL_COLOR;
+        break;
+    case eColorID__moz_dragtargetzone:
+        aColor = BG_SELECTED_COLOR;
+        break; 
+    case eColorID__moz_buttondefault:
+        // default button border color
+        aColor = NS_RGB(0,0,0);
+        break;
+    case eColorID__moz_buttonhoverface:
+        aColor = BG_PRELIGHT_COLOR;
+        break;
+    case eColorID__moz_buttonhovertext:
+        aColor = FG_PRELIGHT_COLOR;
+        break;
+    case eColorID__moz_cellhighlight:
+    case eColorID__moz_html_cellhighlight:
+        aColor = BASE_ACTIVE_COLOR;
+        break;
+    case eColorID__moz_cellhighlighttext:
+    case eColorID__moz_html_cellhighlighttext:
+        aColor = TEXT_ACTIVE_COLOR;
+        break;
+    case eColorID__moz_menuhover:
+        aColor = BG_PRELIGHT_COLOR;
+        break;
+    case eColorID__moz_menuhovertext:
+        aColor = FG_PRELIGHT_COLOR;
+        break;
+    case eColorID__moz_oddtreerow:
+        aColor = NS_TRANSPARENT;
+        break;
+    case eColorID__moz_nativehyperlinktext:
+        aColor = NS_SAME_AS_FOREGROUND_COLOR;
+        break;
+    case eColorID__moz_comboboxtext:
+        aColor = TEXT_NORMAL_COLOR;
+        break;
+    case eColorID__moz_combobox:
+        aColor = BG_NORMAL_COLOR;
+        break;
+    case eColorID__moz_menubartext:
+        aColor = TEXT_NORMAL_COLOR;
+        break;
+    case eColorID__moz_menubarhovertext:
+        aColor = FG_PRELIGHT_COLOR;
+        break;
+    default:
+        /* default color is BLACK */
+        aColor = 0;
+        rv = NS_ERROR_FAILURE;
+        break;
+    }
+
+    return rv;
+}
+
+
new file mode 100644
--- /dev/null
+++ b/widget/src/gonk/nsLookAndFeel.h
@@ -0,0 +1,54 @@
+/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
+/* ***** BEGIN LICENSE BLOCK *****
+ * Version: MPL 1.1/GPL 2.0/LGPL 2.1
+ *
+ * The contents of this file are subject to the Mozilla Public License Version
+ * 1.1 (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ * http://www.mozilla.org/MPL/
+ *
+ * Software distributed under the License is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+ * for the specific language governing rights and limitations under the
+ * License.
+ *
+ * The Original Code is mozilla.org code.
+ *
+ * The Initial Developer of the Original Code is
+ * Netscape Communications Corporation.
+ * Portions created by the Initial Developer are Copyright (C) 1998
+ * the Initial Developer. All Rights Reserved.
+ *
+ * Contributor(s):
+ *   Lars Knoll <knoll@kde.org>
+ *   John C. Griggs <johng@corel.com>
+ *
+ * Alternatively, the contents of this file may be used under the terms of
+ * either the GNU General Public License Version 2 or later (the "GPL"), or
+ * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
+ * in which case the provisions of the GPL or the LGPL are applicable instead
+ * of those above. If you wish to allow use of your version of this file only
+ * under the terms of either the GPL or the LGPL, and not to allow others to
+ * use your version of this file under the terms of the MPL, indicate your
+ * decision by deleting the provisions above and replace them with the notice
+ * and other provisions required by the GPL or the LGPL. If you do not delete
+ * the provisions above, a recipient may use your version of this file under
+ * the terms of any one of the MPL, the GPL or the LGPL.
+ *
+ * ***** END LICENSE BLOCK ***** */
+#ifndef __nsLookAndFeel
+#define __nsLookAndFeel
+
+#include "nsXPLookAndFeel.h"
+
+class nsLookAndFeel : public nsXPLookAndFeel
+{
+public:
+    nsLookAndFeel();
+    virtual ~nsLookAndFeel();
+
+protected:
+    virtual nsresult NativeGetColor(ColorID aID, nscolor &aColor);
+};
+
+#endif
new file mode 100644
--- /dev/null
+++ b/widget/src/gonk/nsScreenManagerGonk.cpp
@@ -0,0 +1,133 @@
+/* -*- Mode: C++; tab-width: 40; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
+/* ***** BEGIN LICENSE BLOCK *****
+ * Version: MPL 1.1/GPL 2.0/LGPL 2.1
+ *
+ * The contents of this file are subject to the Mozilla Public License Version
+ * 1.1 (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ * http://www.mozilla.org/MPL/
+ *
+ * Software distributed under the License is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+ * for the specific language governing rights and limitations under the
+ * License.
+ *
+ * The Original Code is mozilla.org code.
+ *
+ * The Initial Developer of the Original Code is
+ *   Mozilla Foundation
+ * Portions created by the Initial Developer are Copyright (C) 2010
+ * the Initial Developer. All Rights Reserved.
+ *
+ * Contributor(s):
+ *   Vladimir Vukicevic <vladimir@pobox.com>
+ *
+ * Alternatively, the contents of this file may be used under the terms of
+ * either of the GNU General Public License Version 2 or later (the "GPL"),
+ * or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
+ * in which case the provisions of the GPL or the LGPL are applicable instead
+ * of those above. If you wish to allow use of your version of this file only
+ * under the terms of either the GPL or the LGPL, and not to allow others to
+ * use your version of this file under the terms of the MPL, indicate your
+ * decision by deleting the provisions above and replace them with the notice
+ * and other provisions required by the GPL or the LGPL. If you do not delete
+ * the provisions above, a recipient may use your version of this file under
+ * the terms of any one of the MPL, the GPL or the LGPL.
+ *
+ * ***** END LICENSE BLOCK ***** */
+
+#include "nsScreenManagerGonk.h"
+#include "nsWindow.h"
+
+using namespace mozilla;
+
+NS_IMPL_ISUPPORTS2(nsScreenGonk, nsIScreen, nsIScreen)
+
+nsScreenGonk::nsScreenGonk(void *nativeScreen)
+{
+}
+
+nsScreenGonk::~nsScreenGonk()
+{
+}
+
+NS_IMETHODIMP
+nsScreenGonk::GetRect(PRInt32 *outLeft,  PRInt32 *outTop,
+                      PRInt32 *outWidth, PRInt32 *outHeight)
+{
+    *outLeft = gScreenBounds.x;
+    *outTop = gScreenBounds.y;
+
+    *outWidth = gScreenBounds.width;
+    *outHeight = gScreenBounds.height;
+
+    return NS_OK;
+}
+
+
+NS_IMETHODIMP
+nsScreenGonk::GetAvailRect(PRInt32 *outLeft,  PRInt32 *outTop,
+                          PRInt32 *outWidth, PRInt32 *outHeight)
+{
+    return GetRect(outLeft, outTop, outWidth, outHeight);
+}
+
+
+
+NS_IMETHODIMP
+nsScreenGonk::GetPixelDepth(PRInt32 *aPixelDepth)
+{
+    // XXX do we need to lie here about 16bpp?  Or
+    // should we actually check and return the right thing?
+    *aPixelDepth = 24;
+    return NS_OK;
+}
+
+
+NS_IMETHODIMP
+nsScreenGonk::GetColorDepth(PRInt32 *aColorDepth)
+{
+    return GetPixelDepth(aColorDepth);
+}
+
+NS_IMPL_ISUPPORTS1(nsScreenManagerGonk, nsIScreenManager)
+
+nsScreenManagerGonk::nsScreenManagerGonk()
+{
+    mOneScreen = new nsScreenGonk(nsnull);
+}
+
+nsScreenManagerGonk::~nsScreenManagerGonk()
+{
+}
+
+NS_IMETHODIMP
+nsScreenManagerGonk::GetPrimaryScreen(nsIScreen **outScreen)
+{
+    NS_IF_ADDREF(*outScreen = mOneScreen.get());
+    return NS_OK;
+}
+
+NS_IMETHODIMP
+nsScreenManagerGonk::ScreenForRect(PRInt32 inLeft,
+                                   PRInt32 inTop,
+                                   PRInt32 inWidth,
+                                   PRInt32 inHeight,
+                                   nsIScreen **outScreen)
+{
+    return GetPrimaryScreen(outScreen);
+}
+
+NS_IMETHODIMP
+nsScreenManagerGonk::ScreenForNativeWidget(void *aWidget, nsIScreen **outScreen)
+{
+    return GetPrimaryScreen(outScreen);
+}
+
+NS_IMETHODIMP
+nsScreenManagerGonk::GetNumberOfScreens(PRUint32 *aNumberOfScreens)
+{
+    *aNumberOfScreens = 1;
+    return NS_OK;
+}
+
new file mode 100644
--- /dev/null
+++ b/widget/src/gonk/nsScreenManagerGonk.h
@@ -0,0 +1,71 @@
+/* -*- Mode: C++; tab-width: 40; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
+/* ***** BEGIN LICENSE BLOCK *****
+ * Version: MPL 1.1/GPL 2.0/LGPL 2.1
+ *
+ * The contents of this file are subject to the Mozilla Public License Version
+ * 1.1 (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ * http://www.mozilla.org/MPL/
+ *
+ * Software distributed under the License is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+ * for the specific language governing rights and limitations under the
+ * License.
+ *
+ * The Original Code is mozilla.org code.
+ *
+ * The Initial Developer of the Original Code is
+ *   Mozilla Foundation
+ * Portions created by the Initial Developer are Copyright (C) 2010
+ * the Initial Developer. All Rights Reserved.
+ *
+ * Contributor(s):
+ *   Vladimir Vukicevic <vladimir@pobox.com>
+ *
+ * Alternatively, the contents of this file may be used under the terms of
+ * either of the GNU General Public License Version 2 or later (the "GPL"),
+ * or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
+ * in which case the provisions of the GPL or the LGPL are applicable instead
+ * of those above. If you wish to allow use of your version of this file only
+ * under the terms of either the GPL or the LGPL, and not to allow others to
+ * use your version of this file under the terms of the MPL, indicate your
+ * decision by deleting the provisions above and replace them with the notice
+ * and other provisions required by the GPL or the LGPL. If you do not delete
+ * the provisions above, a recipient may use your version of this file under
+ * the terms of any one of the MPL, the GPL or the LGPL.
+ *
+ * ***** END LICENSE BLOCK ***** */
+
+#ifndef nsScreenManagerGonk_h___
+#define nsScreenManagerGonk_h___
+
+#include "nsCOMPtr.h"
+
+#include "nsIScreenManager.h"
+#include "nsIScreen.h"
+#include "WidgetUtils.h"
+
+class nsScreenGonk : public nsIScreen
+{
+public:
+    nsScreenGonk(void *nativeScreen);
+    ~nsScreenGonk();
+
+    NS_DECL_ISUPPORTS
+    NS_DECL_NSISCREEN
+};
+
+class nsScreenManagerGonk : public nsIScreenManager
+{
+public:
+    nsScreenManagerGonk();
+    ~nsScreenManagerGonk();
+
+    NS_DECL_ISUPPORTS
+    NS_DECL_NSISCREENMANAGER
+
+protected:
+    nsCOMPtr<nsIScreen> mOneScreen;
+};
+
+#endif /* nsScreenManagerGonk_h___ */
new file mode 100644
--- /dev/null
+++ b/widget/src/gonk/nsWidgetFactory.cpp
@@ -0,0 +1,98 @@
+/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
+/* ***** BEGIN LICENSE BLOCK *****
+ * Version: MPL 1.1/GPL 2.0/LGPL 2.1
+ *
+ * The contents of this file are subject to the Mozilla Public License Version
+ * 1.1 (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ * http://www.mozilla.org/MPL/
+ *
+ * Software distributed under the License is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+ * for the specific language governing rights and limitations under the
+ * License.
+ *
+ * The Original Code is mozilla.org code.
+ *
+ * The Initial Developer of the Original Code is
+ *   Mozilla Foundation
+ * Portions created by the Initial Developer are Copyright (C) 2009-2010
+ * the Initial Developer. All Rights Reserved.
+ *
+ * Contributor(s):
+ *   Vladimir Vukicevic <vladimir@pobox.com>
+ *
+ * Alternatively, the contents of this file may be used under the terms of
+ * either the GNU General Public License Version 2 or later (the "GPL"), or
+ * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
+ * in which case the provisions of the GPL or the LGPL are applicable instead
+ * of those above. If you wish to allow use of your version of this file only
+ * under the terms of either the GPL or the LGPL, and not to allow others to
+ * use your version of this file under the terms of the MPL, indicate your
+ * decision by deleting the provisions above and replace them with the notice
+ * and other provisions required by the GPL or the LGPL. If you do not delete
+ * the provisions above, a recipient may use your version of this file under
+ * the terms of any one of the MPL, the GPL or the LGPL.
+ *
+ * ***** END LICENSE BLOCK ***** */
+
+#include "mozilla/ModuleUtils.h"
+
+#include "nsCOMPtr.h"
+#include "nsWidgetsCID.h"
+#include "nsAppShell.h"
+
+#include "nsWindow.h"
+#include "nsLookAndFeel.h"
+#include "nsAppShellSingleton.h"
+#include "nsScreenManagerGonk.h"
+
+#include "nsHTMLFormatConverter.h"
+#include "nsXULAppAPI.h"
+
+NS_GENERIC_FACTORY_CONSTRUCTOR(nsWindow)
+NS_GENERIC_FACTORY_CONSTRUCTOR(nsScreenManagerGonk)
+NS_GENERIC_FACTORY_CONSTRUCTOR(nsHTMLFormatConverter)
+
+NS_DEFINE_NAMED_CID(NS_APPSHELL_CID);
+NS_DEFINE_NAMED_CID(NS_WINDOW_CID);
+NS_DEFINE_NAMED_CID(NS_CHILD_CID);
+NS_DEFINE_NAMED_CID(NS_SCREENMANAGER_CID);
+NS_DEFINE_NAMED_CID(NS_HTMLFORMATCONVERTER_CID);
+
+static const mozilla::Module::CIDEntry kWidgetCIDs[] = {
+    { &kNS_WINDOW_CID, false, NULL, nsWindowConstructor },
+    { &kNS_CHILD_CID, false, NULL, nsWindowConstructor },
+    { &kNS_APPSHELL_CID, false, NULL, nsAppShellConstructor },
+    { &kNS_SCREENMANAGER_CID, false, NULL, nsScreenManagerGonkConstructor },
+    { &kNS_HTMLFORMATCONVERTER_CID, false, NULL, nsHTMLFormatConverterConstructor },
+    { NULL }
+};
+
+static const mozilla::Module::ContractIDEntry kWidgetContracts[] = {
+    { "@mozilla.org/widgets/window/gonk;1", &kNS_WINDOW_CID },
+    { "@mozilla.org/widgets/child_window/gonk;1", &kNS_CHILD_CID },
+    { "@mozilla.org/widget/appshell/gonk;1", &kNS_APPSHELL_CID },
+    { "@mozilla.org/gfx/screenmanager;1", &kNS_SCREENMANAGER_CID },
+    { "@mozilla.org/widget/htmlformatconverter;1", &kNS_HTMLFORMATCONVERTER_CID },
+    { NULL }
+};
+
+static void
+nsWidgetGonkModuleDtor()
+{
+    nsLookAndFeel::Shutdown();
+    nsAppShellShutdown();
+}
+
+static const mozilla::Module kWidgetModule = {
+    mozilla::Module::kVersion,
+    kWidgetCIDs,
+    kWidgetContracts,
+    NULL,
+    NULL,
+    nsAppShellInit,
+    nsWidgetGonkModuleDtor
+};
+
+NSMODULE_DEFN(nsWidgetGonkModule) = &kWidgetModule;
new file mode 100644
--- /dev/null
+++ b/widget/src/gonk/nsWindow.cpp
@@ -0,0 +1,359 @@
+/* ***** BEGIN LICENSE BLOCK *****
+ * Version: MPL 1.1/GPL 2.0/LGPL 2.1
+ *
+ * The contents of this file are subject to the Mozilla Public License Version
+ * 1.1 (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ * http://www.mozilla.org/MPL/
+ *
+ * Software distributed under the License is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+ * for the specific language governing rights and limitations under the
+ * License.
+ *
+ * The Original Code is Gonk.
+ *
+ * The Initial Developer of the Original Code is
+ * the Mozilla Foundation.
+ * Portions created by the Initial Developer are Copyright (C) 2011
+ * the Initial Developer. All Rights Reserved.
+ *
+ * Contributor(s):
+ *   Michael Wu <mwu@mozilla.com>
+ *
+ * Alternatively, the contents of this file may be used under the terms of
+ * either the GNU General Public License Version 2 or later (the "GPL"), or
+ * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
+ * in which case the provisions of the GPL or the LGPL are applicable instead
+ * of those above. If you wish to allow use of your version of this file only
+ * under the terms of either the GPL or the LGPL, and not to allow others to
+ * use your version of this file under the terms of the MPL, indicate your
+ * decision by deleting the provisions above and replace them with the notice
+ * and other provisions required by the GPL or the LGPL. If you do not delete
+ * the provisions above, a recipient may use your version of this file under
+ * the terms of any one of the MPL, the GPL or the LGPL.
+ *
+ * ***** END LICENSE BLOCK ***** */
+
+#include "nsAutoPtr.h"
+#include "nsAppShell.h"
+#include "nsTArray.h"
+#include "nsWindow.h"
+
+#include <EGL/egl.h>
+#include <EGL/eglext.h>
+#include "ui/FramebufferNativeWindow.h"
+
+#include "LayerManagerOGL.h"
+#include "GLContextProvider.h"
+
+#include "android/log.h"
+
+#define LOG(args...)  __android_log_print(ANDROID_LOG_INFO, "Gonk" , ## args)
+
+#define IS_TOPLEVEL() (mWindowType == eWindowType_toplevel || mWindowType == eWindowType_dialog)
+
+using namespace mozilla::gl;
+using namespace mozilla::layers;
+
+nsIntRect gScreenBounds;
+
+static nsRefPtr<GLContext> sGLContext;
+static nsTArray<nsWindow *> sTopWindows;
+static nsWindow *gWindowToRedraw = nsnull;
+static nsWindow *gFocusedWindow = nsnull;
+static android::FramebufferNativeWindow *gNativeWindow = nsnull;
+
+nsWindow::nsWindow()
+{
+    if (!sGLContext) {
+        gNativeWindow = new android::FramebufferNativeWindow();
+        sGLContext = GLContextProvider::CreateForWindow(this);
+        // CreateForWindow sets up gScreenBounds
+    }
+}
+
+nsWindow::~nsWindow()
+{
+}
+
+void
+nsWindow::DoDraw(void)
+{
+    if (!gWindowToRedraw)
+        return;
+
+    nsPaintEvent event(true, NS_PAINT, gWindowToRedraw);
+    event.region = gScreenBounds;
+    static_cast<LayerManagerOGL*>(gWindowToRedraw->GetLayerManager(nsnull))->
+                    SetClippingRegion(nsIntRegion(gScreenBounds));
+    gWindowToRedraw->mEventCallback(&event);
+}
+
+nsEventStatus
+nsWindow::DispatchInputEvent(nsGUIEvent &aEvent)
+{
+    if (!gFocusedWindow)
+        return nsEventStatus_eIgnore;
+
+    aEvent.widget = gFocusedWindow;
+    return gFocusedWindow->mEventCallback(&aEvent);
+}
+
+NS_IMETHODIMP
+nsWindow::Create(nsIWidget *aParent,
+                 void *aNativeParent,
+                 const nsIntRect &aRect,
+                 EVENT_CALLBACK aHandleEventFunction,
+                 nsDeviceContext *aContext,
+                 nsWidgetInitData *aInitData)
+{
+    BaseCreate(aParent, IS_TOPLEVEL() ? gScreenBounds : aRect,
+               aHandleEventFunction, aContext, aInitData);
+
+    mBounds = aRect;
+
+    nsWindow *parent = (nsWindow *)aNativeParent;
+    mParent = parent;
+
+    if (!aNativeParent) {
+        mBounds = gScreenBounds;
+    }
+
+    if (!IS_TOPLEVEL())
+        return NS_OK;
+
+    sTopWindows.AppendElement(this);
+
+    Resize(0, 0, gScreenBounds.width, gScreenBounds.height, false);
+    return NS_OK;
+}
+
+NS_IMETHODIMP
+nsWindow::Destroy(void)
+{
+    sTopWindows.RemoveElement(this);
+    if (this == gWindowToRedraw)
+        gWindowToRedraw = nsnull;
+    if (this == gFocusedWindow)
+        gFocusedWindow = nsnull;
+    return NS_OK;
+}
+
+NS_IMETHODIMP
+nsWindow::Show(bool aState)
+{
+    if (!IS_TOPLEVEL())
+        return NS_OK;
+
+    if (aState)
+        BringToTop();
+    else
+        mVisible = false;
+
+    return NS_OK;
+}
+
+NS_IMETHODIMP
+nsWindow::IsVisible(bool & aState)
+{
+    aState = mVisible;
+    return NS_OK;
+}
+
+NS_IMETHODIMP
+nsWindow::ConstrainPosition(bool aAllowSlop,
+                  PRInt32 *aX,
+                  PRInt32 *aY)
+{
+    return NS_OK;
+}
+
+NS_IMETHODIMP
+nsWindow::Move(PRInt32 aX,
+               PRInt32 aY)
+{
+    return NS_OK;
+}
+
+NS_IMETHODIMP
+nsWindow::Resize(PRInt32 aWidth,
+                 PRInt32 aHeight,
+                 bool    aRepaint)
+{
+    return Resize(0, 0, aWidth, aHeight, aRepaint);
+}
+
+NS_IMETHODIMP
+nsWindow::Resize(PRInt32 aX,
+                 PRInt32 aY,
+                 PRInt32 aWidth,
+                 PRInt32 aHeight,
+                 bool    aRepaint)
+{
+    nsSizeEvent event(true, NS_SIZE, this);
+    event.time = PR_Now() / 1000;
+
+    nsIntRect rect(aX, aY, aWidth, aHeight);
+    event.windowSize = &rect;
+    event.mWinWidth = gScreenBounds.width;
+    event.mWinHeight = gScreenBounds.height;
+
+    (*mEventCallback)(&event);
+
+    return NS_OK;
+}
+
+NS_IMETHODIMP
+nsWindow::Enable(bool aState)
+{
+    return NS_OK;
+}
+
+NS_IMETHODIMP
+nsWindow::IsEnabled(bool *aState)
+{
+    *aState = true;
+    return NS_OK;
+}
+
+NS_IMETHODIMP
+nsWindow::SetFocus(bool aRaise)
+{
+    if (aRaise)
+        BringToTop();
+
+    gFocusedWindow = this;
+    return NS_OK;
+}
+
+NS_IMETHODIMP
+nsWindow::ConfigureChildren(const nsTArray<nsIWidget::Configuration>&)
+{
+    return NS_OK;
+}
+
+NS_IMETHODIMP
+nsWindow::Invalidate(const nsIntRect &aRect,
+                     bool aIsSynchronous)
+{
+    gWindowToRedraw = this;
+    gDrawRequest = true;
+    mozilla::NotifyEvent();
+    return NS_OK;
+}
+
+NS_IMETHODIMP
+nsWindow::Update()
+{
+    Invalidate(gScreenBounds, false);
+    return NS_OK;
+}
+
+nsIntPoint
+nsWindow::WidgetToScreenOffset()
+{
+    nsIntPoint p(0, 0);
+    nsWindow *w = this;
+
+    while (w && w->mParent) {
+        p.x += w->mBounds.x;
+        p.y += w->mBounds.y;
+
+        w = w->mParent;
+    }
+
+    return p;
+}
+
+void*
+nsWindow::GetNativeData(PRUint32 aDataType)
+{
+    switch (aDataType) {
+    case NS_NATIVE_WINDOW:
+        return gNativeWindow;
+    case NS_NATIVE_WIDGET:
+        return this;
+    }
+    return nsnull;
+}
+
+NS_IMETHODIMP
+nsWindow::DispatchEvent(nsGUIEvent *aEvent, nsEventStatus &aStatus)
+{
+    return NS_OK;
+}
+
+NS_IMETHODIMP
+nsWindow::ReparentNativeWidget(nsIWidget* aNewParent)
+{
+    return NS_OK;
+}
+
+float
+nsWindow::GetDPI()
+{
+    return gNativeWindow->xdpi;
+}
+
+LayerManager *
+nsWindow::GetLayerManager(PLayersChild* aShadowManager,
+                          LayersBackend aBackendHint,
+                          LayerManagerPersistence aPersistence,
+                          bool* aAllowRetaining)
+{
+    if (aAllowRetaining)
+        *aAllowRetaining = true;
+    if (mLayerManager)
+        return mLayerManager;
+
+    nsWindow *topWindow = sTopWindows[0];
+
+    if (!topWindow) {
+        LOG(" -- no topwindow\n");
+        return nsnull;
+    }
+
+    if (!sGLContext) {
+        LOG(" -- no GLContext\n");
+        return nsnull;
+    }
+
+    nsRefPtr<LayerManagerOGL> layerManager =
+        new LayerManagerOGL(this);
+
+    if (layerManager->Initialize(sGLContext))
+        mLayerManager = layerManager;
+    else
+        LOG("Could not create LayerManager");
+
+    return mLayerManager;
+}
+
+gfxASurface *
+nsWindow::GetThebesSurface()
+{
+    /* This is really a dummy surface; this is only used when doing reflow, because
+     * we need a RenderingContext to measure text against.
+     */
+
+    // XXX this really wants to return already_AddRefed, but this only really gets used
+    // on direct assignment to a gfxASurface
+    return new gfxImageSurface(gfxIntSize(5,5), gfxImageSurface::ImageFormatRGB24);
+}
+
+void
+nsWindow::BringToTop()
+{
+    if (!sTopWindows.IsEmpty()) {
+        nsGUIEvent event(true, NS_DEACTIVATE, sTopWindows[0]);
+        (*mEventCallback)(&event);
+    }
+
+    sTopWindows.RemoveElement(this);
+    sTopWindows.InsertElementAt(0, this);
+
+    nsGUIEvent event(true, NS_ACTIVATE, this);
+    (*mEventCallback)(&event);
+}
+
new file mode 100644
--- /dev/null
+++ b/widget/src/gonk/nsWindow.h
@@ -0,0 +1,128 @@
+/* ***** BEGIN LICENSE BLOCK *****
+ * Version: MPL 1.1/GPL 2.0/LGPL 2.1
+ *
+ * The contents of this file are subject to the Mozilla Public License Version
+ * 1.1 (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ * http://www.mozilla.org/MPL/
+ *
+ * Software distributed under the License is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+ * for the specific language governing rights and limitations under the
+ * License.
+ *
+ * The Original Code is Gonk.
+ *
+ * The Initial Developer of the Original Code is
+ *   Mozilla Foundation.
+ * Portions created by the Initial Developer are Copyright (C) 2011
+ * the Initial Developer. All Rights Reserved.
+ *
+ * Contributor(s):
+ *   Michael Wu <mwu@mozilla.com>
+ *
+ * Alternatively, the contents of this file may be used under the terms of
+ * either the GNU General Public License Version 2 or later (the "GPL"), or
+ * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
+ * in which case the provisions of the GPL or the LGPL are applicable instead
+ * of those above. If you wish to allow use of your version of this file only
+ * under the terms of either the GPL or the LGPL, and not to allow others to
+ * use your version of this file under the terms of the MPL, indicate your
+ * decision by deleting the provisions above and replace them with the notice
+ * and other provisions required by the GPL or the LGPL. If you do not delete
+ * the provisions above, a recipient may use your version of this file under
+ * the terms of any one of the MPL, the GPL or the LGPL.
+ *
+ * ***** END LICENSE BLOCK ***** */
+
+#ifndef nsWindow_h
+#define nsWindow_h
+
+#include "nsBaseWidget.h"
+
+extern nsIntRect gScreenBounds;
+
+namespace mozilla {
+namespace gl {
+class GLContext;
+}
+namespace layers {
+class LayersManager;
+}
+}
+
+namespace android {
+class FramebufferNativeWindow;
+}
+
+class nsWindow : public nsBaseWidget
+{
+public:
+    nsWindow();
+    virtual ~nsWindow();
+
+    static void DoDraw(void);
+    static nsEventStatus DispatchInputEvent(nsGUIEvent &aEvent);
+
+    NS_IMETHOD Create(nsIWidget *aParent,
+                      void *aNativeParent,
+                      const nsIntRect &aRect,
+                      EVENT_CALLBACK aHandleEventFunction,
+                      nsDeviceContext *aContext,
+                      nsWidgetInitData *aInitData);
+    NS_IMETHOD Destroy(void);
+
+    NS_IMETHOD Show(bool aState);
+    NS_IMETHOD IsVisible(bool & aState);
+    NS_IMETHOD ConstrainPosition(bool aAllowSlop,
+                                 PRInt32 *aX,
+                                 PRInt32 *aY);
+    NS_IMETHOD Move(PRInt32 aX,
+                    PRInt32 aY);
+    NS_IMETHOD Resize(PRInt32 aWidth,
+                      PRInt32 aHeight,
+                      bool  aRepaint);
+    NS_IMETHOD Resize(PRInt32 aX,
+                      PRInt32 aY,
+                      PRInt32 aWidth,
+                      PRInt32 aHeight,
+                      bool aRepaint);
+    NS_IMETHOD Enable(bool aState);
+    NS_IMETHOD IsEnabled(bool *aState);
+    NS_IMETHOD SetFocus(bool aRaise = false);
+    NS_IMETHOD ConfigureChildren(const nsTArray<nsIWidget::Configuration>&);
+    NS_IMETHOD Invalidate(const nsIntRect &aRect,
+                          bool aIsSynchronous);
+    NS_IMETHOD Update();
+    virtual void* GetNativeData(PRUint32 aDataType);
+    NS_IMETHOD SetTitle(const nsAString& aTitle)
+    {
+        return NS_OK;
+    }
+    virtual nsIntPoint WidgetToScreenOffset();
+    NS_IMETHOD DispatchEvent(nsGUIEvent *aEvent, nsEventStatus &aStatus);
+    NS_IMETHOD CaptureRollupEvents(nsIRollupListener *aListener,
+                                   nsIMenuRollup *aMenuRollup,
+                                   bool aDoCapture,
+                                   bool aConsumeRollupEvent)
+    {
+        return NS_ERROR_NOT_IMPLEMENTED;
+    }
+    NS_IMETHOD ReparentNativeWidget(nsIWidget* aNewParent);
+
+    virtual float GetDPI();
+    virtual mozilla::layers::LayerManager*
+        GetLayerManager(PLayersChild* aShadowManager = nsnull,
+                        LayersBackend aBackendHint = LayerManager::LAYERS_NONE,
+                        LayerManagerPersistence aPersistence = LAYER_MANAGER_CURRENT,
+                        bool* aAllowRetaining = nsnull);
+    gfxASurface* GetThebesSurface();
+
+protected:
+    nsWindow* mParent;
+    bool mVisible;
+
+    void BringToTop();
+};
+
+#endif /* nsWindow_h */
--- a/widget/src/xpwidgets/Makefile.in
+++ b/widget/src/xpwidgets/Makefile.in
@@ -77,17 +77,17 @@ ifdef MOZ_X11
 CPPSRCS		+= \
 		GfxInfoX11.cpp
 endif
 
 ifneq (,$(filter os2 cocoa windows,$(MOZ_WIDGET_TOOLKIT)))
 CPPSRCS += nsBaseClipboard.cpp
 endif
 
-ifneq (,$(filter qt gtk2 os2 cocoa windows android,$(MOZ_WIDGET_TOOLKIT)))
+ifneq (,$(filter qt gtk2 os2 cocoa windows android gonk,$(MOZ_WIDGET_TOOLKIT)))
 CPPSRCS += nsBaseFilePicker.cpp
 endif
 
 ifneq (,$(filter qt gtk2 windows cocoa,$(MOZ_WIDGET_TOOLKIT)))
 CPPSRCS += nsNativeTheme.cpp
 endif
 
 SHARED_LIBRARY_LIBS = ../shared/$(LIB_PREFIX)widget_shared.$(LIB_SUFFIX)
--- a/xpcom/base/nsSystemInfo.cpp
+++ b/xpcom/base/nsSystemInfo.cpp
@@ -44,17 +44,17 @@
 #include "prprf.h"
 #include "mozilla/SSE.h"
 #include "mozilla/arm.h"
 
 #ifdef MOZ_WIDGET_GTK2
 #include <gtk/gtk.h>
 #endif
 
-#ifdef ANDROID
+#ifdef MOZ_WIDGET_ANDROID
 #include "AndroidBridge.h"
 #endif
 
 using namespace mozilla;
 
 nsSystemInfo::nsSystemInfo()
 {
 }
@@ -169,17 +169,17 @@ nsSystemInfo::Init()
 #if MOZ_PLATFORM_MAEMO > 5
       pclose(fp);
 #else
       fclose(fp);
 #endif
     }
 #endif
 
-#ifdef ANDROID
+#ifdef MOZ_WIDGET_ANDROID
     if (mozilla::AndroidBridge::Bridge()) {
         nsAutoString str;
         if (mozilla::AndroidBridge::Bridge()->GetStaticStringField("android/os/Build", "MODEL", str))
             SetPropertyAsAString(NS_LITERAL_STRING("device"), str);
         if (mozilla::AndroidBridge::Bridge()->GetStaticStringField("android/os/Build", "MANUFACTURER", str))
             SetPropertyAsAString(NS_LITERAL_STRING("manufacturer"), str);
         PRInt32 version;
         if (!mozilla::AndroidBridge::Bridge()->GetStaticIntField("android/os/Build$VERSION", "SDK_INT", &version))
--- a/xpcom/components/ManifestParser.cpp
+++ b/xpcom/components/ManifestParser.cpp
@@ -47,17 +47,17 @@
 #if defined(XP_WIN)
 #include <windows.h>
 #elif defined(MOZ_WIDGET_COCOA)
 #include <CoreServices/CoreServices.h>
 #elif defined(MOZ_WIDGET_GTK2)
 #include <gtk/gtk.h>
 #endif
 
-#ifdef ANDROID
+#ifdef MOZ_WIDGET_ANDROID
 #include "AndroidBridge.h"
 #endif
 
 #include "mozilla/Services.h"
 
 #include "nsConsoleMessage.h"
 #include "nsTextFormatter.h"
 #include "nsVersionComparator.h"
@@ -497,17 +497,17 @@ ParseManifestCommon(NSLocationType aType
     nsTextFormatter::ssprintf(osVersion, NS_LITERAL_STRING("%ld.%ld").get(),
                                          majorVersion,
                                          minorVersion);
   }
 #elif defined(MOZ_WIDGET_GTK2)
   nsTextFormatter::ssprintf(osVersion, NS_LITERAL_STRING("%ld.%ld").get(),
                                        gtk_major_version,
                                        gtk_minor_version);
-#elif defined(ANDROID)
+#elif defined(MOZ_WIDGET_ANDROID)
   if (mozilla::AndroidBridge::Bridge()) {
     mozilla::AndroidBridge::Bridge()->GetStaticStringField("android/os/Build$VERSION", "RELEASE", osVersion);
   }
 #endif
 
   // Because contracts must be registered after CIDs, we save and process them
   // at the end.
   nsTArray<CachedDirective> contracts;
--- a/xpcom/io/nsLocalFileUnix.cpp
+++ b/xpcom/io/nsLocalFileUnix.cpp
@@ -108,17 +108,17 @@ static nsresult MacErrorMapper(OSErr inE
 
 #if (MOZ_PLATFORM_MAEMO == 5)
 #include <glib.h>
 #include <hildon-uri.h>
 #include <hildon-mime.h>
 #include <libosso.h>
 #endif
 
-#ifdef ANDROID
+#ifdef MOZ_WIDGET_ANDROID
 #include "AndroidBridge.h"
 #include "nsIMIMEService.h"
 #include <linux/magic.h>
 #endif
 
 #include "nsNativeCharsetUtils.h"
 #include "nsTraceRefcntImpl.h"
 
@@ -1880,17 +1880,17 @@ nsLocalFile::Launch()
       ContentAction::Action::defaultActionForFile(uri);
 
     if (action.isValid()) {
       action.trigger();
       return NS_OK;
     }
 
     return NS_ERROR_FAILURE;
-#elif defined(ANDROID)
+#elif defined(MOZ_WIDGET_ANDROID)
     // Try to get a mimetype, if this fails just use the file uri alone
     nsresult rv;
     nsCAutoString type;
     nsCOMPtr<nsIMIMEService> mimeService(do_GetService("@mozilla.org/mime;1", &rv));
     if (NS_SUCCEEDED(rv))
         rv = mimeService->GetTypeFromFile(this, type);
 
     nsDependentCString fileUri = NS_LITERAL_CSTRING("file://");