Merge MC -> JM
authorBrian Hackett <bhackett1024@gmail.com>
Mon, 19 Sep 2011 15:29:22 -0700
changeset 78458 648d084ca28ee49ffd502255b47fb421bed0aebc
parent 78457 c943bbf9dac4263560f51f303e146cf2a5710775 (current diff)
parent 78453 ea2f892d94391494c13e907c1128a6ca9826d582 (diff)
child 78459 f7cbb2d9c61dbaf6c78c4aababd46427320a2d3b
push id78
push userclegnitto@mozilla.com
push dateFri, 16 Dec 2011 17:32:24 +0000
treeherdermozilla-release@79d24e644fdd [default view] [failures only]
perfherder[talos] [build metrics] [platform microbench] (compared to previous push)
milestone9.0a1
first release with
nightly linux32
648d084ca28e / 9.0a1 / 20110920030905 / files
nightly linux64
648d084ca28e / 9.0a1 / 20110920030905 / files
nightly mac
648d084ca28e / 9.0a1 / 20110920030905 / files
nightly win32
648d084ca28e / 9.0a1 / 20110920030905 / files
nightly win64
648d084ca28e / 9.0a1 / 20110920030905 / files
last release without
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
releases
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
Merge MC -> JM
content/base/public/nsIPrivateDOMImplementation.h
--- a/accessible/src/xul/Makefile.in
+++ b/accessible/src/xul/Makefile.in
@@ -67,12 +67,9 @@ CPPSRCS = \
 FORCE_STATIC_LIB = 1
 
 include $(topsrcdir)/config/rules.mk
 
 LOCAL_INCLUDES = \
   -I$(srcdir) \
   -I$(srcdir)/../base \
   -I$(srcdir)/../html \
-  -I$(srcdir)/../../../layout/html/base/src \
-  -I$(srcdir)/../../../layout/html/forms/src \
-  -I$(srcdir)/../../../layout/html/forms/public \
   $(NULL)
--- a/build/macosx/mozconfig.leopard
+++ b/build/macosx/mozconfig.leopard
@@ -15,16 +15,18 @@ HOST_CXX=$CXX
 
 # These must be set for cross builds, and don't hurt straight builds.
 RANLIB=ranlib
 AR=ar
 AS=$CC
 LD=ld
 STRIP="strip -x -S"
 
+MOZ_CAN_RUN_PROGRAMS=1
+
 # We do 32 bit builds for leopard
 TARGET_CPU=i386
 CC="$CC -arch $TARGET_CPU"
 CXX="$CXX -arch $TARGET_CPU"
 
 NATIVE_CPU=`$topsrcdir/build/autoconf/config.guess | cut -f1 -d-`
 
 if test "$NATIVE_CPU" != "$TARGET_CPU" ; then
--- a/caps/src/nsSecurityManagerFactory.cpp
+++ b/caps/src/nsSecurityManagerFactory.cpp
@@ -315,22 +315,22 @@ static JSFunctionSpec PrivilegeManager_s
     { "setCanEnablePrivilege", netscape_security_setCanEnablePrivilege,
                                                                     2,0},
     { "invalidate",            netscape_security_invalidate,        1,0},
     {nsnull,nsnull,0,0}
 };
 
 /*
  * "Steal" calls to netscape.security.PrivilegeManager.enablePrivilege,
- * et. al. so that code that worked with 4.0 can still work.
+ * et al. so that code that worked with 4.0 can still work.
  */
 NS_IMETHODIMP 
 nsSecurityNameSet::InitializeNameSet(nsIScriptContext* aScriptContext)
 {
-    JSContext *cx = (JSContext *) aScriptContext->GetNativeContext();
+    JSContext* cx = aScriptContext->GetNativeContext();
     JSObject *global = JS_GetGlobalObject(cx);
     OBJ_TO_INNER_OBJECT(cx, global);
 
     /*
      * Find Object.prototype's class by walking up the global object's
      * prototype chain.
      */
     JSObject *obj = global;
--- a/config/autoconf.mk.in
+++ b/config/autoconf.mk.in
@@ -652,16 +652,17 @@ MOZ_MAEMO_LIBLOCATION 	= @MOZ_MAEMO_LIBL
 MOZ_ENABLE_LIBCONIC = @MOZ_ENABLE_LIBCONIC@
 LIBCONIC_CFLAGS     = @LIBCONIC_CFLAGS@
 LIBCONIC_LIBS       = @LIBCONIC_LIBS@
 
 MACOS_SDK_DIR	= @MACOS_SDK_DIR@
 NEXT_ROOT	= @NEXT_ROOT@
 GCC_VERSION	= @GCC_VERSION@
 UNIVERSAL_BINARY= @UNIVERSAL_BINARY@
+MOZ_CAN_RUN_PROGRAMS = MOZ_CAN_RUN_PROGRAMS@
 HAVE_DTRACE= @HAVE_DTRACE@
 
 VISIBILITY_FLAGS = @VISIBILITY_FLAGS@
 WRAP_SYSTEM_INCLUDES = @WRAP_SYSTEM_INCLUDES@
 
 HAVE_ARM_SIMD = @HAVE_ARM_SIMD@
 HAVE_ARM_NEON = @HAVE_ARM_NEON@
 HAVE_GCC_ALIGN_ARG_POINTER = @HAVE_GCC_ALIGN_ARG_POINTER@
--- a/configure.in
+++ b/configure.in
@@ -1095,18 +1095,20 @@ from building Mozilla. Upgrade to Xcode 
     dnl it has moved into /usr/bin.
     MOZ_PATH_PROG(SDP, sdp, :, [$PATH:/usr/bin:/Developer/Tools])
     ;;
 esac
 
 AC_SUBST(GCC_VERSION)
 
 dnl The universal machinery sets UNIVERSAL_BINARY to inform packager.mk
-dnl that a universal binary is being produced.
+dnl that a universal binary is being produced and MOZ_CAN_RUN_PROGRAMS
+dnl when we can run target binaries.
 AC_SUBST(UNIVERSAL_BINARY)
+AC_SUBST(MOZ_CAN_RUN_PROGRAMS)
 
 dnl ========================================================
 dnl Check for MacOS deployment target version
 dnl ========================================================
 
 MOZ_ARG_ENABLE_STRING(macos-target,
                       [  --enable-macos-target=VER (default=10.5)
                           Set the minimum MacOS version needed at runtime],
--- a/content/base/public/nsContentCID.h
+++ b/content/base/public/nsContentCID.h
@@ -116,20 +116,16 @@
 // {09F689E0-B4DA-11d2-A68B-00104BDE6048}
 #define NS_EVENTLISTENERMANAGER_CID \
 { 0x9f689e0, 0xb4da, 0x11d2, { 0xa6, 0x8b, 0x0, 0x10, 0x4b, 0xde, 0x60, 0x48 } }
 
 // {64F300A1-C88C-11d3-97FB-00400553EEF0}
 #define NS_XBLSERVICE_CID \
 { 0x64f300a1, 0xc88c, 0x11d3, { 0x97, 0xfb, 0x0, 0x40, 0x5, 0x53, 0xee, 0xf0 } }
 
-// 3a9cd622-264d-11d4-ba06-0060b0fc76dd
-#define NS_DOM_IMPLEMENTATION_CID \
-{ 0x3a9cd622, 0x264d, 0x11d4, {0xba, 0x06, 0x00, 0x60, 0xb0, 0xfc, 0x76, 0xdd } }
-
 // {4aef38b7-6364-4e23-a5e7-12f837fbbd9c}
 #define NS_XMLCONTENTSERIALIZER_CID \
 { 0x4aef38b7, 0x6364, 0x4e23, { 0xa5, 0xe7, 0x12, 0xf8, 0x37, 0xfb, 0xbd, 0x9c } }
 
 // {e7c2aaf5-c11a-4954-9dbf-e28edec1fd91}
 #define NS_XHTMLCONTENTSERIALIZER_CID \
 { 0xe7c2aaf5, 0xc11a, 0x4954, { 0x9d, 0xbf, 0xe2, 0x8e, 0xde, 0xc1, 0xfd, 0x91 } }
 
--- a/content/base/public/nsIDocument.h
+++ b/content/base/public/nsIDocument.h
@@ -1879,17 +1879,18 @@ NS_NewDocumentFragment(nsIDOMDocumentFra
 nsresult
 NS_NewDOMDocument(nsIDOMDocument** aInstancePtrResult,
                   const nsAString& aNamespaceURI, 
                   const nsAString& aQualifiedName, 
                   nsIDOMDocumentType* aDoctype,
                   nsIURI* aDocumentURI,
                   nsIURI* aBaseURI,
                   nsIPrincipal* aPrincipal,
-                  PRBool aLoadedAsData);
+                  PRBool aLoadedAsData,
+                  nsIScriptGlobalObject* aEventObject);
 nsresult
 NS_NewPluginDocument(nsIDocument** aInstancePtrResult);
 
 inline nsIDocument*
 nsINode::GetOwnerDocument() const
 {
   nsIDocument* ownerDoc = GetOwnerDoc();
 
deleted file mode 100644
--- a/content/base/public/nsIPrivateDOMImplementation.h
+++ /dev/null
@@ -1,69 +0,0 @@
-/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
-/* ***** 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):
- *
- * 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 nsIPrivateDOMImplementation_h__
-#define nsIPrivateDOMImplementation_h__
-
-#include "nsISupports.h"
-
-class nsIURI;
-class nsIPrincipal;
-
-/*
- * Event listener manager interface.
- */
-#define NS_IPRIVATEDOMIMPLEMENTATION_IID \
-{ /* 87c20441-8b0d-4383-a189-52fef1dd5d8a */ \
-0x87c20441, 0x8b0d, 0x4383, \
- { 0xa1, 0x89, 0x52, 0xfe, 0xf1, 0xdd, 0x5d, 0x8a } }
-
-class nsIPrivateDOMImplementation : public nsISupports {
-
-public:
-  NS_DECLARE_STATIC_IID_ACCESSOR(NS_IPRIVATEDOMIMPLEMENTATION_IID)
-
-  NS_IMETHOD Init(nsIURI* aDocumentURI, nsIURI* aBaseURI,
-                  nsIPrincipal* aPrincipal) = 0;
-};
-
-NS_DEFINE_STATIC_IID_ACCESSOR(nsIPrivateDOMImplementation,
-                              NS_IPRIVATEDOMIMPLEMENTATION_IID)
-
-nsresult
-NS_NewDOMImplementation(nsIDOMDOMImplementation** aInstancePtrResult);
-
-#endif // nsIPrivateDOMImplementation_h__
--- a/content/base/src/nsContentUtils.cpp
+++ b/content/base/src/nsContentUtils.cpp
@@ -1,12 +1,11 @@
-/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
- * vim: set ts=2 sw=2 et tw=78:
- *
- * ***** BEGIN LICENSE BLOCK *****
+/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=2 sw=2 et tw=78: */
+/* ***** 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,
@@ -1281,21 +1280,20 @@ nsContentUtils::GetContextFromDocument(n
   if (!sgo) {
     // No script global, no context.
     return nsnull;
   }
 
   nsIScriptContext *scx = sgo->GetContext();
   if (!scx) {
     // No context left in the scope...
-
     return nsnull;
   }
 
-  return (JSContext *)scx->GetNativeContext();
+  return scx->GetNativeContext();
 }
 
 // static
 nsresult
 nsContentUtils::GetContextAndScope(nsIDocument *aOldDocument,
                                    nsIDocument *aNewDocument, JSContext **aCx,
                                    JSObject **aNewScope)
 {
@@ -2554,17 +2552,17 @@ nsCxPusher::Push(nsIDOMEventTarget *aCur
     // Nothing to do here, I guess.  Have to return true so that event firing
     // will still work correctly even if there is no associated JSContext
     return PR_TRUE;
   }
 
   JSContext* cx = nsnull;
 
   if (scx) {
-    cx = static_cast<JSContext*>(scx->GetNativeContext());
+    cx = scx->GetNativeContext();
     // Bad, no JSContext from script context!
     NS_ENSURE_TRUE(cx, PR_FALSE);
   }
 
   // If there's no native context in the script context it must be
   // in the process or being torn down. We don't want to notify the
   // script context about scripts having been evaluated in such a
   // case, calling with a null cx is fine in that case.
@@ -3683,21 +3681,20 @@ nsContentUtils::CreateDocument(const nsA
                                nsIDOMDocumentType* aDoctype,
                                nsIURI* aDocumentURI, nsIURI* aBaseURI,
                                nsIPrincipal* aPrincipal,
                                nsIScriptGlobalObject* aEventObject,
                                nsIDOMDocument** aResult)
 {
   nsresult rv = NS_NewDOMDocument(aResult, aNamespaceURI, aQualifiedName,
                                   aDoctype, aDocumentURI, aBaseURI, aPrincipal,
-                                  PR_TRUE);
+                                  PR_TRUE, aEventObject);
   NS_ENSURE_SUCCESS(rv, rv);
 
   nsCOMPtr<nsIDocument> document = do_QueryInterface(*aResult);
-  document->SetScriptHandlingObject(aEventObject);
   
   // created documents are immediately "complete" (ready to use)
   document->SetReadyStateInternal(nsIDocument::READYSTATE_COMPLETE);
   return NS_OK;
 }
 
 /* static */
 nsresult
--- a/content/base/src/nsDOMDocumentType.cpp
+++ b/content/base/src/nsDOMDocumentType.cpp
@@ -50,44 +50,29 @@
 #include "nsIDocument.h"
 #include "nsIXPConnect.h"
 #include "nsIDOMDocument.h"
 #include "xpcpublic.h"
 
 nsresult
 NS_NewDOMDocumentType(nsIDOMDocumentType** aDocType,
                       nsNodeInfoManager *aNodeInfoManager,
-                      nsIPrincipal *aPrincipal,
                       nsIAtom *aName,
                       const nsAString& aPublicId,
                       const nsAString& aSystemId,
                       const nsAString& aInternalSubset)
 {
-  NS_PRECONDITION(aNodeInfoManager || aPrincipal,
-                  "Must have a principal if no nodeinfo manager.");
   NS_ENSURE_ARG_POINTER(aDocType);
   NS_ENSURE_ARG_POINTER(aName);
 
-  nsRefPtr<nsNodeInfoManager> nimgr;
-  if (aNodeInfoManager) {
-    nimgr = aNodeInfoManager;
-  }
-  else {
-    nimgr = new nsNodeInfoManager();
-    nsresult rv = nimgr->Init(nsnull);
-    NS_ENSURE_SUCCESS(rv, rv);
-
-    nimgr->SetDocumentPrincipal(aPrincipal);
-  }
-
   nsCOMPtr<nsINodeInfo> ni =
-    nimgr->GetNodeInfo(nsGkAtoms::documentTypeNodeName, nsnull,
-                       kNameSpaceID_None,
-                       nsIDOMNode::DOCUMENT_TYPE_NODE,
-                       aName);
+    aNodeInfoManager->GetNodeInfo(nsGkAtoms::documentTypeNodeName, nsnull,
+                                  kNameSpaceID_None,
+                                  nsIDOMNode::DOCUMENT_TYPE_NODE,
+                                  aName);
   NS_ENSURE_TRUE(ni, NS_ERROR_OUT_OF_MEMORY);
 
   *aDocType = new nsDOMDocumentType(ni.forget(), aPublicId, aSystemId,
                                     aInternalSubset);
   NS_ADDREF(*aDocType);
 
   return NS_OK;
 }
@@ -171,64 +156,8 @@ nsDOMDocumentType::GetInternalSubset(nsA
 nsGenericDOMDataNode*
 nsDOMDocumentType::CloneDataNode(nsINodeInfo *aNodeInfo, PRBool aCloneText) const
 {
   nsCOMPtr<nsINodeInfo> ni = aNodeInfo;
   return new nsDOMDocumentType(ni.forget(), mPublicId, mSystemId,
                                mInternalSubset);
 }
 
-nsresult
-nsDOMDocumentType::BindToTree(nsIDocument *aDocument, nsIContent *aParent,
-                              nsIContent *aBindingParent,
-                              PRBool aCompileEventHandlers)
-{
-  if (!HasSameOwnerDoc(NODE_FROM(aParent, aDocument))) {
-    NS_ASSERTION(!GetOwnerDoc(), "Need to adopt or import first!");
-
-    // DocumentType nodes are the only nodes that can have a null ownerDocument
-    // according to the DOM spec, so we need to give them a new nodeinfo in that
-    // case.
-    // XXX We may want to move this to nsDOMImplementation::CreateDocument if
-    //     we want to rely on the nodeinfo and wrappers being right before
-    //     getting into ReplaceOrInsertBefore or doInsertChildAt. That would
-    //     break inserting DOMDocumentType nodes through other DOM methods
-    //     though.
-    nsNodeInfoManager *nimgr = aParent ?
-      aParent->NodeInfo()->NodeInfoManager() :
-      aDocument->NodeInfoManager();
-    nsCOMPtr<nsINodeInfo> newNodeInfo;
-    newNodeInfo = nimgr->GetNodeInfo(mNodeInfo->NameAtom(),
-                                     mNodeInfo->GetPrefixAtom(),
-                                     mNodeInfo->NamespaceID(),
-                                     nsIDOMNode::DOCUMENT_TYPE_NODE,
-                                     mNodeInfo->GetExtraName());
-    NS_ENSURE_TRUE(newNodeInfo, NS_ERROR_OUT_OF_MEMORY);
-
-    mNodeInfo.swap(newNodeInfo);
-
-    JSObject *oldScope = GetWrapper();
-    if (oldScope) {
-      nsIXPConnect *xpc = nsContentUtils::XPConnect();
-
-      JSContext *cx = nsnull;
-      JSObject *newScope = nsnull;
-      nsresult rv = nsContentUtils::GetContextAndScope(nsnull,
-                                                       nimgr->GetDocument(),
-                                                       &cx, &newScope);
-      if (cx && xpc) {
-        nsISupports *node = NS_ISUPPORTS_CAST(nsIContent*, this);
-        nsCOMPtr<nsIXPConnectJSObjectHolder> oldWrapper;
-        rv = xpc->ReparentWrappedNativeIfFound(cx, oldScope, newScope, node,
-                                               getter_AddRefs(oldWrapper));
-      }
-
-      if (NS_FAILED(rv)) {
-        mNodeInfo.swap(newNodeInfo);
-
-        return rv;
-      }
-    }
-  }
-
-  return nsGenericDOMDataNode::BindToTree(aDocument, aParent, aBindingParent,
-                                          aCompileEventHandlers);
-}
--- a/content/base/src/nsDOMDocumentType.h
+++ b/content/base/src/nsDOMDocumentType.h
@@ -96,32 +96,28 @@ public:
     return NS_OK;
   }
 
   // nsINode
   virtual PRBool IsNodeOfType(PRUint32 aFlags) const;
 
   // nsIContent overrides
   virtual const nsTextFragment* GetText();
-  virtual nsresult BindToTree(nsIDocument *aDocument, nsIContent *aParent,
-                              nsIContent *aBindingParent,
-                              PRBool aCompileEventHandlers);
 
   virtual nsGenericDOMDataNode* CloneDataNode(nsINodeInfo *aNodeInfo,
                                               PRBool aCloneText) const;
 
   virtual nsXPCClassInfo* GetClassInfo();
 protected:
   nsString mPublicId;
   nsString mSystemId;
   nsString mInternalSubset;
 };
 
 nsresult
 NS_NewDOMDocumentType(nsIDOMDocumentType** aDocType,
-                      nsNodeInfoManager *aOwnerDoc,
-                      nsIPrincipal *aPrincipal,
+                      nsNodeInfoManager* aNodeInfoManager,
                       nsIAtom *aName,
                       const nsAString& aPublicId,
                       const nsAString& aSystemId,
                       const nsAString& aInternalSubset);
 
 #endif // nsDOMDocumentType_h
--- a/content/base/src/nsDocument.cpp
+++ b/content/base/src/nsDocument.cpp
@@ -1316,75 +1316,63 @@ nsDOMStyleSheetSetList::GetSets(nsTArray
 
 // ==================================================================
 // =
 // ==================================================================
 
 class nsDOMImplementation : public nsIDOMDOMImplementation
 {
 public:
-  nsDOMImplementation(nsIScriptGlobalObject* aScriptObject,
+  nsDOMImplementation(nsIDocument* aOwner,
+                      nsIScriptGlobalObject* aScriptObject,
                       nsIURI* aDocumentURI,
-                      nsIURI* aBaseURI,
-                      nsIPrincipal* aPrincipal);
+                      nsIURI* aBaseURI);
   virtual ~nsDOMImplementation();
 
-  NS_DECL_ISUPPORTS
+  NS_DECL_CYCLE_COLLECTING_ISUPPORTS
+  NS_DECL_CYCLE_COLLECTION_CLASS(nsDOMImplementation)
 
   // nsIDOMDOMImplementation
   NS_DECL_NSIDOMDOMIMPLEMENTATION
 
 protected:
+  nsCOMPtr<nsIDocument> mOwner;
   nsWeakPtr mScriptObject;
   nsCOMPtr<nsIURI> mDocumentURI;
   nsCOMPtr<nsIURI> mBaseURI;
-  nsCOMPtr<nsIPrincipal> mPrincipal;
 };
 
-
-nsresult
-NS_NewDOMImplementation(nsIDOMDOMImplementation** aInstancePtrResult)
-{
-  *aInstancePtrResult = new nsDOMImplementation(nsnull, nsnull, nsnull, nsnull);
-  if (!*aInstancePtrResult) {
-    return NS_ERROR_OUT_OF_MEMORY;
-  }
-
-  NS_ADDREF(*aInstancePtrResult);
-
-  return NS_OK;
-}
-
-nsDOMImplementation::nsDOMImplementation(nsIScriptGlobalObject* aScriptObject,
+nsDOMImplementation::nsDOMImplementation(nsIDocument* aOwner,
+                                         nsIScriptGlobalObject* aScriptObject,
                                          nsIURI* aDocumentURI,
-                                         nsIURI* aBaseURI,
-                                         nsIPrincipal* aPrincipal)
-  : mScriptObject(do_GetWeakReference(aScriptObject)),
+                                         nsIURI* aBaseURI)
+  : mOwner(aOwner),
+    mScriptObject(do_GetWeakReference(aScriptObject)),
     mDocumentURI(aDocumentURI),
-    mBaseURI(aBaseURI),
-    mPrincipal(aPrincipal)
+    mBaseURI(aBaseURI)
 {
 }
 
 nsDOMImplementation::~nsDOMImplementation()
 {
 }
 
 DOMCI_DATA(DOMImplementation, nsDOMImplementation)
 
 // QueryInterface implementation for nsDOMImplementation
-NS_INTERFACE_MAP_BEGIN(nsDOMImplementation)
+NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(nsDOMImplementation)
   NS_INTERFACE_MAP_ENTRY(nsIDOMDOMImplementation)
   NS_INTERFACE_MAP_ENTRY_AMBIGUOUS(nsISupports, nsIDOMDOMImplementation)
   NS_DOM_INTERFACE_MAP_ENTRY_CLASSINFO(DOMImplementation)
 NS_INTERFACE_MAP_END
 
-
-NS_IMPL_ADDREF(nsDOMImplementation)
-NS_IMPL_RELEASE(nsDOMImplementation)
+NS_IMPL_CYCLE_COLLECTION_1(nsDOMImplementation, mOwner)
+
+NS_IMPL_CYCLE_COLLECTING_ADDREF(nsDOMImplementation)
+NS_IMPL_CYCLE_COLLECTING_RELEASE(nsDOMImplementation)
 
 
 NS_IMETHODIMP
 nsDOMImplementation::HasFeature(const nsAString& aFeature,
                                 const nsAString& aVersion,
                                 PRBool* aReturn)
 {
   return nsGenericElement::InternalIsSupported(
@@ -1394,27 +1382,29 @@ nsDOMImplementation::HasFeature(const ns
 
 NS_IMETHODIMP
 nsDOMImplementation::CreateDocumentType(const nsAString& aQualifiedName,
                                         const nsAString& aPublicId,
                                         const nsAString& aSystemId,
                                         nsIDOMDocumentType** aReturn)
 {
   *aReturn = nsnull;
+  NS_ENSURE_STATE(mOwner);
 
   nsresult rv = nsContentUtils::CheckQName(aQualifiedName);
   NS_ENSURE_SUCCESS(rv, rv);
 
   nsCOMPtr<nsIAtom> name = do_GetAtom(aQualifiedName);
   NS_ENSURE_TRUE(name, NS_ERROR_OUT_OF_MEMORY);
 
   // Indicate that there is no internal subset (not just an empty one)
   nsAutoString voidString;
   voidString.SetIsVoid(PR_TRUE);
-  return NS_NewDOMDocumentType(aReturn, nsnull, mPrincipal, name, aPublicId,
+  return NS_NewDOMDocumentType(aReturn, mOwner->NodeInfoManager(),
+                               name, aPublicId,
                                aSystemId, voidString);
 }
 
 NS_IMETHODIMP
 nsDOMImplementation::CreateDocument(const nsAString& aNamespaceURI,
                                     const nsAString& aQualifiedName,
                                     nsIDOMDocumentType* aDoctype,
                                     nsIDOMDocument** aReturn)
@@ -1438,63 +1428,57 @@ nsDOMImplementation::CreateDocument(cons
       return NS_ERROR_DOM_NAMESPACE_ERR;
     }
   }
   else if (DOMStringIsNull(aQualifiedName) &&
            !DOMStringIsNull(aNamespaceURI)) {
     return NS_ERROR_DOM_NAMESPACE_ERR;
   }
 
-  if (aDoctype) {
-    nsCOMPtr<nsIDOMDocument> owner;
-    aDoctype->GetOwnerDocument(getter_AddRefs(owner));
-    if (owner) {
-      return NS_ERROR_DOM_WRONG_DOCUMENT_ERR;
-    }
-  }
-
   nsCOMPtr<nsIScriptGlobalObject> scriptHandlingObject =
     do_QueryReferent(mScriptObject);
   
   NS_ENSURE_STATE(!mScriptObject || scriptHandlingObject);
 
   return nsContentUtils::CreateDocument(aNamespaceURI, aQualifiedName, aDoctype,
-                                        mDocumentURI, mBaseURI, mPrincipal,
+                                        mDocumentURI, mBaseURI,
+                                        mOwner->NodePrincipal(),
                                         scriptHandlingObject, aReturn);
 }
 
 NS_IMETHODIMP
 nsDOMImplementation::CreateHTMLDocument(const nsAString& aTitle,
                                         nsIDOMDocument** aReturn)
 {
-  *aReturn = NULL;
+  *aReturn = nsnull;
+  NS_ENSURE_STATE(mOwner);
 
   nsCOMPtr<nsIDOMDocumentType> doctype;
   // Indicate that there is no internal subset (not just an empty one)
   nsAutoString voidString;
   voidString.SetIsVoid(true);
   nsresult rv = NS_NewDOMDocumentType(getter_AddRefs(doctype),
-                                      NULL, // aNodeInfoManager
-                                      mPrincipal, // aPrincipal
+                                      mOwner->NodeInfoManager(),
                                       nsGkAtoms::html, // aName
                                       EmptyString(), // aPublicId
                                       EmptyString(), // aSystemId
                                       voidString); // aInternalSubset
   NS_ENSURE_SUCCESS(rv, rv);
 
 
   nsCOMPtr<nsIScriptGlobalObject> scriptHandlingObject =
     do_QueryReferent(mScriptObject);
 
   NS_ENSURE_STATE(!mScriptObject || scriptHandlingObject);
                                                        
   nsCOMPtr<nsIDOMDocument> document;
   rv = nsContentUtils::CreateDocument(EmptyString(), EmptyString(),
                                       doctype, mDocumentURI, mBaseURI,
-                                      mPrincipal, scriptHandlingObject,
+                                      mOwner->NodePrincipal(),
+                                      scriptHandlingObject,
                                       getter_AddRefs(document));
   NS_ENSURE_SUCCESS(rv, rv);
   nsCOMPtr<nsIDocument> doc = do_QueryInterface(document);
 
   nsCOMPtr<nsIContent> root;
   rv = doc->CreateElem(NS_LITERAL_STRING("html"), NULL, kNameSpaceID_XHTML,
                        false, getter_AddRefs(root));
   NS_ENSURE_SUCCESS(rv, rv);
@@ -3808,17 +3792,17 @@ nsDocument::SetScriptGlobalObject(nsIScr
 #ifdef DEBUG
     if (!mWillReparent) {
       // We really shouldn't have a wrapper here but if we do we need to make sure
       // it has the correct parent.
       JSObject *obj = GetWrapperPreserveColor();
       if (obj) {
         JSObject *newScope = aScriptGlobalObject->GetGlobalJSObject();
         nsIScriptContext *scx = aScriptGlobalObject->GetContext();
-        JSContext *cx = scx ? (JSContext *)scx->GetNativeContext() : nsnull;
+        JSContext *cx = scx ? scx->GetNativeContext() : nsnull;
         if (!cx) {
           nsContentUtils::ThreadJSContextStack()->Peek(&cx);
           if (!cx) {
             nsContentUtils::ThreadJSContextStack()->GetSafeJSContext(&cx);
             NS_ASSERTION(cx, "Uhoh, no context, this is bad!");
           }
         }
         if (cx) {
@@ -4310,18 +4294,17 @@ nsDocument::GetImplementation(nsIDOMDOMI
   if (!mDOMImplementation) {
     nsCOMPtr<nsIURI> uri;
     NS_NewURI(getter_AddRefs(uri), "about:blank");
     NS_ENSURE_TRUE(uri, NS_ERROR_OUT_OF_MEMORY);
     PRBool hasHadScriptObject = PR_TRUE;
     nsIScriptGlobalObject* scriptObject =
       GetScriptHandlingObject(hasHadScriptObject);
     NS_ENSURE_STATE(scriptObject || !hasHadScriptObject);
-    mDOMImplementation = new nsDOMImplementation(scriptObject, uri, uri,
-                                                 NodePrincipal());
+    mDOMImplementation = new nsDOMImplementation(this, scriptObject, uri, uri);
     if (!mDOMImplementation) {
       return NS_ERROR_OUT_OF_MEMORY;
     }
   }
 
   NS_ADDREF(*aImplementation = mDOMImplementation);
 
   return NS_OK;
@@ -4801,16 +4784,17 @@ nsDocument::ImportNode(nsIDOMNode* aImpo
   switch (nodeType) {
     case nsIDOMNode::ATTRIBUTE_NODE:
     case nsIDOMNode::DOCUMENT_FRAGMENT_NODE:
     case nsIDOMNode::ELEMENT_NODE:
     case nsIDOMNode::PROCESSING_INSTRUCTION_NODE:
     case nsIDOMNode::TEXT_NODE:
     case nsIDOMNode::CDATA_SECTION_NODE:
     case nsIDOMNode::COMMENT_NODE:
+    case nsIDOMNode::DOCUMENT_TYPE_NODE:
     {
       nsCOMPtr<nsINode> imported = do_QueryInterface(aImportedNode);
       NS_ENSURE_TRUE(imported, NS_ERROR_FAILURE);
 
       nsCOMPtr<nsIDOMNode> newNode;
       nsCOMArray<nsINode> nodesWithProperties;
       rv = nsNodeUtils::Clone(imported, aDeep, mNodeInfoManager,
                               nodesWithProperties, getter_AddRefs(newNode));
@@ -6114,16 +6098,17 @@ nsDocument::AdoptNode(nsIDOMNode *aAdopt
       break;
     }
     case nsIDOMNode::DOCUMENT_FRAGMENT_NODE:
     case nsIDOMNode::ELEMENT_NODE:
     case nsIDOMNode::PROCESSING_INSTRUCTION_NODE:
     case nsIDOMNode::TEXT_NODE:
     case nsIDOMNode::CDATA_SECTION_NODE:
     case nsIDOMNode::COMMENT_NODE:
+    case nsIDOMNode::DOCUMENT_TYPE_NODE:
     {
       // We don't want to adopt an element into its own contentDocument or into
       // a descendant contentDocument, so we check if the frameElement of this
       // document or any of its parents is the adopted node or one of its
       // descendants.
       nsIDocument *doc = this;
       do {
         nsPIDOMWindow *win = doc->GetWindow();
@@ -6146,17 +6131,16 @@ nsDocument::AdoptNode(nsIDOMNode *aAdopt
 
       break;
     }
     case nsIDOMNode::ENTITY_REFERENCE_NODE:
     {
       return NS_ERROR_NOT_IMPLEMENTED;
     }
     case nsIDOMNode::DOCUMENT_NODE:
-    case nsIDOMNode::DOCUMENT_TYPE_NODE:
     case nsIDOMNode::ENTITY_NODE:
     case nsIDOMNode::NOTATION_NODE:
     {
       return NS_ERROR_DOM_NOT_SUPPORTED_ERR;
     }
     default:
     {
       NS_WARNING("Don't know how to adopt this nodetype for adoptNode.");
@@ -6418,17 +6402,17 @@ nsDocument::IsScriptEnabled()
   NS_ENSURE_TRUE(sm, PR_FALSE);
 
   nsIScriptGlobalObject* globalObject = GetScriptGlobalObject();
   NS_ENSURE_TRUE(globalObject, PR_FALSE);
 
   nsIScriptContext *scriptContext = globalObject->GetContext();
   NS_ENSURE_TRUE(scriptContext, PR_FALSE);
 
-  JSContext* cx = (JSContext *) scriptContext->GetNativeContext();
+  JSContext* cx = scriptContext->GetNativeContext();
   NS_ENSURE_TRUE(cx, PR_FALSE);
 
   PRBool enabled;
   nsresult rv = sm->CanExecuteScripts(cx, NodePrincipal(), &enabled);
   NS_ENSURE_SUCCESS(rv, PR_FALSE);
   return enabled;
 }
 
--- a/content/base/src/nsEventSource.cpp
+++ b/content/base/src/nsEventSource.cpp
@@ -1345,17 +1345,17 @@ nsEventSource::DispatchAllMessageEvents(
 
   // Let's play get the JSContext
   nsCOMPtr<nsIScriptGlobalObject> sgo = do_QueryInterface(mOwner);
   NS_ENSURE_TRUE(sgo,);
 
   nsIScriptContext* scriptContext = sgo->GetContext();
   NS_ENSURE_TRUE(scriptContext,);
 
-  JSContext* cx = (JSContext*)scriptContext->GetNativeContext();
+  JSContext* cx = scriptContext->GetNativeContext();
   NS_ENSURE_TRUE(cx,);
 
   while (mMessagesToDispatch.GetSize() > 0) {
     nsAutoPtr<Message>
       message(static_cast<Message*>(mMessagesToDispatch.PopFront()));
 
     // Now we can turn our string into a jsval
     jsval jsData;
--- a/content/base/src/nsFrameLoader.cpp
+++ b/content/base/src/nsFrameLoader.cpp
@@ -2065,17 +2065,17 @@ nsFrameLoader::EnsureMessageManager()
       mMessageManager->SetCallbackData(mRemoteBrowserShown ? this : nsnull);
     }
     return NS_OK;
   }
 
   nsIScriptContext* sctx = mOwnerContent->GetContextForEventHandlers(&rv);
   NS_ENSURE_SUCCESS(rv, rv);
   NS_ENSURE_STATE(sctx);
-  JSContext* cx = static_cast<JSContext*>(sctx->GetNativeContext());
+  JSContext* cx = sctx->GetNativeContext();
   NS_ENSURE_STATE(cx);
 
   nsCOMPtr<nsIDOMChromeWindow> chromeWindow =
     do_QueryInterface(mOwnerContent->GetOwnerDoc()->GetWindow());
   NS_ENSURE_STATE(chromeWindow);
   nsCOMPtr<nsIChromeFrameMessageManager> parentManager;
   chromeWindow->GetMessageManager(getter_AddRefs(parentManager));
 
--- a/content/base/src/nsGenericElement.cpp
+++ b/content/base/src/nsGenericElement.cpp
@@ -3589,24 +3589,18 @@ nsINode::doInsertChildAt(nsIContent* aKi
   // react to unexpected attribute changes.
   nsMutationGuard::DidMutate();
 
   // Do this before checking the child-count since this could cause mutations
   nsIDocument* doc = GetCurrentDoc();
   mozAutoDocUpdate updateBatch(doc, UPDATE_CONTENT_MODEL, aNotify);
 
   if (!HasSameOwnerDoc(aKid)) {
-    // DocumentType nodes are the only nodes that can have a null
-    // ownerDocument according to the DOM spec, and we need to allow
-    // inserting them w/o calling AdoptNode().
-    if (aKid->NodeType() != nsIDOMNode::DOCUMENT_TYPE_NODE ||
-        aKid->GetOwnerDoc()) {
-      rv = AdoptNodeIntoOwnerDoc(this, aKid);
-      NS_ENSURE_SUCCESS(rv, rv);
-    }
+    rv = AdoptNodeIntoOwnerDoc(this, aKid);
+    NS_ENSURE_SUCCESS(rv, rv);
   }
 
   PRUint32 childCount = aChildArray.ChildCount();
   NS_ENSURE_TRUE(aIndex <= childCount, NS_ERROR_ILLEGAL_VALUE);
   PRBool isAppend = (aIndex == childCount);
 
   rv = aChildArray.InsertChildAt(aKid, aIndex);
   NS_ENSURE_SUCCESS(rv, rv);
@@ -4108,19 +4102,17 @@ nsINode::ReplaceOrInsertBefore(PRBool aR
     }
   }
 
   // Move new child over to our document if needed. Do this after removing
   // it from its parent so that AdoptNode doesn't fire DOMNodeRemoved
   // DocumentType nodes are the only nodes that can have a null
   // ownerDocument according to the DOM spec, and we need to allow
   // inserting them w/o calling AdoptNode().
-  if (!HasSameOwnerDoc(newContent) &&
-      (nodeType != nsIDOMNode::DOCUMENT_TYPE_NODE ||
-       newContent->GetOwnerDoc())) {
+  if (!HasSameOwnerDoc(newContent)) {
     res = AdoptNodeIntoOwnerDoc(this, aNewChild);
     NS_ENSURE_SUCCESS(res, res);
   }
 
   /*
    * Check if we're inserting a document fragment. If we are, we need
    * to remove the children of the document fragment and add them
    * individually (i.e. we don't add the actual document fragment).
--- a/content/base/src/nsGkAtomList.h
+++ b/content/base/src/nsGkAtomList.h
@@ -685,16 +685,18 @@ GK_ATOM(onkeydown, "onkeydown")
 GK_ATOM(onkeypress, "onkeypress")
 GK_ATOM(onkeyup, "onkeyup")
 GK_ATOM(onLoad, "onLoad")
 GK_ATOM(onload, "onload")
 GK_ATOM(onpopstate, "onpopstate")
 GK_ATOM(only, "only")               // this one is not an event
 GK_ATOM(onmessage, "onmessage")
 GK_ATOM(onmousedown, "onmousedown")
+GK_ATOM(onmouseenter, "onmouseenter")
+GK_ATOM(onmouseleave, "onmouseleave")
 GK_ATOM(onmousemove, "onmousemove")
 GK_ATOM(onmouseout, "onmouseout")
 GK_ATOM(onmouseover, "onmouseover")
 GK_ATOM(onMozMouseHittest, "onMozMouseHittest")
 GK_ATOM(onmouseup, "onmouseup")
 GK_ATOM(onMozAfterPaint, "onMozAfterPaint")
 GK_ATOM(onMozBeforePaint, "onMozBeforePaint")
 GK_ATOM(onmozfullscreenchange, "onmozfullscreenchange")
--- a/content/base/src/nsNodeInfoManager.h
+++ b/content/base/src/nsNodeInfoManager.h
@@ -134,17 +134,16 @@ public:
     return mBindingManager;
   }
 
 protected:
   friend class nsDocument;
   friend class nsXULPrototypeDocument;
   friend nsresult NS_NewDOMDocumentType(nsIDOMDocumentType** ,
                                         nsNodeInfoManager *,
-                                        nsIPrincipal *,
                                         nsIAtom *,
                                         const nsAString& ,
                                         const nsAString& ,
                                         const nsAString& );
 
   /**
    * Sets the principal of the document this nodeinfo manager belongs to.
    */
--- a/content/base/src/nsNodeUtils.cpp
+++ b/content/base/src/nsNodeUtils.cpp
@@ -566,16 +566,19 @@ nsNodeUtils::CloneAndAdopt(nsINode *aNod
 #ifdef MOZ_MEDIA
           if (elm->MayHaveAudioAvailableEventListener()) {
             window->SetHasAudioAvailableEventListeners();
           }
 #endif
           if (elm->MayHaveTouchEventListener()) {
             window->SetHasTouchEventListeners();
           }
+          if (elm->MayHaveMouseEnterLeaveEventListener()) {
+            window->SetHasMouseEnterLeaveEventListeners();
+          }
         }
       }
     }
 
 #ifdef MOZ_MEDIA
     if (wasRegistered && oldDoc != newDoc) {
       nsCOMPtr<nsIDOMHTMLMediaElement> domMediaElem(do_QueryInterface(aNode));
       if (domMediaElem) {
--- a/content/base/src/nsScriptLoader.cpp
+++ b/content/base/src/nsScriptLoader.cpp
@@ -905,17 +905,17 @@ nsScriptLoader::EvaluateScript(nsScriptL
                           aRequest->mLineNo, aRequest->mJSVersion, nsnull,
                           &isUndefined);
 
   // Put the old script back in case it wants to do anything else.
   mCurrentScript = oldCurrent;
 
   JSContext *cx = nsnull; // Initialize this to keep GCC happy.
   if (stid == nsIProgrammingLanguage::JAVASCRIPT) {
-    cx = (JSContext *)context->GetNativeContext();
+    cx = context->GetNativeContext();
     ::JS_BeginRequest(cx);
     NS_ASSERTION(!::JS_IsExceptionPending(cx),
                  "JS_ReportPendingException wasn't called in EvaluateString");
   }
 
   context->SetProcessingScriptTag(oldProcessingScriptTag);
 
   if (stid == nsIProgrammingLanguage::JAVASCRIPT) {
--- a/content/base/src/nsWebSocket.cpp
+++ b/content/base/src/nsWebSocket.cpp
@@ -896,17 +896,17 @@ nsWebSocket::CreateAndDispatchMessageEve
 
   // Let's play get the JSContext
   nsCOMPtr<nsIScriptGlobalObject> sgo = do_QueryInterface(mOwner);
   NS_ENSURE_TRUE(sgo, NS_ERROR_FAILURE);
 
   nsIScriptContext* scriptContext = sgo->GetContext();
   NS_ENSURE_TRUE(scriptContext, NS_ERROR_FAILURE);
 
-  JSContext* cx = (JSContext*)scriptContext->GetNativeContext();
+  JSContext* cx = scriptContext->GetNativeContext();
   NS_ENSURE_TRUE(cx, NS_ERROR_FAILURE);
 
   // Now we can turn our string into a jsval
 
   jsval jsData;
   {
     NS_ConvertUTF8toUTF16 utf16Data(aData);
     JSString* jsString;
--- a/content/base/test/Makefile.in
+++ b/content/base/test/Makefile.in
@@ -501,16 +501,17 @@ include $(topsrcdir)/config/rules.mk
 		somedatas.resource \
 		somedatas.resource^headers^ \
 		delayedServerEvents.sjs \
 		test_bug664916.html \
 		test_bug666604.html \
 		test_bug675121.html \
 		file_bug675121.sjs \
 		test_bug654352.html \
+		test_bug675166.html \
 		test_bug682592.html \
 		bug682592-subframe.html \
 		bug682592-subframe-ref.html \
 		test_bug685798.html \
 		$(NULL)
 
 _CHROME_FILES =	\
 		test_bug357450.js \
--- a/content/base/test/test_bug450160.html
+++ b/content/base/test/test_bug450160.html
@@ -22,17 +22,17 @@ https://bugzilla.mozilla.org/show_bug.cg
 
 function testHTMLDocuments(ids, isXHTML) {
   for (var i = 0; i < ids.length; ++i) {
     var docType1 =
       document.implementation.createDocumentType(isXHTML ? "html" : "HTML",
                                                  ids[i],
                                                  null);
     ok(docType1, "No doctype?");
-    ok(!docType1.ownerDocument, "docType shouldn't have ownerDocument!");
+    ok(docType1.ownerDocument, "docType should have ownerDocument!");
     var doc1 = document.implementation.createDocument(null, null, docType1);
     is(docType1.ownerDocument, doc1, "docType should have ownerDocument!");
     ok(!doc1.documentElement, "Document shouldn't have document element!");
     is(doc1.body, null, "Shouldn't have .body!");
     ok(doc1 instanceof Components.interfaces.nsIDOMHTMLDocument,
        "Document should be an HTML document!");
     ok(!(doc1 instanceof Components.interfaces.nsIDOMSVGDocument),
        "Document shouldn't be an SVG document!");
@@ -59,17 +59,17 @@ function testHTMLDocuments(ids, isXHTML)
 }
 
 function testSVGDocument() {
   var docType1 =
       document.implementation.createDocumentType("svg",
                                                  "-//W3C//DTD SVG 1.1//EN",
                                                  null);
   ok(docType1, "No doctype?");
-  ok(!docType1.ownerDocument, "docType shouldn't have ownerDocument!");
+  ok(docType1.ownerDocument, "docType should have ownerDocument!");
   var doc1 = document.implementation.createDocument(null, null, docType1);
   is(docType1.ownerDocument, doc1, "docType should have ownerDocument!");
   ok(!doc1.documentElement, "Document shouldn't have document element!");
   ok(!(doc1 instanceof Components.interfaces.nsIDOMHTMLDocument),
      "Document shouldn't be an HTML document!");
   ok(doc1 instanceof Components.interfaces.nsIDOMSVGDocument,
      "Document should be an SVG document!");
 
@@ -86,17 +86,17 @@ function testSVGDocument() {
   ok(doc2.rootElement, "Should have .rootElement in document");
   is(doc2.rootElement.localName, "svg", "Wrong .rootElement!");
 }
 
 function testFooBarDocument() {
   var docType1 =
       document.implementation.createDocumentType("FooBar", "FooBar", null);
   ok(docType1, "No doctype?");
-  ok(!docType1.ownerDocument, "docType shouldn't have ownerDocument!");
+  ok(docType1.ownerDocument, "docType should have ownerDocument!");
   var doc1 = document.implementation.createDocument(null, null, docType1);
   is(docType1.ownerDocument, doc1, "docType should have ownerDocument!");
   ok(!doc1.documentElement, "Document shouldn't have document element!");
   ok(!(doc1 instanceof Components.interfaces.nsIDOMHTMLDocument),
      "Document shouldn't be an HTML document!");
   ok(!(doc1 instanceof Components.interfaces.nsIDOMSVGDocument),
      "Document shouldn't be an SVG document!");
 
new file mode 100644
--- /dev/null
+++ b/content/base/test/test_bug675166.html
@@ -0,0 +1,57 @@
+<!DOCTYPE HTML>
+<html>
+<!--
+https://bugzilla.mozilla.org/show_bug.cgi?id=675166
+-->
+<head>
+  <title>Test for Bug 675166</title>
+  <script type="application/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
+  <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/>
+</head>
+<body>
+<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=675166">Mozilla Bug 675166</a>
+<p id="display"></p>
+<div id="content" style="display: none">
+  
+</div>
+<pre id="test">
+<script type="application/javascript">
+
+/** Test for Bug 675166 **/
+
+
+var dt = document.implementation.createDocumentType("html", null, null);
+isnot(dt.ownerDocument, null, "DocumentType should have ownerDocument");
+
+var d = document.implementation.createDocument(null, null, dt);
+is(dt.ownerDocument, d, "DocumentType shouldn't have null ownerDocument");
+
+try {
+  document.implementation.createDocument(null, null, dt);
+  ok(true, "Creating document using already bound document type shouldn't throw!");
+} catch(ex) {
+  ok(false, "Creating document using already bound document type shouldn't throw!");
+}
+
+var d2 = document.implementation.createDocument(null, null, null);
+var dt2 = document.implementation.createDocumentType("html", null, null);
+d2.appendChild(dt2);
+is(dt2.ownerDocument, d2, "DocumentType shouldn't have null ownerDocument");
+
+is(document.ownerDocument, null, "Document's ownerDocument should be null!");
+is(document.documentElement.ownerDocument, document,
+   "Element should have ownerDocument!")
+
+is(dt2.parentNode, d2, "parentNode should be document!");
+d2.removeChild(dt2);
+is(dt2.parentNode, null, "parentNode should be null!");
+
+d.adoptNode(dt2);
+d2.adoptNode(dt2);
+d2.appendChild(dt2);
+is(dt2.parentNode, d2, "parentNode should be document!");
+
+</script>
+</pre>
+</body>
+</html>
--- a/content/events/public/nsEventNameList.h
+++ b/content/events/public/nsEventNameList.h
@@ -222,16 +222,24 @@ EVENT(loadedmetadata,
 EVENT(loadstart,
       NS_LOADSTART,
       EventNameType_HTML,
       NS_EVENT_NULL)
 EVENT(mousedown,
       NS_MOUSE_BUTTON_DOWN,
       EventNameType_All,
       NS_MOUSE_EVENT)
+EVENT(mouseenter,
+      NS_MOUSEENTER,
+      EventNameType_All,
+      NS_MOUSE_EVENT)
+EVENT(mouseleave,
+      NS_MOUSELEAVE,
+      EventNameType_All,
+      NS_MOUSE_EVENT)
 EVENT(mousemove,
       NS_MOUSE_MOVE,
       EventNameType_All,
       NS_MOUSE_EVENT)
 EVENT(mouseout,
       NS_MOUSE_EXIT_SYNTH,
       EventNameType_All,
       NS_MOUSE_EVENT)
--- a/content/events/src/nsDOMEvent.cpp
+++ b/content/events/src/nsDOMEvent.cpp
@@ -56,17 +56,17 @@
 #include "nsIScriptSecurityManager.h"
 #include "nsIScriptError.h"
 #include "nsDOMPopStateEvent.h"
 #include "mozilla/Preferences.h"
 
 using namespace mozilla;
 
 static const char* const sEventNames[] = {
-  "mousedown", "mouseup", "click", "dblclick", "mouseover",
+  "mousedown", "mouseup", "click", "dblclick", "mouseenter", "mouseleave", "mouseover",
   "mouseout", "MozMouseHittest", "mousemove", "contextmenu", "keydown", "keyup", "keypress",
   "focus", "blur", "load", "popstate", "beforescriptexecute",
   "afterscriptexecute", "beforeunload", "unload",
   "hashchange", "readystatechange", "abort", "error",
   "submit", "reset", "change", "select", "input", "invalid", "text",
   "compositionstart", "compositionend", "popupshowing", "popupshown",
   "popuphiding", "popuphidden", "close", "command", "broadcast", "commandupdate",
   "dragenter", "dragover", "dragexit", "dragdrop", "draggesture",
@@ -1104,16 +1104,20 @@ const char* nsDOMEvent::GetEventName(PRU
   case NS_MOUSE_BUTTON_DOWN:
     return sEventNames[eDOMEvents_mousedown];
   case NS_MOUSE_BUTTON_UP:
     return sEventNames[eDOMEvents_mouseup];
   case NS_MOUSE_CLICK:
     return sEventNames[eDOMEvents_click];
   case NS_MOUSE_DOUBLECLICK:
     return sEventNames[eDOMEvents_dblclick];
+  case NS_MOUSEENTER:
+    return sEventNames[eDOMEvents_mouseenter];
+  case NS_MOUSELEAVE:
+    return sEventNames[eDOMEvents_mouseleave];
   case NS_MOUSE_ENTER_SYNTH:
     return sEventNames[eDOMEvents_mouseover];
   case NS_MOUSE_EXIT_SYNTH:
     return sEventNames[eDOMEvents_mouseout];
   case NS_MOUSE_MOZHITTEST:
     return sEventNames[eDOMEvents_MozMouseHittest];
   case NS_MOUSE_MOVE:
     return sEventNames[eDOMEvents_mousemove];
--- a/content/events/src/nsDOMEvent.h
+++ b/content/events/src/nsDOMEvent.h
@@ -60,16 +60,18 @@ class nsDOMEvent : public nsIDOMEvent,
 public:
 
   // Note: this enum must be kept in sync with sEventNames in nsDOMEvent.cpp
   enum nsDOMEvents {
     eDOMEvents_mousedown=0,
     eDOMEvents_mouseup,
     eDOMEvents_click,
     eDOMEvents_dblclick,
+    eDOMEvents_mouseenter,
+    eDOMEvents_mouseleave,
     eDOMEvents_mouseover,
     eDOMEvents_mouseout,
     eDOMEvents_MozMouseHittest,
     eDOMEvents_mousemove,
     eDOMEvents_contextmenu,
     eDOMEvents_keydown,
     eDOMEvents_keyup,
     eDOMEvents_keypress,
--- a/content/events/src/nsEventListenerManager.cpp
+++ b/content/events/src/nsEventListenerManager.cpp
@@ -129,16 +129,17 @@ PRUint32 nsEventListenerManager::sCreate
 
 nsEventListenerManager::nsEventListenerManager(nsISupports* aTarget) :
   mMayHavePaintEventListener(PR_FALSE),
   mMayHaveMutationListeners(PR_FALSE),
   mMayHaveCapturingListeners(PR_FALSE),
   mMayHaveSystemGroupListeners(PR_FALSE),
   mMayHaveAudioAvailableEventListener(PR_FALSE),
   mMayHaveTouchEventListener(PR_FALSE),
+  mMayHaveMouseEnterLeaveEventListener(PR_FALSE),
   mNoListenerForEvent(0),
   mTarget(aTarget)
 {
   NS_ASSERTION(aTarget, "unexpected null pointer");
 
   ++sCreatedCount;
 }
 
@@ -288,16 +289,29 @@ nsEventListenerManager::AddEventListener
               aTypeAtom == nsGkAtoms::ontouchmove ||
               aTypeAtom == nsGkAtoms::ontouchenter ||
               aTypeAtom == nsGkAtoms::ontouchleave ||
               aTypeAtom == nsGkAtoms::ontouchcancel)) {
     mMayHaveTouchEventListener = PR_TRUE;
     nsPIDOMWindow* window = GetInnerWindowForTarget();
     if (window)
       window->SetHasTouchEventListeners();
+  } else if (aTypeAtom == nsGkAtoms::onmouseenter ||
+             aTypeAtom == nsGkAtoms::onmouseleave) {
+    mMayHaveMouseEnterLeaveEventListener = PR_TRUE;
+    nsPIDOMWindow* window = GetInnerWindowForTarget();
+    if (window) {
+#ifdef DEBUG
+      nsCOMPtr<nsIDocument> d = do_QueryInterface(window->GetExtantDocument());
+      NS_WARN_IF_FALSE(!nsContentUtils::IsChromeDoc(d),
+                       "Please do not use mouseenter/leave events in chrome. "
+                       "They are slower than mouseover/out!");
+#endif
+      window->SetHasMouseEnterLeaveEventListeners();
+    }
   }
 }
 
 void
 nsEventListenerManager::RemoveEventListener(nsIDOMEventListener *aListener, 
                                             PRUint32 aType,
                                             nsIAtom* aUserType,
                                             PRInt32 aFlags)
@@ -639,18 +653,17 @@ nsEventListenerManager::CompileEventHand
       nsIURI *uri = doc->GetDocumentURI();
       if (uri) {
         uri->GetSpec(url);
         lineNo = 1;
       }
     }
 
     nsCxPusher pusher;
-    if (aNeedsCxPush &&
-        !pusher.Push((JSContext*)context->GetNativeContext())) {
+    if (aNeedsCxPush && !pusher.Push(context->GetNativeContext())) {
       return NS_ERROR_FAILURE;
     }
 
 
     if (handlerOwner) {
       // Always let the handler owner compile the event
       // handler, as it may want to use a special
       // context or scope object.
--- a/content/events/src/nsEventListenerManager.h
+++ b/content/events/src/nsEventListenerManager.h
@@ -227,16 +227,18 @@ public:
   PRBool MayHaveAudioAvailableEventListener() { return mMayHaveAudioAvailableEventListener; }
 
   /**
    * Returns PR_TRUE if there may be a touch event listener registered,
    * PR_FALSE if there definitely isn't.
    */
   PRBool MayHaveTouchEventListener() { return mMayHaveTouchEventListener; }
 
+  PRBool MayHaveMouseEnterLeaveEventListener() { return mMayHaveMouseEnterLeaveEventListener; }
+
   PRInt64 SizeOf() const;
 protected:
   nsresult HandleEventSubType(nsListenerStruct* aListenerStruct,
                               nsIDOMEventListener* aListener,
                               nsIDOMEvent* aDOMEvent,
                               nsIDOMEventTarget* aCurrentTarget,
                               PRUint32 aPhaseFlags,
                               nsCxPusher* aPusher);
@@ -297,17 +299,18 @@ protected:
   nsPIDOMWindow* GetInnerWindowForTarget();
 
   PRUint32 mMayHavePaintEventListener : 1;
   PRUint32 mMayHaveMutationListeners : 1;
   PRUint32 mMayHaveCapturingListeners : 1;
   PRUint32 mMayHaveSystemGroupListeners : 1;
   PRUint32 mMayHaveAudioAvailableEventListener : 1;
   PRUint32 mMayHaveTouchEventListener : 1;
-  PRUint32 mNoListenerForEvent : 26;
+  PRUint32 mMayHaveMouseEnterLeaveEventListener : 1;
+  PRUint32 mNoListenerForEvent : 25;
 
   nsAutoTObserverArray<nsListenerStruct, 2> mListeners;
   nsISupports*                              mTarget;  //WEAK
   nsCOMPtr<nsIAtom>                         mNoListenerForEventAtom;
 
   static PRUint32                           mInstanceCount;
   static jsid                               sAddListenerID;
 
--- a/content/events/src/nsEventStateManager.cpp
+++ b/content/events/src/nsEventStateManager.cpp
@@ -3834,16 +3834,60 @@ nsEventStateManager::DispatchMouseEvent(
   }
 
   mCurrentTargetContent = nsnull;
   mCurrentTarget = previousTarget;
 
   return targetFrame;
 }
 
+class MouseEnterLeaveDispatcher
+{
+public:
+  MouseEnterLeaveDispatcher(nsEventStateManager* aESM,
+                            nsIContent* aTarget, nsIContent* aRelatedTarget,
+                            nsGUIEvent* aEvent, PRUint32 aType)
+  : mESM(aESM), mEvent(aEvent), mType(aType)
+  {
+    nsPIDOMWindow* win =
+      aTarget ? aTarget->GetOwnerDoc()->GetInnerWindow() : nsnull;
+    if (win && win->HasMouseEnterLeaveEventListeners()) {
+      mRelatedTarget = aRelatedTarget ?
+        aRelatedTarget->FindFirstNonNativeAnonymous() : nsnull;
+      nsINode* commonParent = nsnull;
+      if (aTarget && aRelatedTarget) {
+        commonParent =
+          nsContentUtils::GetCommonAncestor(aTarget, aRelatedTarget);
+      }
+      nsIContent* current = aTarget;
+      // Note, it is ok if commonParent is null!
+      while (current && current != commonParent) {
+        if (!current->IsInNativeAnonymousSubtree()) {
+          mTargets.AppendObject(current);
+        }
+        // mouseenter/leave is fired only on elements.
+        current = current->GetParent();
+      }
+    }
+  }
+
+  ~MouseEnterLeaveDispatcher()
+  {
+    for (PRInt32 i = 0; i < mTargets.Count(); ++i) {
+      mESM->DispatchMouseEvent(mEvent, mType, mTargets[i], mRelatedTarget);
+    }
+  }
+
+  nsEventStateManager*   mESM;
+  nsCOMArray<nsIContent> mTargets;
+  nsCOMPtr<nsIContent>   mRelatedTarget;
+  nsGUIEvent*            mEvent;
+  PRUint32               mType;
+};
+
 void
 nsEventStateManager::NotifyMouseOut(nsGUIEvent* aEvent, nsIContent* aMovingInto)
 {
   if (!mLastMouseOverElement)
     return;
   // Before firing mouseout, check for recursion
   if (mLastMouseOverElement == mFirstMouseOutEventElement)
     return;
@@ -3879,17 +3923,20 @@ nsEventStateManager::NotifyMouseOut(nsGU
   // Don't touch hover state if aMovingInto is non-null.  Caller will update
   // hover state itself, and we have optimizations for hover switching between
   // two nearby elements both deep in the DOM tree that would be defeated by
   // switching the hover state to null here.
   if (!aMovingInto) {
     // Unset :hover
     SetContentState(nsnull, NS_EVENT_STATE_HOVER);
   }
-  
+
+  MouseEnterLeaveDispatcher leaveDispatcher(this, mLastMouseOverElement, aMovingInto,
+                                            aEvent, NS_MOUSELEAVE);
+
   // Fire mouseout
   DispatchMouseEvent(aEvent, NS_MOUSE_EXIT_SYNTH,
                      mLastMouseOverElement, aMovingInto);
   
   mLastMouseOverFrame = nsnull;
   mLastMouseOverElement = nsnull;
   
   // Turn recursion protection back off
@@ -3927,16 +3974,19 @@ nsEventStateManager::NotifyMouseOver(nsG
   // of havoc.  Reverify and take care.
   if (mLastMouseOverElement == aContent)
     return;
 
   // Remember mLastMouseOverElement as the related content for the
   // DispatchMouseEvent() call below, since NotifyMouseOut() resets it, bug 298477.
   nsCOMPtr<nsIContent> lastMouseOverElement = mLastMouseOverElement;
 
+  MouseEnterLeaveDispatcher enterDispatcher(this, aContent, lastMouseOverElement,
+                                            aEvent, NS_MOUSEENTER);
+  
   NotifyMouseOut(aEvent, aContent);
 
   // Store the first mouseOver event we fire and don't refire mouseOver
   // to that element while the first mouseOver is still ongoing.
   mFirstMouseOverEventElement = aContent;
   
   SetContentState(aContent, NS_EVENT_STATE_HOVER);
   
--- a/content/events/src/nsEventStateManager.h
+++ b/content/events/src/nsEventStateManager.h
@@ -61,16 +61,17 @@
 #include "nsContentUtils.h"
 
 class nsIPresShell;
 class nsIDocShell;
 class nsIDocShellTreeNode;
 class nsIDocShellTreeItem;
 class imgIContainer;
 class nsDOMDataTransfer;
+class MouseEnterLeaveDispatcher;
 
 namespace mozilla {
 namespace dom {
 class TabParent;
 }
 }
 
 /*
@@ -223,16 +224,18 @@ public:
   // if aContent is non-null, marks the object as active.
   static void SetActiveManager(nsEventStateManager* aNewESM,
                                nsIContent* aContent);
 
   // Sets the full-screen event state on aElement to aIsFullScreen.
   static void SetFullScreenState(mozilla::dom::Element* aElement, PRBool aIsFullScreen);
 
 protected:
+  friend class MouseEnterLeaveDispatcher;
+
   void UpdateCursor(nsPresContext* aPresContext, nsEvent* aEvent, nsIFrame* aTargetFrame, nsEventStatus* aStatus);
   /**
    * Turn a GUI mouse event into a mouse event targeted at the specified
    * content.  This returns the primary frame for the content (or null
    * if it goes away during the event).
    */
   nsIFrame* DispatchMouseEvent(nsGUIEvent* aEvent, PRUint32 aMessage,
                                nsIContent* aTargetContent,
--- a/content/events/test/Makefile.in
+++ b/content/events/test/Makefile.in
@@ -66,16 +66,17 @@ include $(topsrcdir)/config/rules.mk
 		test_bug379120.html \
 		test_bug391568.xhtml \
 		test_bug402089.html \
 		test_bug405632.html \
 		test_bug409604.html \
 		test_bug412567.html \
 		test_bug426082.html \
 		test_bug427537.html \
+		test_bug432698.html \
 		test_bug443985.html \
 		test_bug447736.html \
 		test_bug450876.html \
 		test_bug456273.html \
 		test_bug457672.html \
 		test_bug428988.html \
 		bug457672.html \
 		test_draggableprop.html \
new file mode 100644
--- /dev/null
+++ b/content/events/test/test_bug432698.html
@@ -0,0 +1,190 @@
+<!DOCTYPE HTML>
+<html>
+<!--
+https://bugzilla.mozilla.org/show_bug.cgi?id=432698
+-->
+<head>
+  <title>Test for Bug 432698</title>
+  <script type="application/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
+  <script type="application/javascript" src="/tests/SimpleTest/EventUtils.js"></script>
+  <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/>
+</head>
+<body>
+<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=432698">Mozilla Bug 432698</a>
+<p id="display"></p>
+<div id="content" style="display: none">
+  
+</div>
+<pre id="test">
+<script type="application/javascript">
+
+/** Test for Bug 432698 **/
+SimpleTest.waitForExplicitFinish();
+SimpleTest.waitForFocus(runTests);
+var outer;
+var middle;
+var inner;
+var outside;
+var container;
+var file;
+var iframe;
+var checkRelatedTarget = false;
+var expectedRelatedEnter = null;
+var expectedRelatedLeave = null;
+var mouseentercount = 0;
+var mouseleavecount = 0;
+var mouseovercount = 0;
+var mouseoutcount = 0;
+
+function sendMouseEvent(t, elem) {
+  var r = elem.getBoundingClientRect();
+  synthesizeMouse(elem, r.width / 2, r.height / 2, {type: t});
+}
+
+function runTests() {
+  outer = document.getElementById("outertest");
+  middle = document.getElementById("middletest");
+  inner = document.getElementById("innertest");
+  outside = document.getElementById("outside");
+  container = document.getElementById("container");
+  file = document.getElementById("file");
+  iframe = document.getElementById("iframe");
+
+  // Make sure ESM thinks mouse is outside the test elements.
+  sendMouseEvent("mousemove", outside);
+
+  mouseentercount = 0;
+  mouseleavecount = 0;
+  mouseovercount = 0;
+  mouseoutcount = 0;
+  checkRelatedTarget = true;
+  expectedRelatedEnter = outside;
+  expectedRelatedLeave = inner;
+  sendMouseEvent("mousemove", inner);
+  is(mouseentercount, 3, "Unexpected mouseenter event count!");
+  is(mouseovercount, 1, "Unexpected mouseover event count!");
+  is(mouseoutcount, 0, "Unexpected mouseout event count!");
+  is(mouseleavecount, 0, "Unexpected mouseleave event count!");
+  expectedRelatedEnter = inner;
+  expectedRelatedLeave = outside;
+  sendMouseEvent("mousemove", outside);
+  is(mouseentercount, 3, "Unexpected mouseenter event count!");
+  is(mouseovercount, 1, "Unexpected mouseover event count!");
+  is(mouseoutcount, 1, "Unexpected mouseout event count!");
+  is(mouseleavecount, 3, "Unexpected mouseleave event count!");
+
+  // Event handling over native anonymous content.
+  var r = file.getBoundingClientRect();
+  expectedRelatedEnter = outside;
+  expectedRelatedLeave = file;
+  synthesizeMouse(file, r.width / 6, r.height / 2, {type: "mousemove"});
+  is(mouseentercount, 4, "Unexpected mouseenter event count!");
+  is(mouseovercount, 2, "Unexpected mouseover event count!");
+  is(mouseoutcount, 1, "Unexpected mouseout event count!");
+  is(mouseleavecount, 3, "Unexpected mouseleave event count!");
+
+  // Moving mouse over type="file" shouldn't cause mouseover/out/enter/leave events
+  synthesizeMouse(file, r.width - (r.width / 6), r.height / 2, {type: "mousemove"});
+  is(mouseentercount, 4, "Unexpected mouseenter event count!");
+  is(mouseovercount, 2, "Unexpected mouseover event count!");
+  is(mouseoutcount, 1, "Unexpected mouseout event count!");
+  is(mouseleavecount, 3, "Unexpected mouseleave event count!");
+
+  expectedRelatedEnter = file;
+  expectedRelatedLeave = outside;
+  sendMouseEvent("mousemove", outside);
+  is(mouseentercount, 4, "Unexpected mouseenter event count!");
+  is(mouseovercount, 2, "Unexpected mouseover event count!");
+  is(mouseoutcount, 2, "Unexpected mouseout event count!");
+  is(mouseleavecount, 4, "Unexpected mouseleave event count!");
+  
+  // Initialize iframe
+  iframe.contentDocument.documentElement.style.overflow = "hidden";
+  iframe.contentDocument.body.style.margin = "0px";
+  iframe.contentDocument.body.style.width = "100%";
+  iframe.contentDocument.body.style.height = "100%";
+  iframe.contentDocument.body.innerHTML =
+    "<div style='width: 100%; height: 50%; border: 1px solid black;'></div>" +
+    "<div style='width: 100%; height: 50%; border: 1px solid black;'></div>";
+  iframe.contentDocument.body.offsetLeft; // flush
+
+  iframe.contentDocument.body.firstChild.onmouseenter = menter;
+  iframe.contentDocument.body.firstChild.onmouseleave = mleave;
+  iframe.contentDocument.body.lastChild.onmouseenter = menter;
+  iframe.contentDocument.body.lastChild.onmouseleave = mleave;
+  r = iframe.getBoundingClientRect();
+  expectedRelatedEnter = outside;
+  expectedRelatedLeave = iframe;
+  // Move mouse inside the iframe.
+  synthesizeMouse(iframe.contentDocument.body, r.width / 2, r.height / 4, {type: "mousemove"},
+                  iframe.contentWindow);
+  synthesizeMouse(iframe.contentDocument.body, r.width / 2, r.height - (r.height / 4), {type: "mousemove"},
+                  iframe.contentWindow);
+  is(mouseentercount, 7, "Unexpected mouseenter event count!");
+  expectedRelatedEnter = iframe;
+  expectedRelatedLeave = outside;
+  sendMouseEvent("mousemove", outside);
+  is(mouseleavecount, 7, "Unexpected mouseleave event count!");
+
+  SimpleTest.finish();
+}
+
+function menter(evt) {
+  ++mouseentercount;
+  evt.stopPropagation();
+  is(evt.bubbles, false, evt.type + " should not bubble!");
+  is(evt.cancelable, false, evt.type + " is not cancelable!");
+  is(evt.target, evt.currentTarget, "Wrong event target!");
+  ok(!evt.relatedTarget || evt.target.ownerDocument == evt.relatedTarget.ownerDocument,
+     "Leaking nodes to another document?");
+  if (checkRelatedTarget && evt.target.ownerDocument == document) {
+    is(evt.relatedTarget, expectedRelatedEnter, "Wrong related target (mouseenter)");
+  }
+}
+
+function mleave(evt) {
+  ++mouseleavecount;
+  evt.stopPropagation();
+  is(evt.bubbles, false, evt.type + " should not bubble!");
+  is(evt.cancelable, false, evt.type + " is not cancelable!");
+  is(evt.target, evt.currentTarget, "Wrong event target!");
+  ok(!evt.relatedTarget || evt.target.ownerDocument == evt.relatedTarget.ownerDocument,
+     "Leaking nodes to another document?");
+  if (checkRelatedTarget && evt.target.ownerDocument == document) {
+    is(evt.relatedTarget, expectedRelatedLeave, "Wrong related target (mouseleave)");
+  }
+}
+
+function mover(evt) {
+  ++mouseovercount;
+  evt.stopPropagation();
+}
+
+function mout(evt) {
+  ++mouseoutcount;
+  evt.stopPropagation();
+}
+
+</script>
+</pre>
+<div id="container" onmouseenter="menter(event)" onmouseleave="mleave(event)"
+                    onmouseout="mout(event)" onmouseover="mover(event)">
+  <div id="outside" onmouseout="event.stopPropagation()" onmouseover="event.stopPropagation()">foo</div>
+  <div id="outertest" onmouseenter="menter(event)" onmouseleave="mleave(event)"
+                      onmouseout="mout(event)" onmouseover="mover(event)">
+    <div id="middletest" onmouseenter="menter(event)" onmouseleave="mleave(event)"
+                         onmouseout="mout(event)" onmouseover="mover(event)">
+      <div id="innertest" onmouseenter="menter(event)" onmouseleave="mleave(event)"
+                          onmouseout="mout(event)" onmouseover="mover(event)">foo</div>
+    </div>
+  </div>
+  <input type="file" id="file"
+         onmouseenter="menter(event)" onmouseleave="mleave(event)"
+         onmouseout="mout(event)" onmouseover="mover(event)">
+  <br>
+  <iframe id="iframe" width="50px" height="50px"
+          onmouseenter="menter(event)" onmouseleave="mleave(event)"
+          onmouseout="mout(event)" onmouseover="mover(event)"></iframe>
+</div>
+</body>
+</html>
--- a/content/html/content/public/nsHTMLAudioElement.h
+++ b/content/html/content/public/nsHTMLAudioElement.h
@@ -45,18 +45,17 @@
 typedef PRUint16 nsMediaNetworkState;
 typedef PRUint16 nsMediaReadyState;
 
 class nsHTMLAudioElement : public nsHTMLMediaElement,
                            public nsIDOMHTMLAudioElement,
                            public nsIJSNativeInitializer
 {
 public:
-  nsHTMLAudioElement(already_AddRefed<nsINodeInfo> aNodeInfo,
-                     mozilla::dom::FromParser aFromParser = mozilla::dom::NOT_FROM_PARSER);
+  nsHTMLAudioElement(already_AddRefed<nsINodeInfo> aNodeInfo);
   virtual ~nsHTMLAudioElement();
 
   // nsISupports
   NS_DECL_ISUPPORTS_INHERITED
 
   // nsIDOMNode
   NS_FORWARD_NSIDOMNODE(nsHTMLMediaElement::)
 
--- a/content/html/content/public/nsHTMLMediaElement.h
+++ b/content/html/content/public/nsHTMLMediaElement.h
@@ -68,18 +68,17 @@ public:
   typedef mozilla::TimeDuration TimeDuration;
 
   enum CanPlayStatus {
     CANPLAY_NO,
     CANPLAY_MAYBE,
     CANPLAY_YES
   };
 
-  nsHTMLMediaElement(already_AddRefed<nsINodeInfo> aNodeInfo,
-                     mozilla::dom::FromParser aFromParser = mozilla::dom::NOT_FROM_PARSER);
+  nsHTMLMediaElement(already_AddRefed<nsINodeInfo> aNodeInfo);
   virtual ~nsHTMLMediaElement();
 
   /**
    * This is used when the browser is constructing a video element to play
    * a channel that we've already started loading. The src attribute and
    * <source> children are ignored.
    * @param aChannel the channel to use
    * @param aListener returns a stream listener that should receive
--- a/content/html/content/public/nsHTMLVideoElement.h
+++ b/content/html/content/public/nsHTMLVideoElement.h
@@ -40,18 +40,17 @@
 
 #include "nsIDOMHTMLVideoElement.h"
 #include "nsHTMLMediaElement.h"
 
 class nsHTMLVideoElement : public nsHTMLMediaElement,
                            public nsIDOMHTMLVideoElement
 {
 public:
-  nsHTMLVideoElement(already_AddRefed<nsINodeInfo> aNodeInfo,
-                     mozilla::dom::FromParser aFromParser = mozilla::dom::NOT_FROM_PARSER);
+  nsHTMLVideoElement(already_AddRefed<nsINodeInfo> aNodeInfo);
   virtual ~nsHTMLVideoElement();
 
   // nsISupports
   NS_DECL_ISUPPORTS_INHERITED
 
   // nsIDOMNode
   NS_FORWARD_NSIDOMNODE(nsHTMLMediaElement::)
 
--- a/content/html/content/src/nsGenericHTMLElement.cpp
+++ b/content/html/content/src/nsGenericHTMLElement.cpp
@@ -2500,17 +2500,17 @@ nsGenericHTMLFormElement::nsGenericHTMLF
   // We should add the NS_EVENT_STATE_ENABLED bit here as needed, but
   // that depends on our type, which is not initialized yet.  So we
   // have to do this in subclasses.
 }
 
 nsGenericHTMLFormElement::~nsGenericHTMLFormElement()
 {
   if (mFieldSet) {
-    static_cast<nsHTMLFieldSetElement*>(mFieldSet)->RemoveElement(this);
+    mFieldSet->RemoveElement(this);
   }
 
   // Check that this element doesn't know anything about its form at this point.
   NS_ASSERTION(!mForm, "mForm should be null at this point!");
 }
 
 NS_IMPL_QUERY_INTERFACE_INHERITED1(nsGenericHTMLFormElement,
                                    nsGenericHTMLElement,
@@ -2837,16 +2837,32 @@ nsGenericHTMLFormElement::PreHandleEvent
         break;
       }
     }
   }
 
   return nsGenericHTMLElement::PreHandleEvent(aVisitor);
 }
 
+/* virtual */
+bool
+nsGenericHTMLFormElement::IsDisabled() const
+{
+  return HasAttr(kNameSpaceID_None, nsGkAtoms::disabled) ||
+         (mFieldSet && mFieldSet->IsDisabled());
+}
+
+void
+nsGenericHTMLFormElement::ForgetFieldSet(nsIContent* aFieldset)
+{
+  if (mFieldSet == aFieldset) {
+    mFieldSet = nsnull;
+  }
+}
+
 PRBool
 nsGenericHTMLFormElement::CanBeDisabled() const
 {
   PRInt32 type = GetType();
   // It's easier to test the types that _cannot_ be disabled
   return
     type != NS_FORM_LABEL &&
     type != NS_FORM_OBJECT &&
@@ -3087,42 +3103,40 @@ nsGenericHTMLFormElement::UpdateFormOwne
 void
 nsGenericHTMLFormElement::UpdateFieldSet(PRBool aNotify)
 {
   nsIContent* parent = nsnull;
   nsIContent* prev = nsnull;
 
   for (parent = GetParent(); parent;
        prev = parent, parent = parent->GetParent()) {
-    if (parent->IsHTML(nsGkAtoms::fieldset)) {
-      nsHTMLFieldSetElement* fieldset =
-        static_cast<nsHTMLFieldSetElement*>(parent);
-
-      if (!prev || fieldset->GetFirstLegend() != prev) {
-        if (mFieldSet == fieldset) {
-          // We already have the right fieldset;
-          return;
-        }
-
-        if (mFieldSet) {
-          static_cast<nsHTMLFieldSetElement*>(mFieldSet)->RemoveElement(this);
-        }
-        mFieldSet = fieldset;
-        fieldset->AddElement(this);
-
-        // The disabled state may have changed
-        FieldSetDisabledChanged(aNotify);
+    nsHTMLFieldSetElement* fieldset =
+      nsHTMLFieldSetElement::FromContent(parent);
+    if (fieldset &&
+        (!prev || fieldset->GetFirstLegend() != prev)) {
+      if (mFieldSet == fieldset) {
+        // We already have the right fieldset;
         return;
       }
+
+      if (mFieldSet) {
+        mFieldSet->RemoveElement(this);
+      }
+      mFieldSet = fieldset;
+      fieldset->AddElement(this);
+
+      // The disabled state may have changed
+      FieldSetDisabledChanged(aNotify);
+      return;
     }
   }
 
   // No fieldset found.
   if (mFieldSet) {
-    static_cast<nsHTMLFieldSetElement*>(mFieldSet)->RemoveElement(this);
+    mFieldSet->RemoveElement(this);
     mFieldSet = nsnull;
     // The disabled state may have changed
     FieldSetDisabledChanged(aNotify);
   }
 }
 
 void
 nsGenericHTMLFormElement::FieldSetDisabledChanged(PRBool aNotify)
--- a/content/html/content/src/nsGenericHTMLElement.h
+++ b/content/html/content/src/nsGenericHTMLElement.h
@@ -830,16 +830,18 @@ protected:
 
 private:
   void ChangeEditableState(PRInt32 aChange);
 };
 
 
 //----------------------------------------------------------------------
 
+class nsHTMLFieldSetElement;
+
 /**
  * A helper class for form elements that can contain children
  */
 class nsGenericHTMLFormElement : public nsGenericHTMLElement,
                                  public nsIFormControl
 {
 public:
   nsGenericHTMLFormElement(already_AddRefed<nsINodeInfo> aNodeInfo);
@@ -880,20 +882,17 @@ public:
                               PRBool aCompileEventHandlers);
   virtual void UnbindFromTree(PRBool aDeep = PR_TRUE,
                               PRBool aNullParent = PR_TRUE);
   virtual PRUint32 GetDesiredIMEState();
   virtual nsEventStates IntrinsicState() const;
 
   virtual nsresult PreHandleEvent(nsEventChainPreVisitor& aVisitor);
 
-  virtual bool IsDisabled() const {
-    return HasAttr(kNameSpaceID_None, nsGkAtoms::disabled) ||
-           (mFieldSet && mFieldSet->IsDisabled());
-  }
+  virtual bool IsDisabled() const;
 
   /**
    * This callback is called by a fieldest on all its elements whenever its
    * disabled attribute is changed so the element knows its disabled state
    * might have changed.
    *
    * @note Classes redefining this method should not do any content
    * state updates themselves but should just make sure to call into
@@ -907,21 +906,17 @@ public:
 
   /**
    * This callback is called by a fieldset on all it's elements when it's being
    * destroyed. When called, the elements should check that aFieldset is there
    * first parent fieldset and null mFieldset in that case only.
    *
    * @param aFieldSet The fieldset being removed.
    */
-  void ForgetFieldSet(nsIContent* aFieldset) {
-    if (mFieldSet == aFieldset) {
-      mFieldSet = nsnull;
-    }
-  }
+  void ForgetFieldSet(nsIContent* aFieldset);
 
   /**
    * Returns if the control can be disabled.
    */
   PRBool CanBeDisabled() const;
 
   virtual PRBool IsHTMLFocusable(PRBool aWithMouse, PRBool* aIsFocusable,
                                  PRInt32* aTabIndex);
@@ -989,17 +984,17 @@ protected:
   // Get our focus state.  If this returns eInactiveWindow, it will set this
   // element as the focused element for that window.
   FocusTristate FocusState();
 
   /** The form that contains this control */
   nsHTMLFormElement* mForm;
 
   /* This is a pointer to our closest fieldset parent if any */
-  nsGenericHTMLFormElement* mFieldSet;
+  nsHTMLFieldSetElement* mFieldSet;
 };
 
 // If this flag is set on an nsGenericHTMLFormElement, that means that we have
 // added ourselves to our mForm.  It's possible to have a non-null mForm, but
 // not have this flag set.  That happens when the form is set via the content
 // sink.
 #define ADDED_TO_FORM (1 << ELEMENT_TYPE_SPECIFIC_BITS_OFFSET)
 
--- a/content/html/content/src/nsHTMLAudioElement.cpp
+++ b/content/html/content/src/nsHTMLAudioElement.cpp
@@ -85,17 +85,17 @@ NS_NewHTMLAudioElement(already_AddRefed<
     NS_ENSURE_TRUE(doc, nsnull);
 
     nodeInfo = doc->NodeInfoManager()->GetNodeInfo(nsGkAtoms::audio, nsnull,
                                                    kNameSpaceID_XHTML,
                                                    nsIDOMNode::ELEMENT_NODE);
     NS_ENSURE_TRUE(nodeInfo, nsnull);
   }
 
-  return new nsHTMLAudioElement(nodeInfo.forget(), aFromParser);
+  return new nsHTMLAudioElement(nodeInfo.forget());
 }
 
 NS_IMPL_ADDREF_INHERITED(nsHTMLAudioElement, nsHTMLMediaElement)
 NS_IMPL_RELEASE_INHERITED(nsHTMLAudioElement, nsHTMLMediaElement)
 
 DOMCI_NODE_DATA(HTMLAudioElement, nsHTMLAudioElement)
 
 NS_INTERFACE_TABLE_HEAD(nsHTMLAudioElement)
@@ -103,19 +103,18 @@ NS_HTML_CONTENT_INTERFACE_TABLE3(nsHTMLA
                                  nsIDOMHTMLAudioElement, nsIJSNativeInitializer)
 NS_HTML_CONTENT_INTERFACE_TABLE_TO_MAP_SEGUE(nsHTMLAudioElement,
                                                nsHTMLMediaElement)
 NS_HTML_CONTENT_INTERFACE_TABLE_TAIL_CLASSINFO(HTMLAudioElement)
 
 NS_IMPL_ELEMENT_CLONE(nsHTMLAudioElement)
 
 
-nsHTMLAudioElement::nsHTMLAudioElement(already_AddRefed<nsINodeInfo> aNodeInfo,
-                                       FromParser aFromParser)
-  : nsHTMLMediaElement(aNodeInfo, aFromParser)
+nsHTMLAudioElement::nsHTMLAudioElement(already_AddRefed<nsINodeInfo> aNodeInfo)
+  : nsHTMLMediaElement(aNodeInfo)
 {
 }
 
 nsHTMLAudioElement::~nsHTMLAudioElement()
 {
 }
 
 NS_IMETHODIMP
--- a/content/html/content/src/nsHTMLFieldSetElement.h
+++ b/content/html/content/src/nsHTMLFieldSetElement.h
@@ -48,16 +48,25 @@ class nsHTMLFieldSetElement : public nsG
                               public nsIConstraintValidation
 {
 public:
   using nsIConstraintValidation::GetValidationMessage;
 
   nsHTMLFieldSetElement(already_AddRefed<nsINodeInfo> aNodeInfo);
   virtual ~nsHTMLFieldSetElement();
 
+  /** Typesafe, non-refcounting cast from nsIContent.  Cheaper than QI. **/
+  static nsHTMLFieldSetElement* FromContent(nsIContent* aContent)
+  {
+    if (!aContent || !aContent->IsHTML(nsGkAtoms::fieldset)) {
+      return nsnull;
+    }
+    return static_cast<nsHTMLFieldSetElement*>(aContent);
+  }
+
   // nsISupports
   NS_DECL_ISUPPORTS_INHERITED
 
   // nsIDOMNode
   NS_FORWARD_NSIDOMNODE(nsGenericHTMLFormElement::)
 
   // nsIDOMElement
   NS_FORWARD_NSIDOMELEMENT(nsGenericHTMLFormElement::)
--- a/content/html/content/src/nsHTMLMediaElement.cpp
+++ b/content/html/content/src/nsHTMLMediaElement.cpp
@@ -45,22 +45,18 @@
 #include "nsIPresShell.h"
 #include "nsGkAtoms.h"
 #include "nsSize.h"
 #include "nsIFrame.h"
 #include "nsIDocument.h"
 #include "nsIDOMDocument.h"
 #include "nsDOMError.h"
 #include "nsNodeInfoManager.h"
-#include "plbase64.h"
-#include "nsNetUtil.h"
-#include "prmem.h"
 #include "nsNetUtil.h"
 #include "nsXPCOMStrings.h"
-#include "prlock.h"
 #include "nsThreadUtils.h"
 #include "nsIThreadInternal.h"
 #include "nsContentUtils.h"
 #include "nsFrameManager.h"
 #include "nsIScriptSecurityManager.h"
 #include "nsIXPConnect.h"
 #include "jsapi.h"
 
@@ -1264,18 +1260,17 @@ NS_IMETHODIMP nsHTMLMediaElement::SetMut
     mAudioStream->SetVolume(mMuted ? 0.0 : mVolume);
   }
 
   DispatchAsyncEvent(NS_LITERAL_STRING("volumechange"));
 
   return NS_OK;
 }
 
-nsHTMLMediaElement::nsHTMLMediaElement(already_AddRefed<nsINodeInfo> aNodeInfo,
-                                       FromParser aFromParser)
+nsHTMLMediaElement::nsHTMLMediaElement(already_AddRefed<nsINodeInfo> aNodeInfo)
   : nsGenericHTMLElement(aNodeInfo),
     mCurrentLoadID(0),
     mNetworkState(nsIDOMHTMLMediaElement::NETWORK_EMPTY),
     mReadyState(nsIDOMHTMLMediaElement::HAVE_NOTHING),
     mLoadWaitStatus(NOT_WAITING),
     mVolume(1.0),
     mChannels(0),
     mRate(0),
--- a/content/html/content/src/nsHTMLVideoElement.cpp
+++ b/content/html/content/src/nsHTMLVideoElement.cpp
@@ -61,17 +61,17 @@
 #include "nsITimer.h"
 
 #include "nsEventDispatcher.h"
 #include "nsIDOMProgressEvent.h"
 #include "nsMediaError.h"
 
 using namespace mozilla::dom;
 
-NS_IMPL_NS_NEW_HTML_ELEMENT_CHECK_PARSER(Video)
+NS_IMPL_NS_NEW_HTML_ELEMENT(Video)
 
 NS_IMPL_ADDREF_INHERITED(nsHTMLVideoElement, nsHTMLMediaElement)
 NS_IMPL_RELEASE_INHERITED(nsHTMLVideoElement, nsHTMLMediaElement)
 
 DOMCI_NODE_DATA(HTMLVideoElement, nsHTMLVideoElement)
 
 NS_INTERFACE_TABLE_HEAD(nsHTMLVideoElement)
   NS_HTML_CONTENT_INTERFACE_TABLE2(nsHTMLVideoElement, nsIDOMHTMLMediaElement, nsIDOMHTMLVideoElement)
@@ -95,19 +95,18 @@ NS_IMETHODIMP nsHTMLVideoElement::GetVid
 
 /* readonly attribute unsigned long videoHeight; */
 NS_IMETHODIMP nsHTMLVideoElement::GetVideoHeight(PRUint32 *aVideoHeight)
 {
   *aVideoHeight = mMediaSize.height == -1 ? 0 : mMediaSize.height;
   return NS_OK;
 }
 
-nsHTMLVideoElement::nsHTMLVideoElement(already_AddRefed<nsINodeInfo> aNodeInfo,
-                                       FromParser aFromParser)
-  : nsHTMLMediaElement(aNodeInfo, aFromParser)
+nsHTMLVideoElement::nsHTMLVideoElement(already_AddRefed<nsINodeInfo> aNodeInfo)
+  : nsHTMLMediaElement(aNodeInfo)
 {
 }
 
 nsHTMLVideoElement::~nsHTMLVideoElement()
 {
 }
 
 nsIntSize nsHTMLVideoElement::GetVideoSize(nsIntSize aDefaultSize)
--- a/content/html/document/src/nsHTMLContentSink.cpp
+++ b/content/html/document/src/nsHTMLContentSink.cpp
@@ -1539,17 +1539,17 @@ IsScriptEnabled(nsIDocument *aDoc, nsIDo
 
     globalObject = owner->GetScriptGlobalObject();
     NS_ENSURE_TRUE(globalObject, PR_TRUE);
   }
 
   nsIScriptContext *scriptContext = globalObject->GetContext();
   NS_ENSURE_TRUE(scriptContext, PR_TRUE);
 
-  JSContext* cx = (JSContext *) scriptContext->GetNativeContext();
+  JSContext* cx = scriptContext->GetNativeContext();
   NS_ENSURE_TRUE(cx, PR_TRUE);
 
   PRBool enabled = PR_TRUE;
   nsContentUtils::GetSecurityManager()->
     CanExecuteScripts(cx, aDoc->NodePrincipal(), &enabled);
   return enabled;
 }
 
@@ -2447,17 +2447,17 @@ HTMLContentSink::AddDocTypeDecl(const ns
     if (!nameAtom) {
       return NS_ERROR_OUT_OF_MEMORY;
     }
 
     // Indicate that there is no internal subset (not just an empty one)
     nsAutoString voidString;
     voidString.SetIsVoid(PR_TRUE);
     rv = NS_NewDOMDocumentType(getter_AddRefs(docType),
-                               mDocument->NodeInfoManager(), nsnull, nameAtom,
+                               mDocument->NodeInfoManager(), nameAtom,
                                publicId, systemId, voidString);
     NS_ENSURE_SUCCESS(rv, rv);
 
     if (oldDocType) {
       // If we already have a doctype we replace the old one.
       nsCOMPtr<nsIDOMNode> tmpNode;
       rv = doc->ReplaceChild(oldDocType, docType, getter_AddRefs(tmpNode));
     } else {
--- a/content/svg/content/src/SVGAnimatedPreserveAspectRatio.cpp
+++ b/content/svg/content/src/SVGAnimatedPreserveAspectRatio.cpp
@@ -242,19 +242,17 @@ SVGAnimatedPreserveAspectRatio::SetBaseV
     mAnimVal = mBaseVal;
   }
 #ifdef MOZ_SMIL
   else {
     aSVGElement->AnimationNeedsResample();
   }
 #endif
 
-  // We don't need to call DidChange* here - we're only called by
-  // nsSVGElement::ParseAttribute under nsGenericElement::SetAttr,
-  // which takes care of notifying.
+  aSVGElement->DidChangePreserveAspectRatio(aDoSetAttr);
   return NS_OK;
 }
 
 void
 SVGAnimatedPreserveAspectRatio::GetBaseValueString(nsAString & aValueAsString)
 {
   nsAutoString tmpString;
 
--- a/content/svg/content/src/nsSVGSVGElement.cpp
+++ b/content/svg/content/src/nsSVGSVGElement.cpp
@@ -1208,24 +1208,16 @@ nsSVGSVGElement::DidChangeLength(PRUint8
 
 nsSVGElement::LengthAttributesInfo
 nsSVGSVGElement::GetLengthInfo()
 {
   return LengthAttributesInfo(mLengthAttributes, sLengthInfo,
                               NS_ARRAY_LENGTH(sLengthInfo));
 }
 
-void
-nsSVGSVGElement::DidChangeEnum(PRUint8 aAttrEnum, PRBool aDoSetAttr)
-{
-  nsSVGSVGElementBase::DidChangeEnum(aAttrEnum, aDoSetAttr);
-
-  InvalidateTransformNotifyFrame();
-}
-
 nsSVGElement::EnumAttributesInfo
 nsSVGSVGElement::GetEnumInfo()
 {
   return EnumAttributesInfo(mEnumAttributes, sEnumInfo,
                             NS_ARRAY_LENGTH(sEnumInfo));
 }
 
 void
--- a/content/svg/content/src/nsSVGSVGElement.h
+++ b/content/svg/content/src/nsSVGSVGElement.h
@@ -189,17 +189,16 @@ public:
   NS_IMETHOD_(PRBool) IsAttributeMapped(const nsIAtom* aAttribute) const;
 #ifdef MOZ_SMIL
   virtual nsresult PreHandleEvent(nsEventChainPreVisitor& aVisitor);
 #endif // MOZ_SMIL
 
   // nsSVGElement specializations:
   virtual gfxMatrix PrependLocalTransformTo(const gfxMatrix &aMatrix) const;
   virtual void DidChangeLength(PRUint8 aAttrEnum, PRBool aDoSetAttr);
-  virtual void DidChangeEnum(PRUint8 aAttrEnum, PRBool aDoSetAttr);
   virtual void DidChangeViewBox(PRBool aDoSetAttr);
   virtual void DidChangePreserveAspectRatio(PRBool aDoSetAttr);
 
   virtual void DidAnimateViewBox();
   virtual void DidAnimatePreserveAspectRatio();
   
   // nsSVGSVGElement methods:
   float GetLength(PRUint8 mCtxType);
--- a/content/xbl/src/nsBindingManager.cpp
+++ b/content/xbl/src/nsBindingManager.cpp
@@ -1243,17 +1243,17 @@ nsBindingManager::GetBindingImplementati
       nsIScriptGlobalObject *global = doc->GetScriptGlobalObject();
       if (!global)
         return NS_NOINTERFACE;
 
       nsIScriptContext *context = global->GetContext();
       if (!context)
         return NS_NOINTERFACE;
 
-      JSContext* jscontext = (JSContext*)context->GetNativeContext();
+      JSContext* jscontext = context->GetNativeContext();
       if (!jscontext)
         return NS_NOINTERFACE;
 
       nsIXPConnect *xpConnect = nsContentUtils::XPConnect();
 
       nsCOMPtr<nsIXPConnectWrappedNative> wrapper;
       xpConnect->GetWrappedNativeOfNativeObject(jscontext,
                                                 global->GetGlobalJSObject(),
--- a/content/xbl/src/nsXBLBinding.cpp
+++ b/content/xbl/src/nsXBLBinding.cpp
@@ -1057,17 +1057,17 @@ nsXBLBinding::ChangeDocument(nsIDocument
           // scope might be null if we've cycle-collected the global
           // object, since the Unlink phase of cycle collection happens
           // after JS GC finalization.  But in that case, we don't care
           // about fixing the prototype chain, since everything's going
           // away immediately.
 
           nsCOMPtr<nsIScriptContext> context = global->GetContext();
           if (context && scope) {
-            JSContext *cx = (JSContext *)context->GetNativeContext();
+            JSContext *cx = context->GetNativeContext();
  
             nsCxPusher pusher;
             pusher.Push(cx);
 
             nsCOMPtr<nsIXPConnectWrappedNative> wrapper;
             nsIXPConnect *xpc = nsContentUtils::XPConnect();
             nsresult rv =
               xpc->GetWrappedNativeOfNativeObject(cx, scope, mBoundElement,
@@ -1390,17 +1390,17 @@ nsXBLBinding::AllowScripts()
     return PR_FALSE;
   }
 
   nsCOMPtr<nsIScriptContext> context = global->GetContext();
   if (!context) {
     return PR_FALSE;
   }
   
-  JSContext* cx = (JSContext*) context->GetNativeContext();
+  JSContext* cx = context->GetNativeContext();
 
   nsCOMPtr<nsIDocument> ourDocument =
     mPrototypeBinding->XBLDocumentInfo()->GetDocument();
   PRBool canExecute;
   nsresult rv =
     mgr->CanExecuteScripts(cx, ourDocument->NodePrincipal(), &canExecute);
   if (NS_FAILED(rv) || !canExecute) {
     return PR_FALSE;
--- a/content/xbl/src/nsXBLDocumentInfo.cpp
+++ b/content/xbl/src/nsXBLDocumentInfo.cpp
@@ -313,17 +313,17 @@ nsXBLDocGlobalObject::EnsureScriptEnviro
   nsCOMPtr<nsIScriptRuntime> scriptRuntime;
   rv = NS_GetScriptRuntimeByID(aLangID, getter_AddRefs(scriptRuntime));
   NS_ENSURE_SUCCESS(rv, rv);
   nsCOMPtr<nsIScriptContext> newCtx;
   rv = scriptRuntime->CreateContext(getter_AddRefs(newCtx));
   NS_ENSURE_SUCCESS(rv, rv);
   rv = SetScriptContext(aLangID, newCtx);
 
-  JSContext *cx = (JSContext *)mScriptContext->GetNativeContext();
+  JSContext *cx = mScriptContext->GetNativeContext();
   JSAutoRequest ar(cx);
 
   // nsJSEnvironment set the error reporter to NS_ScriptErrorReporter so
   // we must apparently override that with our own (although it isn't clear 
   // why - see bug 339647)
   JS_SetErrorReporter(cx, XBL_ProtoErrorReporter);
 
   nsIPrincipal *principal = GetPrincipal();
@@ -367,18 +367,17 @@ JSObject *
 nsXBLDocGlobalObject::GetGlobalJSObject()
 {
   // The prototype document has its own special secret script object
   // that can be used to compile scripts and event handlers.
 
   if (!mScriptContext)
     return nsnull;
 
-  JSContext* cx = static_cast<JSContext*>
-                             (mScriptContext->GetNativeContext());
+  JSContext* cx = mScriptContext->GetNativeContext();
   if (!cx)
     return nsnull;
 
   JSObject *ret = ::JS_GetGlobalObject(cx);
   NS_ASSERTION(mJSObject == ret, "How did this magic switch happen?");
   return ret;
 }
 
--- a/content/xbl/src/nsXBLProtoImpl.cpp
+++ b/content/xbl/src/nsXBLProtoImpl.cpp
@@ -98,17 +98,17 @@ nsXBLProtoImpl::InstallImplementation(ns
   void * targetClassObject = nsnull;
   nsresult rv = InitTargetObjects(aBinding, context, aBoundElement,
                                   getter_AddRefs(holder), &targetClassObject);
   NS_ENSURE_SUCCESS(rv, rv); // kick out if we were unable to properly intialize our target objects
 
   JSObject * targetScriptObject;
   holder->GetJSObject(&targetScriptObject);
 
-  JSContext *cx = (JSContext *)context->GetNativeContext();
+  JSContext *cx = context->GetNativeContext();
 
   AutoVersionChecker avc(cx);
   
   // Walk our member list and install each one in turn.
   for (nsXBLProtoImplMember* curr = mMembers;
        curr;
        curr = curr->GetNext())
     curr->InstallMember(context, aBoundElement, targetScriptObject,
@@ -142,17 +142,17 @@ nsXBLProtoImpl::InitTargetObjects(nsXBLP
   nsIScriptGlobalObject *sgo;
 
   if (!ownerDoc || !(sgo = ownerDoc->GetScopeObject())) {
     return NS_ERROR_UNEXPECTED;
   }
 
   // Because our prototype implementation has a class, we need to build up a corresponding
   // class for the concrete implementation in the bound document.
-  JSContext* jscontext = (JSContext*)aContext->GetNativeContext();
+  JSContext* jscontext = aContext->GetNativeContext();
   JSObject* global = sgo->GetGlobalJSObject();
   nsCOMPtr<nsIXPConnectJSObjectHolder> wrapper;
   jsval v;
   rv = nsContentUtils::WrapNative(jscontext, global, aBoundElement, &v,
                                   getter_AddRefs(wrapper));
   NS_ENSURE_SUCCESS(rv, rv);
 
   // All of the above code was just obtaining the bound element's script object and its immediate
@@ -180,17 +180,17 @@ nsXBLProtoImpl::CompilePrototypeMembers(
   nsCOMPtr<nsIScriptGlobalObjectOwner> globalOwner(
       do_QueryObject(aBinding->XBLDocumentInfo()));
   nsIScriptGlobalObject* globalObject = globalOwner->GetScriptGlobalObject();
   NS_ENSURE_TRUE(globalObject, NS_ERROR_UNEXPECTED);
 
   nsIScriptContext *context = globalObject->GetContext();
   NS_ENSURE_TRUE(context, NS_ERROR_OUT_OF_MEMORY);
 
-  JSContext *cx = (JSContext *)context->GetNativeContext();
+  JSContext *cx = context->GetNativeContext();
   JSObject *global = globalObject->GetGlobalJSObject();
   
 
   void* classObject;
   nsresult rv = aBinding->InitClass(mClassName, cx, global, global,
                                     &classObject);
   if (NS_FAILED(rv))
     return rv;
--- a/content/xbl/src/nsXBLProtoImplField.cpp
+++ b/content/xbl/src/nsXBLProtoImplField.cpp
@@ -112,17 +112,17 @@ nsXBLProtoImplField::InstallField(nsIScr
 
   // EvaluateStringWithValue and JS_DefineUCProperty can both trigger GC, so
   // protect |result| here.
   nsresult rv;
 
   nsCAutoString uriSpec;
   aBindingDocURI->GetSpec(uriSpec);
   
-  JSContext* cx = (JSContext*) aContext->GetNativeContext();
+  JSContext* cx = aContext->GetNativeContext();
   NS_ASSERTION(!::JS_IsExceptionPending(cx),
                "Shouldn't get here when an exception is pending!");
   
   // compile the literal string
   PRBool undefined;
   nsCOMPtr<nsIScriptContext> context = aContext;
 
   JSAutoRequest ar(cx);
--- a/content/xbl/src/nsXBLProtoImplMethod.cpp
+++ b/content/xbl/src/nsXBLProtoImplMethod.cpp
@@ -123,17 +123,17 @@ nsresult
 nsXBLProtoImplMethod::InstallMember(nsIScriptContext* aContext,
                                     nsIContent* aBoundElement, 
                                     void* aScriptObject,
                                     void* aTargetClassObject,
                                     const nsCString& aClassStr)
 {
   NS_PRECONDITION(IsCompiled(),
                   "Should not be installing an uncompiled method");
-  JSContext* cx = (JSContext*) aContext->GetNativeContext();
+  JSContext* cx = aContext->GetNativeContext();
 
   nsIDocument *ownerDoc = aBoundElement->GetOwnerDoc();
   nsIScriptGlobalObject *sgo;
 
   if (!ownerDoc || !(sgo = ownerDoc->GetScopeObject())) {
     return NS_ERROR_UNEXPECTED;
   }
 
@@ -289,17 +289,17 @@ nsXBLProtoImplAnonymousMethod::Execute(n
     return NS_OK;
   }
 
   nsCOMPtr<nsIScriptContext> context = global->GetContext();
   if (!context) {
     return NS_OK;
   }
   
-  JSContext* cx = (JSContext*) context->GetNativeContext();
+  JSContext* cx = context->GetNativeContext();
 
   JSObject* globalObject = global->GetGlobalJSObject();
 
   nsCOMPtr<nsIXPConnectJSObjectHolder> wrapper;
   jsval v;
   nsresult rv =
     nsContentUtils::WrapNative(cx, globalObject, aBoundElement, &v,
                                getter_AddRefs(wrapper));
--- a/content/xbl/src/nsXBLProtoImplProperty.cpp
+++ b/content/xbl/src/nsXBLProtoImplProperty.cpp
@@ -150,17 +150,17 @@ nsresult
 nsXBLProtoImplProperty::InstallMember(nsIScriptContext* aContext,
                                       nsIContent* aBoundElement, 
                                       void* aScriptObject,
                                       void* aTargetClassObject,
                                       const nsCString& aClassStr)
 {
   NS_PRECONDITION(mIsCompiled,
                   "Should not be installing an uncompiled property");
-  JSContext* cx = (JSContext*) aContext->GetNativeContext();
+  JSContext* cx = aContext->GetNativeContext();
 
   nsIDocument *ownerDoc = aBoundElement->GetOwnerDoc();
   nsIScriptGlobalObject *sgo;
 
   if (!ownerDoc || !(sgo = ownerDoc->GetScopeObject())) {
     return NS_ERROR_UNEXPECTED;
   }
 
--- a/content/xml/document/src/nsXMLContentSink.cpp
+++ b/content/xml/document/src/nsXMLContentSink.cpp
@@ -1240,17 +1240,17 @@ nsXMLContentSink::HandleDoctypeDecl(cons
 
   NS_ASSERTION(mDocument, "Shouldn't get here from a document fragment");
 
   nsCOMPtr<nsIAtom> name = do_GetAtom(aName);
   NS_ENSURE_TRUE(name, NS_ERROR_OUT_OF_MEMORY);
 
   // Create a new doctype node
   nsCOMPtr<nsIDOMDocumentType> docType;
-  rv = NS_NewDOMDocumentType(getter_AddRefs(docType), mNodeInfoManager, nsnull,
+  rv = NS_NewDOMDocumentType(getter_AddRefs(docType), mNodeInfoManager,
                              name, aPublicId, aSystemId, aSubset);
   if (NS_FAILED(rv) || !docType) {
     return rv;
   }
 
   if (aCatalogData && mCSSLoader && mDocument) {
     // bug 124570 - we only expect additional agent sheets for now -- ignore
     // exit codes, error are not fatal here, just that the stylesheet won't apply
--- a/content/xml/document/src/nsXMLDocument.cpp
+++ b/content/xml/document/src/nsXMLDocument.cpp
@@ -98,17 +98,18 @@
 nsresult
 NS_NewDOMDocument(nsIDOMDocument** aInstancePtrResult,
                   const nsAString& aNamespaceURI, 
                   const nsAString& aQualifiedName, 
                   nsIDOMDocumentType* aDoctype,
                   nsIURI* aDocumentURI,
                   nsIURI* aBaseURI,
                   nsIPrincipal* aPrincipal,
-                  PRBool aLoadedAsData)
+                  PRBool aLoadedAsData,
+                  nsIScriptGlobalObject* aEventObject)
 {
   // Note: can't require that aDocumentURI/aBaseURI/aPrincipal be non-null,
   // since at least one caller (XMLHttpRequest) doesn't have decent args to
   // pass in.
   
   nsresult rv;
 
   *aInstancePtrResult = nsnull;
@@ -148,16 +149,18 @@ NS_NewDOMDocument(nsIDOMDocument** aInst
   } else {
     rv = NS_NewXMLDocument(getter_AddRefs(d));
   }
 
   if (NS_FAILED(rv)) {
     return rv;
   }
 
+  d->SetScriptHandlingObject(aEventObject);
+  
   if (isHTML) {
     nsCOMPtr<nsIHTMLDocument> htmlDoc = do_QueryInterface(d);
     NS_ASSERTION(htmlDoc, "HTML Document doesn't implement nsIHTMLDocument?");
     htmlDoc->SetCompatibilityMode(eCompatibility_FullStandards);
     htmlDoc->SetIsXHTML(isXHTML);
   }
   nsDocument* doc = static_cast<nsDocument*>(d.get());
   doc->SetLoadedAsData(aLoadedAsData);
--- a/content/xslt/src/xslt/txMozillaXMLOutput.cpp
+++ b/content/xslt/src/xslt/txMozillaXMLOutput.cpp
@@ -938,17 +938,17 @@ txMozillaXMLOutput::createResultDocument
             if (!doctypeName) {
                 return NS_ERROR_OUT_OF_MEMORY;
             }
 
             // Indicate that there is no internal subset (not just an empty one)
             nsAutoString voidString;
             voidString.SetIsVoid(PR_TRUE);
             rv = NS_NewDOMDocumentType(getter_AddRefs(documentType),
-                                       mNodeInfoManager, nsnull,
+                                       mNodeInfoManager,
                                        doctypeName,
                                        mOutputFormat.mPublicId,
                                        mOutputFormat.mSystemId,
                                        voidString);
             NS_ENSURE_SUCCESS(rv, rv);
 
             nsCOMPtr<nsIContent> docType = do_QueryInterface(documentType);
             rv = mDocument->AppendChildTo(docType, PR_TRUE);
--- a/content/xtf/src/Makefile.in
+++ b/content/xtf/src/Makefile.in
@@ -62,17 +62,14 @@ FORCE_STATIC_LIB = 1
 EXPORTS 	=  \
 		nsIXTFService.h  \
 		$(NULL)
 
 
 include $(topsrcdir)/config/rules.mk
 
 INCLUDES += 	\
-		-I$(srcdir)/../../shared/public \
-		-I$(srcdir)/../../html/base/src \
 		-I$(srcdir)/../../xml/content/src \
-		-I$(srcdir)/../../../dom \
 		-I$(srcdir)/../../base/src \
-		-I$(srcdir)/../../../layout/html/base/src \
+		-I$(topsrcdir)/dom \
 		$(NULL)
 
 DEFINES += -D_IMPL_NS_LAYOUT
--- a/content/xul/content/src/nsXULElement.cpp
+++ b/content/xul/content/src/nsXULElement.cpp
@@ -792,17 +792,17 @@ nsScriptEventHandlerOwnerTearoff::Compil
 
     // Compile the event handler
     PRUint32 argCount;
     const char **argNames;
     nsContentUtils::GetEventArgNames(kNameSpaceID_XUL, aName, &argCount,
                                      &argNames);
 
     nsCxPusher pusher;
-    if (!pusher.Push((JSContext*)context->GetNativeContext())) {
+    if (!pusher.Push(context->GetNativeContext())) {
       return NS_ERROR_FAILURE;
     }
 
     rv = context->CompileEventHandler(aName, argCount, argNames,
                                       aBody, aURL, aLineNo,
                                       SCRIPTVERSION_DEFAULT,  // for now?
                                       aHandler);
     if (NS_FAILED(rv)) return rv;
--- a/content/xul/document/src/nsXULPrototypeDocument.cpp
+++ b/content/xul/document/src/nsXULPrototypeDocument.cpp
@@ -723,17 +723,17 @@ nsXULPDGlobalObject::EnsureScriptEnviron
   NS_ENSURE_SUCCESS(rv, NS_OK);
 
   nsCOMPtr<nsIScriptContext> ctxNew;
   rv = languageRuntime->CreateContext(getter_AddRefs(ctxNew));
   // We have to setup a special global object.  We do this then
   // attach it as the global for this context.  Then, ::SetScriptContext
   // will re-fetch the global and set it up in our language globals array.
   {
-    JSContext *cx = (JSContext *)ctxNew->GetNativeContext();
+    JSContext *cx = ctxNew->GetNativeContext();
     JSAutoRequest ar(cx);
 
     nsIPrincipal *principal = GetPrincipal();
     JSObject *newGlob;
     JSCompartment *compartment;
 
     rv = xpc_CreateGlobalObject(cx, &gSharedGlobalClass, principal, nsnull,
                                 false, &newGlob, &compartment);
--- a/content/xul/templates/src/nsXULTemplateBuilder.cpp
+++ b/content/xul/templates/src/nsXULTemplateBuilder.cpp
@@ -1415,17 +1415,17 @@ nsXULTemplateBuilder::InitHTMLTemplateRo
         return NS_ERROR_UNEXPECTED;
 
     JSObject *scope = global->GetGlobalJSObject();
 
     nsIScriptContext *context = global->GetContext();
     if (! context)
         return NS_ERROR_UNEXPECTED;
 
-    JSContext* jscontext = reinterpret_cast<JSContext*>(context->GetNativeContext());
+    JSContext* jscontext = context->GetNativeContext();
     NS_ASSERTION(context != nsnull, "no jscontext");
     if (! jscontext)
         return NS_ERROR_UNEXPECTED;
 
     JSAutoRequest ar(jscontext);
 
     jsval v;
     nsCOMPtr<nsIXPConnectJSObjectHolder> wrapper;
--- a/dom/base/nsDOMClassInfo.cpp
+++ b/dom/base/nsDOMClassInfo.cpp
@@ -6487,17 +6487,17 @@ nsWindowSH::NewResolve(nsIXPConnectWrapp
   JSBool ok = JS_TRUE;
   jsval exn = JSVAL_VOID;
   if (!ObjectIsNativeWrapper(cx, obj)) {
     JSAutoEnterCompartment ac;
 
     if (!my_context) {
       my_cx = cx;
     } else {
-      my_cx = (JSContext *)my_context->GetNativeContext();
+      my_cx = my_context->GetNativeContext();
 
       if (my_cx != cx) {
         if (!ac.enter(my_cx, obj)) {
           return NS_ERROR_UNEXPECTED;
         }
       }
     }
 
@@ -9335,17 +9335,17 @@ public:
       mContext(scriptContext)
   {
   }
 
   NS_IMETHOD Run()
   {
     JSContext* cx = nsnull;
     if (mContext) {
-      cx = (JSContext*)mContext->GetNativeContext();
+      cx = mContext->GetNativeContext();
     } else {
       nsCOMPtr<nsIThreadJSContextStack> stack =
         do_GetService("@mozilla.org/js/xpc/ContextStack;1");
       NS_ENSURE_TRUE(stack, NS_OK);
 
       stack->GetSafeJSContext(&cx);
       NS_ENSURE_TRUE(cx, NS_OK);
     }
--- a/dom/base/nsDOMException.cpp
+++ b/dom/base/nsDOMException.cpp
@@ -110,16 +110,18 @@ static struct ResultStruct
 
 #undef DOM_MSG_DEF
 
 static void
 NSResultToNameAndMessage(nsresult aNSResult,
                          const char** aName,
                          const char** aMessage)
 {
+  *aName = nsnull;
+  *aMessage = nsnull;
   ResultStruct* result_struct = gDOMErrorMsgMap;
 
   while (result_struct->mName) {
     if (aNSResult == result_struct->mNSResult) {
       *aName = result_struct->mName;
       *aMessage = result_struct->mMessage;
       return;
     }
--- a/dom/base/nsGlobalWindow.cpp
+++ b/dom/base/nsGlobalWindow.cpp
@@ -769,17 +769,19 @@ NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END
 NS_IMPL_CYCLE_COLLECTION_ROOT_NATIVE(nsTimeout, AddRef)
 NS_IMPL_CYCLE_COLLECTION_UNROOT_NATIVE(nsTimeout, Release)
 
 nsPIDOMWindow::nsPIDOMWindow(nsPIDOMWindow *aOuterWindow)
 : mFrameElement(nsnull), mDocShell(nsnull), mModalStateDepth(0),
   mRunningTimeout(nsnull), mMutationBits(0), mIsDocumentLoaded(PR_FALSE),
   mIsHandlingResizeEvent(PR_FALSE), mIsInnerWindow(aOuterWindow != nsnull),
   mMayHavePaintEventListener(PR_FALSE), mMayHaveTouchEventListener(PR_FALSE),
-  mMayHaveAudioAvailableEventListener(PR_FALSE), mIsModalContentWindow(PR_FALSE),
+  mMayHaveAudioAvailableEventListener(PR_FALSE),
+  mMayHaveMouseEnterLeaveEventListener(PR_FALSE),
+  mIsModalContentWindow(PR_FALSE),
   mIsActive(PR_FALSE), mIsBackground(PR_FALSE),
   mInnerWindow(nsnull), mOuterWindow(aOuterWindow),
   // Make sure no actual window ends up with mWindowID == 0
   mWindowID(++gNextWindowID), mHasNotifiedGlobalCreated(PR_FALSE)
  {}
 
 nsPIDOMWindow::~nsPIDOMWindow() {}
 
@@ -1256,19 +1258,17 @@ nsGlobalWindow::ClearScopeWhenAllScripts
 
 void
 nsGlobalWindow::FreeInnerObjects(PRBool aClearScope)
 {
   NS_ASSERTION(IsInnerWindow(), "Don't free inner objects on an outer window");
 
   // Kill all of the workers for this window.
   nsIScriptContext *scx = GetContextInternal();
-  JSContext *cx = scx ?
-                  static_cast<JSContext*>(scx->GetNativeContext()) :
-                  nsnull;
+  JSContext *cx = scx ? scx->GetNativeContext() : nsnull;
   mozilla::dom::workers::CancelWorkersForWindow(cx, this);
 
   // Close all IndexedDB databases for this window.
   indexedDB::IndexedDatabaseManager* idbManager =
     indexedDB::IndexedDatabaseManager::Get();
   if (idbManager) {
     idbManager->AbortCloseDatabasesForWindow(this);
   }
@@ -1859,17 +1859,17 @@ nsGlobalWindow::SetNewDocument(nsIDocume
     return NS_ERROR_UNEXPECTED;
   }
 
   nsCOMPtr<nsIDocument> oldDoc(do_QueryInterface(mDocument));
 
   nsIScriptContext *scx = GetContextInternal();
   NS_ENSURE_TRUE(scx, NS_ERROR_NOT_INITIALIZED);
 
-  JSContext *cx = (JSContext *)scx->GetNativeContext();
+  JSContext *cx = scx->GetNativeContext();
 #ifndef MOZ_DISABLE_DOMCRYPTO
   // clear smartcard events, our document has gone away.
   if (mCrypto) {
     mCrypto->SetEnableSmartCardEvents(PR_FALSE);
   }
 #endif
   if (!mDocument) {
     // First document load.
@@ -2855,17 +2855,17 @@ nsGlobalWindow::SetArguments(nsIArray *a
 }
 
 nsresult
 nsGlobalWindow::DefineArgumentsProperty(nsIArray *aArguments)
 {
   JSContext *cx;
   nsIScriptContext *ctx = GetOuterWindowInternal()->mContext;
   NS_ENSURE_TRUE(aArguments && ctx &&
-                 (cx = (JSContext *)ctx->GetNativeContext()),
+                 (cx = ctx->GetNativeContext()),
                  NS_ERROR_NOT_INITIALIZED);
 
   if (mIsModalContentWindow) {
     // Modal content windows don't have an "arguments" property, they
     // have a "dialogArguments" property which is handled
     // separately. See nsWindowSH::NewResolve().
 
     return NS_OK;
@@ -6005,18 +6005,17 @@ struct StructuredCloneInfo {
 
 static JSObject*
 PostMessageReadStructuredClone(JSContext* cx,
                                JSStructuredCloneReader* reader,
                                uint32 tag,
                                uint32 data,
                                void* closure)
 {
-  StructuredCloneInfo* scInfo = static_cast<StructuredCloneInfo*>(closure);
-  NS_ASSERTION(scInfo, "Must have scInfo!");
+  NS_ASSERTION(closure, "Must have closure!");
 
   if (tag == SCTAG_DOM_BLOB || tag == SCTAG_DOM_FILELIST) {
     NS_ASSERTION(!data, "Data should be empty");
 
     nsISupports* supports;
     if (JS_ReadBytes(reader, &supports, sizeof(supports))) {
       JSObject* global = JS_GetGlobalForObject(cx, JS_GetScopeChain(cx));
       if (global) {
@@ -6096,17 +6095,17 @@ PostMessageEvent::Run()
                     "should have been passed an outer window!");
   NS_ABORT_IF_FALSE(!mSource || mSource->IsOuterWindow(),
                     "should have been passed an outer window!");
 
   // Get the JSContext for the target window
   JSContext* cx = nsnull;
   nsIScriptContext* scriptContext = mTargetWindow->GetContext();
   if (scriptContext) {
-    cx = (JSContext*)scriptContext->GetNativeContext();
+    cx = scriptContext->GetNativeContext();
   }
 
   if (!cx) {
     // This can happen if mTargetWindow has been closed.  To avoid leaking,
     // we need to find a JSContext.
     nsIThreadJSContextStack* cxStack = nsContentUtils::ThreadJSContextStack();
     if (cxStack) {
       cxStack->GetSafeJSContext(&cx);
@@ -9800,17 +9799,17 @@ nsGlobalWindow::BuildURIfromBase(const c
 
   if (nsContentUtils::IsCallerChrome() && !chrome_win) {
     // If open() is called from chrome on a non-chrome window, we'll
     // use the context from the window on which open() is being called
     // to prevent giving chrome priveleges to new windows opened in
     // such a way. This also makes us get the appropriate base URI for
     // the below URI resolution code.
 
-    cx = (JSContext *)scx->GetNativeContext();
+    cx = scx->GetNativeContext();
   } else {
     // get the JSContext from the call stack
     nsCOMPtr<nsIThreadJSContextStack> stack(do_GetService(sJSStackContractID));
     if (stack)
       stack->Peek(&cx);
   }
 
   /* resolve the URI, which could be relative to the calling window
@@ -9903,17 +9902,17 @@ nsGlobalWindow::SaveWindowState(nsISuppo
   // Don't do anything else to this inner window! After this point, all
   // calls to SetTimeoutOrInterval will create entries in the timeout
   // list that will only run after this window has come out of the bfcache.
   // Also, while we're frozen, we won't dispatch online/offline events
   // to the page.
   inner->Freeze();
 
   // Remember the outer window's prototype.
-  JSContext *cx = (JSContext *)mContext->GetNativeContext();
+  JSContext *cx = mContext->GetNativeContext();
   JSAutoRequest req(cx);
 
   nsIXPConnect *xpc = nsContentUtils::XPConnect();
 
   nsCOMPtr<nsIClassInfo> ci =
     do_QueryInterface((nsIScriptGlobalObject *)this);
   nsCOMPtr<nsIXPConnectJSObjectHolder> proto;
   nsresult rv = xpc->GetWrappedNativePrototype(cx, mJSObject, ci,
@@ -9996,19 +9995,17 @@ nsGlobalWindow::SuspendTimeouts(PRUint32
   PRBool suspended = (mTimeoutsSuspendDepth != 0);
   mTimeoutsSuspendDepth += aIncrease;
 
   if (!suspended) {
     DisableDeviceMotionUpdates();
 
     // Suspend all of the workers for this window.
     nsIScriptContext *scx = GetContextInternal();
-    JSContext *cx = scx ?
-                    static_cast<JSContext*>(scx->GetNativeContext()) :
-                    nsnull;
+    JSContext *cx = scx ? scx->GetNativeContext() : nsnull;
     mozilla::dom::workers::SuspendWorkersForWindow(cx, this);
 
     TimeStamp now = TimeStamp::Now();
     for (nsTimeout *t = FirstTimeout(); IsTimeout(t); t = t->Next()) {
       // Set mTimeRemaining to be the time remaining for this timer.
       if (t->mWhen > now)
         t->mTimeRemaining = t->mWhen - now;
       else
@@ -10074,19 +10071,17 @@ nsGlobalWindow::ResumeTimeouts(PRBool aT
   PRBool shouldResume = (mTimeoutsSuspendDepth == 0);
   nsresult rv;
 
   if (shouldResume) {
     EnableDeviceMotionUpdates();
 
     // Resume all of the workers for this window.
     nsIScriptContext *scx = GetContextInternal();
-    JSContext *cx = scx ?
-                    static_cast<JSContext*>(scx->GetNativeContext()) :
-                    nsnull;
+    JSContext *cx = scx ? scx->GetNativeContext() : nsnull;
     mozilla::dom::workers::ResumeWorkersForWindow(cx, this);
 
     // Restore all of the timeouts, using the stored time remaining
     // (stored in timeout->mTimeRemaining).
 
     TimeStamp now = TimeStamp::Now();
 
 #ifdef DEBUG
@@ -10524,17 +10519,17 @@ nsGlobalChromeWindow::NotifyDefaultButto
 
 NS_IMETHODIMP
 nsGlobalChromeWindow::GetMessageManager(nsIChromeFrameMessageManager** aManager)
 {
   FORWARD_TO_INNER_CHROME(GetMessageManager, (aManager), NS_ERROR_FAILURE);
   if (!mMessageManager) {
     nsIScriptContext* scx = GetContextInternal();
     NS_ENSURE_STATE(scx);
-    JSContext* cx = (JSContext *)scx->GetNativeContext();
+    JSContext* cx = scx->GetNativeContext();
     NS_ENSURE_STATE(cx);
     nsCOMPtr<nsIChromeFrameMessageManager> globalMM =
       do_GetService("@mozilla.org/globalmessagemanager;1");
     mMessageManager =
       new nsFrameMessageManager(PR_TRUE,
                                 nsnull,
                                 nsnull,
                                 nsnull,
--- a/dom/base/nsIScriptContext.h
+++ b/dom/base/nsIScriptContext.h
@@ -38,16 +38,17 @@
 #ifndef nsIScriptContext_h__
 #define nsIScriptContext_h__
 
 #include "nscore.h"
 #include "nsStringGlue.h"
 #include "nsISupports.h"
 #include "nsCOMPtr.h"
 #include "nsIProgrammingLanguage.h"
+#include "jspubtd.h"
 
 class nsIScriptGlobalObject;
 class nsIScriptSecurityManager;
 class nsIPrincipal;
 class nsIAtom;
 class nsIArray;
 class nsIVariant;
 class nsIObjectInputStream;
@@ -68,29 +69,26 @@ public:
 
   virtual nsIScriptObjectPrincipal* GetObjectPrincipal() = 0;
 };
 
 NS_DEFINE_STATIC_IID_ACCESSOR(nsIScriptContextPrincipal,
                               NS_ISCRIPTCONTEXTPRINCIPAL_IID)
 
 #define NS_ISCRIPTCONTEXT_IID \
-  { 0xad76079b, 0xd408, 0x4159, \
-    {0xb7, 0x3f, 0x41, 0x08, 0x77, 0xff, 0x9b, 0x47 } }
+{ 0x827d1e82, 0x5aab, 0x4e3a, \
+  { 0x88, 0x76, 0x53, 0xf7, 0xed, 0x1e, 0x3f, 0xbe } }
 
 /* This MUST match JSVERSION_DEFAULT.  This version stuff if we don't
    know what language we have is a little silly... */
 #define SCRIPTVERSION_DEFAULT JSVERSION_DEFAULT
 
 /**
  * It is used by the application to initialize a runtime and run scripts.
  * A script runtime would implement this interface.
- * <P><I>It does have a bit too much java script information now, that
- * should be removed in a short time. Ideally this interface will be
- * language neutral</I>
  */
 class nsIScriptContext : public nsIScriptContextPrincipal
 {
 public:
   NS_DECLARE_STATIC_IID_ACCESSOR(NS_ISCRIPTCONTEXT_IID)
 
   /* Get the ID of this language. */
   virtual PRUint32 GetScriptTypeID() = 0;
@@ -287,17 +285,17 @@ public:
    *
    **/
   virtual nsIScriptGlobalObject *GetGlobalObject() = 0;
 
   /**
    * Return the native script context
    *
    **/
-  virtual void *GetNativeContext() = 0;
+  virtual JSContext* GetNativeContext() = 0;
 
   /**
    * Return the native global object for this context.
    *
    **/
   virtual void *GetNativeGlobal() = 0;
 
   /**
--- a/dom/base/nsJSEnvironment.cpp
+++ b/dom/base/nsJSEnvironment.cpp
@@ -2237,17 +2237,17 @@ nsJSContext::ConnectToInner(nsIScriptGlo
   JS_SetGlobalObject(mContext, outerGlobal);
   NS_ASSERTION(JS_GetPrototype(mContext, outerGlobal) ==
                JS_GetPrototype(mContext, newInnerJSObject),
                "outer and inner globals should have the same prototype");
 
   return NS_OK;
 }
 
-void *
+JSContext*
 nsJSContext::GetNativeContext()
 {
   return mContext;
 }
 
 nsresult
 nsJSContext::InitContext()
 {
--- a/dom/base/nsJSEnvironment.h
+++ b/dom/base/nsJSEnvironment.h
@@ -29,18 +29,18 @@
  * 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 nsJSEnvironment_h___
-#define nsJSEnvironment_h___
+#ifndef nsJSEnvironment_h
+#define nsJSEnvironment_h
 
 #include "nsIScriptContext.h"
 #include "nsIScriptRuntime.h"
 #include "nsCOMPtr.h"
 #include "jsapi.h"
 #include "nsIObserver.h"
 #include "nsIXPCScriptNotify.h"
 #include "prtime.h"
@@ -124,17 +124,17 @@ public:
                                    const char* aURL,
                                    PRUint32 aLineNo,
                                    PRUint32 aVersion,
                                    PRBool aShared,
                                    void** aFunctionObject);
 
   virtual void SetDefaultLanguageVersion(PRUint32 aVersion);
   virtual nsIScriptGlobalObject *GetGlobalObject();
-  virtual void *GetNativeContext();
+  virtual JSContext* GetNativeContext();
   virtual void *GetNativeGlobal();
   virtual nsresult CreateNativeGlobalForInner(
                                       nsIScriptGlobalObject *aGlobal,
                                       PRBool aIsChrome,
                                       nsIPrincipal *aPrincipal,
                                       void **aNativeGlobal,
                                       nsISupports **aHolder);
   virtual nsresult ConnectToInner(nsIScriptGlobalObject *aNewInner,
@@ -365,9 +365,9 @@ JSObject* NS_DOMReadStructuredClone(JSCo
                                     uint32 data, void* closure);
 
 JSBool NS_DOMWriteStructuredClone(JSContext* cx,
                                   JSStructuredCloneWriter* writer,
                                   JSObject* obj, void *closure);
 
 void NS_DOMStructuredCloneError(JSContext* cx, uint32 errorid);
 
-#endif /* nsJSEnvironment_h___ */
+#endif /* nsJSEnvironment_h */
--- a/dom/base/nsPIDOMWindow.h
+++ b/dom/base/nsPIDOMWindow.h
@@ -75,18 +75,18 @@ class nsIDocument;
 class nsIScriptTimeoutHandler;
 struct nsTimeout;
 class nsScriptObjectHolder;
 class nsXBLPrototypeHandler;
 class nsIArray;
 class nsPIWindowRoot;
 
 #define NS_PIDOMWINDOW_IID \
-{ 0xeee816d2, 0x2f08, 0x4b34, \
-  { 0x97, 0x47, 0x5e, 0x5a, 0xcd, 0xc3, 0x56, 0xfa } }
+{ 0x8ce567b5, 0xcc8d, 0x410b, \
+  { 0xa2, 0x7b, 0x07, 0xaf, 0x31, 0xc0, 0x33, 0xb8 } }
 
 class nsPIDOMWindow : public nsIDOMWindowInternal
 {
 public:
   NS_DECLARE_STATIC_IID_ACCESSOR(NS_PIDOMWINDOW_IID)
 
   virtual nsPIDOMWindow* GetPrivateRoot() = 0;
 
@@ -463,16 +463,34 @@ public:
    * or content in that document) has a MozAudioAvailable event listener.
    */
   void SetHasAudioAvailableEventListeners()
   {
     mMayHaveAudioAvailableEventListener = PR_TRUE;
   }
 
   /**
+   * Call this to check whether some node (this window, its document,
+   * or content in that document) has a mouseenter/leave event listener.
+   */
+  PRBool HasMouseEnterLeaveEventListeners()
+  {
+    return mMayHaveMouseEnterLeaveEventListener;
+  }
+
+  /**
+   * Call this to indicate that some node (this window, its document,
+   * or content in that document) has a mouseenter/leave event listener.
+   */
+  void SetHasMouseEnterLeaveEventListeners()
+  {
+    mMayHaveMouseEnterLeaveEventListener = PR_TRUE;
+  }  
+
+  /**
    * Initialize window.java and window.Packages.
    */
   virtual void InitJavaProperties() = 0;
 
   virtual void* GetCachedXBLPrototypeHandler(nsXBLPrototypeHandler* aKey) = 0;
   virtual void CacheXBLPrototypeHandler(nsXBLPrototypeHandler* aKey,
                                         nsScriptObjectHolder& aHandler) = 0;
 
@@ -622,16 +640,17 @@ protected:
   PRUint32               mMutationBits;
 
   PRPackedBool           mIsDocumentLoaded;
   PRPackedBool           mIsHandlingResizeEvent;
   PRPackedBool           mIsInnerWindow;
   PRPackedBool           mMayHavePaintEventListener;
   PRPackedBool           mMayHaveTouchEventListener;
   PRPackedBool           mMayHaveAudioAvailableEventListener;
+  PRPackedBool           mMayHaveMouseEnterLeaveEventListener;
 
   // This variable is used on both inner and outer windows (and they
   // should match).
   PRPackedBool           mIsModalContentWindow;
 
   // Tracks activation state that's used for :-moz-window-inactive.
   // Only used on outer windows.
   PRPackedBool           mIsActive;
--- a/dom/indexedDB/IDBRequest.cpp
+++ b/dom/indexedDB/IDBRequest.cpp
@@ -138,17 +138,17 @@ IDBRequest::SetDone(AsyncConnectionHelpe
 
   // If the request failed then set the error code and return.
   if (NS_FAILED(rv)) {
     mErrorCode = NS_ERROR_GET_CODE(rv);
     return NS_OK;
   }
 
   // Otherwise we need to get the result from the helper.
-  JSContext* cx = static_cast<JSContext*>(mScriptContext->GetNativeContext());
+  JSContext* cx = mScriptContext->GetNativeContext();
   NS_ASSERTION(cx, "Failed to get a context!");
 
   JSObject* global = static_cast<JSObject*>(mScriptContext->GetNativeGlobal());
   NS_ASSERTION(global, "Failed to get global object!");
 
   JSAutoRequest ar(cx);
   JSAutoEnterCompartment ac;
   if (!ac.enter(cx, global)) {
--- a/dom/interfaces/core/nsIInlineEventHandlers.idl
+++ b/dom/interfaces/core/nsIInlineEventHandlers.idl
@@ -34,17 +34,17 @@
  *
  * ***** END LICENSE BLOCK ***** */
 #include "domstubs.idl"
 
 %{ C++
 #include "jspubtd.h"
 %}
 
-[scriptable, uuid(c3cc4504-1eaf-42e9-8b1b-a3020f6d3a28)]
+[scriptable, uuid(790ad9f7-167a-4f5f-a5c1-8cfb3697104d)]
 interface nsIInlineEventHandlers : nsISupports
 {
   [implicit_jscontext] attribute jsval onabort;
   [implicit_jscontext] attribute jsval onblur;
   [implicit_jscontext] attribute jsval oncanplay;
   [implicit_jscontext] attribute jsval oncanplaythrough;
   [implicit_jscontext] attribute jsval onchange;
   [implicit_jscontext] attribute jsval onclick;
@@ -72,16 +72,18 @@ interface nsIInlineEventHandlers : nsISu
   [implicit_jscontext] attribute jsval onload;
   [implicit_jscontext] attribute jsval onloadeddata;
   [implicit_jscontext] attribute jsval onloadedmetadata;
   [implicit_jscontext] attribute jsval onloadstart;
   [implicit_jscontext] attribute jsval onmousedown;
   [implicit_jscontext] attribute jsval onmousemove;
   [implicit_jscontext] attribute jsval onmouseout;
   [implicit_jscontext] attribute jsval onmouseover;
+  [implicit_jscontext] attribute jsval onmouseenter;
+  [implicit_jscontext] attribute jsval onmouseleave;
   [implicit_jscontext] attribute jsval onmouseup;
   // Not supported yet
   // [implicit_jscontext] attribute jsval onmousewheel;
   [implicit_jscontext] attribute jsval onmozfullscreenchange;
   [implicit_jscontext] attribute jsval onpause;
   [implicit_jscontext] attribute jsval onplay;
   [implicit_jscontext] attribute jsval onplaying;
   [implicit_jscontext] attribute jsval onprogress;
--- a/dom/ipc/ContentParent.cpp
+++ b/dom/ipc/ContentParent.cpp
@@ -91,16 +91,17 @@
 #include "nsExceptionHandler.h"
 #endif
 
 #include "mozilla/dom/ExternalHelperAppParent.h"
 #include "mozilla/dom/StorageParent.h"
 #include "mozilla/Services.h"
 #include "mozilla/unused.h"
 #include "nsDeviceMotion.h"
+#include "mozilla/Util.h"
 
 #include "nsIMemoryReporter.h"
 #include "nsMemoryReporterManager.h"
 #include "mozilla/dom/PMemoryReportRequestParent.h"
 
 #ifdef ANDROID
 #include "gfxAndroidPlatform.h"
 #include "AndroidBridge.h"
@@ -219,17 +220,17 @@ ContentParent::Init()
     if (obs) {
         obs->NotifyObservers(static_cast<nsIObserver*>(this), "ipc:content-created", nsnull);
     }
 
 #ifdef ACCESSIBILITY
     // If accessibility is running in chrome process then start it in content
     // process.
     if (nsIPresShell::IsAccessibilityActive()) {
-        SendActivateA11y();
+        unused << SendActivateA11y();
     }
 #endif
 }
 
 void
 ContentParent::OnChannelConnected(int32 pid)
 {
     ProcessHandle handle;
@@ -363,17 +364,17 @@ ContentParent::ActorDestroy(ActorDestroy
             props->SetPropertyAsAString(NS_LITERAL_STRING("dumpID"), dumpID);
 
             if (!dumpID.IsEmpty()) {
                 CrashReporter::AnnotationTable notes;
                 notes.Init();
                 notes.Put(NS_LITERAL_CSTRING("ProcessType"), NS_LITERAL_CSTRING("content"));
 
                 char startTime[32];
-                sprintf(startTime, "%lld", static_cast<PRInt64>(mProcessStartTime));
+                sprintf(startTime, "%lld", static_cast<long long>(mProcessStartTime));
                 notes.Put(NS_LITERAL_CSTRING("StartupTime"),
                           nsDependentCString(startTime));
 
                 // TODO: Additional per-process annotations.
                 CrashReporter::AppendExtraData(dumpID, notes);
             }
 #endif
 
@@ -486,17 +487,17 @@ ContentParent::RecvReadPermissions(Infal
     nsCOMPtr<nsIPermissionManager> permissionManagerIface =
         do_GetService(NS_PERMISSIONMANAGER_CONTRACTID);
     nsPermissionManager* permissionManager =
         static_cast<nsPermissionManager*>(permissionManagerIface.get());
     NS_ABORT_IF_FALSE(permissionManager,
                  "We have no permissionManager in the Chrome process !");
 
     nsCOMPtr<nsISimpleEnumerator> enumerator;
-    nsresult rv = permissionManager->GetEnumerator(getter_AddRefs(enumerator));
+    DebugOnly<nsresult> rv = permissionManager->GetEnumerator(getter_AddRefs(enumerator));
     NS_ABORT_IF_FALSE(NS_SUCCEEDED(rv), "Could not get enumerator!");
     while(1) {
         PRBool hasMore;
         enumerator->HasMoreElements(&hasMore);
         if (!hasMore)
             break;
 
         nsCOMPtr<nsISupports> supp;
@@ -746,30 +747,30 @@ ContentParent::Observe(nsISupports* aSub
     // listening for alert notifications
     else if (!strcmp(aTopic, "alertfinished") ||
              !strcmp(aTopic, "alertclickcallback") ) {
         if (!SendNotifyAlertsObserver(nsDependentCString(aTopic),
                                       nsDependentString(aData)))
             return NS_ERROR_NOT_AVAILABLE;
     }
     else if (!strcmp(aTopic, "child-memory-reporter-request")) {
-        SendPMemoryReportRequestConstructor();
+        unused << SendPMemoryReportRequestConstructor();
     }
     else if (!strcmp(aTopic, "child-gc-request")){
         SendGarbageCollect();
     }
     else if (!strcmp(aTopic, "child-cc-request")){
         SendCycleCollect();
     }
 #ifdef ACCESSIBILITY
     // Make sure accessibility is running in content process when accessibility
     // gets initiated in chrome process.
     else if (aData && (*aData == '1') &&
              !strcmp(aTopic, "a11y-init-or-shutdown")) {
-        SendActivateA11y();
+        unused << SendActivateA11y();
     }
 #endif
 
     return NS_OK;
 }
 
 PBrowserParent*
 ContentParent::AllocPBrowser(const PRUint32& aChromeFlags)
--- a/dom/plugins/base/Makefile.in
+++ b/dom/plugins/base/Makefile.in
@@ -94,16 +94,21 @@ CPPSRCS		= \
 		nsPluginHost.cpp \
 		nsPluginModule.cpp \
 		nsJSNPRuntime.cpp \
 		nsPluginTags.cpp \
 		PluginPRLibrary.cpp \
 		nsPluginInstanceOwner.cpp \
 		$(NULL)
 
+ifeq ($(MOZ_WIDGET_TOOLKIT),android)
+DIRS += android
+LOCAL_INCLUDES += -I$(topsrcdir)/dom/plugins/base/android
+endif
+
 ifeq ($(OS_ARCH),WINNT)
 	CPPSRCS += nsPluginsDirWin.cpp
 	CPPSRCS += nsPluginNativeWindowWin.cpp
 	CPPSRCS += nsPluginDirServiceProvider.cpp
 	LOCAL_INCLUDES += -I$(topsrcdir)/xpcom/base
 else
 ifeq ($(MOZ_WIDGET_TOOLKIT),os2)
 	CPPSRCS += nsPluginsDirOS2.cpp
@@ -122,17 +127,17 @@ ifeq ($(MOZ_WIDGET_TOOLKIT),qt)
 else
 	CPPSRCS += nsPluginNativeWindow.cpp
 endif
 endif
 endif
 endif
 endif
 
-LOCAL_INCLUDES = \
+LOCAL_INCLUDES += \
   -I$(topsrcdir)/xpcom/base/ \
   $(MOZ_CAIRO_CFLAGS) \
   $(NULL)
 
 include $(topsrcdir)/dom/dom-config.mk
 include $(topsrcdir)/config/config.mk
 include $(topsrcdir)/ipc/chromium/chromium-config.mk
 include $(topsrcdir)/config/rules.mk
--- a/dom/plugins/base/PluginPRLibrary.cpp
+++ b/dom/plugins/base/PluginPRLibrary.cpp
@@ -32,34 +32,62 @@
  * 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/PluginPRLibrary.h"
-
 // Some plugins on Windows, notably Quake Live, implement NP_Initialize using
 // cdecl instead of the documented stdcall. In order to work around this,
 // we force the caller to use a frame pointer.
 #if defined(XP_WIN) && defined(_M_IX86)
 #include <malloc.h>
 
 // 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
 
-namespace mozilla {
+#ifdef ANDROID
+#include "AndroidBridge.h"
+#include "android_npapi.h"
+#include <android/log.h>
+#define ALOG(args...) __android_log_print(ANDROID_LOG_INFO, "GeckoJavaEnv", ## args)
+#endif
 
-#if defined(XP_UNIX) && !defined(XP_MACOSX)
+namespace mozilla {
+#ifdef 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)
+      PR_FindFunctionSymbol(mLibrary, "NP_Initialize");
+    if (!pfNP_Initialize)
+      return NS_ERROR_FAILURE;
+    *error = pfNP_Initialize(bFuncs, pFuncs, GetJNIForThread());
+  }
+
+
+  // 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(XP_UNIX) && !defined(XP_MACOSX)
 nsresult
 PluginPRLibrary::NP_Initialize(NPNetscapeFuncs* bFuncs,
 			       NPPluginFuncs* pFuncs, NPError* error)
 {
   if (mNP_Initialize) {
     *error = mNP_Initialize(bFuncs, pFuncs);
   } else {
     NP_InitializeFunc pfNP_Initialize = (NP_InitializeFunc)
--- a/dom/plugins/base/PluginPRLibrary.h
+++ b/dom/plugins/base/PluginPRLibrary.h
@@ -58,19 +58,21 @@ public:
         mNP_GetMIMEDescription(nsnull),
 #if defined(XP_UNIX) && !defined(XP_MACOSX)
         mNP_GetValue(nsnull),
 #endif
 #if defined(XP_WIN) || defined(XP_MACOSX) || defined(XP_OS2)
         mNP_GetEntryPoints(nsnull),
 #endif
         mNPP_New(nsnull),
+        mNPP_GetValue(nsnull),
         mNPP_ClearSiteData(nsnull),
         mNPP_GetSitesWithData(nsnull),
-        mLibrary(aLibrary)
+        mLibrary(aLibrary),
+        mFilePath(aFilePath)
     {
         NS_ASSERTION(mLibrary, "need non-null lib");
         // addref here??
     }
 
     virtual ~PluginPRLibrary()
     {
         // unref here??
@@ -154,28 +156,32 @@ public:
     NS_OVERRIDE
     virtual nsresult EndUpdateBackground(NPP instance,
                                          gfxContext* aCtx, const nsIntRect&);
 #if defined(MOZ_WIDGET_QT) && (MOZ_PLATFORM_MAEMO == 6)
     virtual nsresult HandleGUIEvent(NPP instance,
                                     const nsGUIEvent& anEvent, bool* handled);
 #endif
 
+    virtual void GetLibraryPath(nsACString& aPath) { aPath.Assign(mFilePath); }
+
 private:
     NP_InitializeFunc mNP_Initialize;
     NP_ShutdownFunc mNP_Shutdown;
     NP_GetMIMEDescriptionFunc mNP_GetMIMEDescription;
 #if defined(XP_UNIX) && !defined(XP_MACOSX)
     NP_GetValueFunc mNP_GetValue;
 #endif
 #if defined(XP_WIN) || defined(XP_MACOSX) || defined(XP_OS2)
     NP_GetEntryPointsFunc mNP_GetEntryPoints;
 #endif
     NPP_NewProcPtr mNPP_New;
+    NPP_GetValueProcPtr mNPP_GetValue;
     NPP_ClearSiteDataPtr mNPP_ClearSiteData;
     NPP_GetSitesWithDataPtr mNPP_GetSitesWithData;
     PRLibrary* mLibrary;
+    nsCString mFilePath;
 };
 
 
 } // namespace mozilla
 
 #endif  // ifndef PluginPRLibrary_h
new file mode 100644
--- /dev/null
+++ b/dom/plugins/base/android/ANPAudio.cpp
@@ -0,0 +1,361 @@
+/* -*- Mode: IDL; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* ***** 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 Android NPAPI support code
+ *
+ * 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):
+ *   Doug Turner <dougt@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 "base/basictypes.h"
+#include "AndroidBridge.h"
+
+#include <android/log.h>
+#include <stdlib.h>
+#include <time.h>
+
+#include "assert.h"
+#include "ANPBase.h"
+#include "nsIThread.h"
+#include "nsThreadUtils.h"
+
+#define LOG(args...)  __android_log_print(ANDROID_LOG_INFO, "GeckoPluginsAudio" , ## args)
+#define ASSIGN(obj, name)   (obj)->name = anp_audio_##name
+
+/* android.media.AudioTrack */
+struct AudioTrack {
+  jclass    at_class;
+  jmethodID constructor;
+  jmethodID flush;
+  jmethodID pause;
+  jmethodID play;
+  jmethodID setvol;
+  jmethodID stop;
+  jmethodID write;
+  jmethodID getpos;
+};
+
+enum AudioTrackMode {
+  MODE_STATIC = 0,
+  MODE_STREAM = 1
+};
+
+/* android.media.AudioManager */
+enum AudioManagerStream {
+  STREAM_VOICE_CALL = 0,
+  STREAM_SYSTEM = 1,
+  STREAM_RING = 2,
+  STREAM_MUSIC = 3,
+  STREAM_ALARM = 4,
+  STREAM_NOTIFICATION = 5,
+  STREAM_DTMF = 8
+};
+
+/* android.media.AudioFormat */
+enum AudioFormatChannel {
+  CHANNEL_OUT_MONO = 4,
+  CHANNEL_OUT_STEREO = 12
+};
+
+enum AudioFormatEncoding {
+  ENCODING_PCM_16BIT = 2,
+  ENCODING_PCM_8BIT = 3
+};
+
+static struct AudioTrack at;
+
+static jclass
+init_jni_bindings(JNIEnv *jenv) {
+  jclass jc = jenv->FindClass("android/media/AudioTrack");
+
+  at.constructor = jenv->GetMethodID(jc, "<init>", "(IIIIII)V");
+  at.flush       = jenv->GetMethodID(jc, "flush", "()V");
+  at.pause       = jenv->GetMethodID(jc, "pause", "()V");
+  at.play        = jenv->GetMethodID(jc, "play",  "()V");
+  at.setvol      = jenv->GetMethodID(jc, "setStereoVolume",  "(FF)I");
+  at.stop        = jenv->GetMethodID(jc, "stop",  "()V");
+  at.write       = jenv->GetMethodID(jc, "write", "([BII)I");
+  at.getpos      = jenv->GetMethodID(jc, "getPlaybackHeadPosition", "()I");
+
+  return jc;
+}
+
+struct ANPAudioTrack {
+  jobject output_unit;
+  jclass at_class;
+
+  unsigned int rate;
+  unsigned int channels;
+  unsigned int bufferSize;
+  unsigned int isStopped;
+  unsigned int keepGoing;
+
+  void* user;
+  ANPAudioCallbackProc proc;
+  ANPSampleFormat format;
+};
+
+class AudioRunnable : public nsRunnable
+{
+public:
+  NS_DECL_NSIRUNNABLE
+
+  AudioRunnable(ANPAudioTrack* aAudioTrack) {
+    mTrack = aAudioTrack;
+  }
+
+  ANPAudioTrack* mTrack;
+};
+
+NS_IMETHODIMP
+AudioRunnable::Run()
+{
+  JNIEnv* jenv = GetJNIForThread();
+
+  if (jenv->PushLocalFrame(128)) {
+    return NS_ERROR_FAILURE;
+  }
+
+  jbyteArray bytearray = jenv->NewByteArray(mTrack->bufferSize);
+  if (!bytearray) {
+    LOG("AudioRunnable:: Run.  Could not create bytearray");
+    return NS_ERROR_FAILURE;
+  }
+
+  jbyte *byte = jenv->GetByteArrayElements(bytearray, NULL);
+  if (!byte) {
+    LOG("AudioRunnable:: Run.  Could not create bytearray");
+    return NS_ERROR_FAILURE;
+  }
+
+  ANPAudioBuffer buffer;
+  buffer.channelCount = mTrack->channels;
+  buffer.format = mTrack->format;
+  buffer.bufferData = (void*) byte;
+
+  while (mTrack->keepGoing)
+  {
+    // reset the buffer size
+    buffer.size = mTrack->bufferSize;
+
+    // Get data from the plugin
+    mTrack->proc(kMoreData_ANPAudioEvent, mTrack->user, &buffer);
+
+    if (buffer.size == 0) {
+      LOG("%p - kMoreData_ANPAudioEvent", mTrack);
+      continue;
+    }
+
+    size_t wroteSoFar = 0;
+    jint retval;
+    do {
+      retval = jenv->CallIntMethod(mTrack->output_unit,
+                                   at.write,
+                                   bytearray,
+                                   wroteSoFar,
+                                   buffer.size - wroteSoFar);
+      if (retval < 0) {
+        LOG("%p - Write failed %d", mTrack, retval);
+        break;
+      }
+
+      wroteSoFar += retval;
+
+    } while(wroteSoFar < buffer.size);
+  }
+
+  jenv->DeleteGlobalRef(mTrack->output_unit);
+  jenv->DeleteGlobalRef(mTrack->at_class);
+
+  free(mTrack);
+
+  jenv->ReleaseByteArrayElements(bytearray, byte, 0);
+  jenv->PopLocalFrame(NULL);
+
+  return NS_OK;
+}
+
+ANPAudioTrack*
+anp_audio_newTrack(uint32_t sampleRate,    // sampling rate in Hz
+                   ANPSampleFormat format,
+                   int channelCount,       // MONO=1, STEREO=2
+                   ANPAudioCallbackProc proc,
+                   void* user)
+{
+  ANPAudioTrack *s = (ANPAudioTrack*) malloc(sizeof(ANPAudioTrack));
+  if (s == NULL) {
+    return NULL;
+  }
+
+  JNIEnv *jenv = GetJNIForThread();
+  if (!jenv)
+    return NULL;
+
+  s->at_class = init_jni_bindings(jenv);
+  s->rate = sampleRate;
+  s->channels = channelCount;
+  s->bufferSize = s->rate * s->channels;
+  s->isStopped = true;
+  s->keepGoing = false;
+  s->user = user;
+  s->proc = proc;
+  s->format = format;
+
+  int jformat;
+  switch (format) {
+  case kPCM16Bit_ANPSampleFormat:
+    jformat = ENCODING_PCM_16BIT;
+    break;
+  case kPCM8Bit_ANPSampleFormat:
+    jformat = ENCODING_PCM_8BIT;
+    break;
+  default:
+    LOG("Unknown audio format.  defaulting to 16bit.");
+    jformat = ENCODING_PCM_16BIT;
+    break;
+  }
+
+  int jChannels;
+  switch (channelCount) {
+  case 1:
+    jChannels = CHANNEL_OUT_MONO;
+    break;
+  case 2:
+    jChannels = CHANNEL_OUT_STEREO;
+    break;
+  default:
+    LOG("Unknown channel count.  defaulting to mono.");
+    jChannels = CHANNEL_OUT_MONO;
+    break;
+  }
+
+  jobject obj = jenv->NewObject(s->at_class,
+                                at.constructor,
+                                STREAM_MUSIC,
+                                s->rate,
+                                jChannels,
+                                jformat,
+                                s->bufferSize,
+                                MODE_STREAM);
+
+  jthrowable exception = jenv->ExceptionOccurred();
+  if (exception) {
+    LOG("%s fAILED  ", __PRETTY_FUNCTION__);
+    jenv->ExceptionDescribe();
+    jenv->ExceptionClear();
+    jenv->DeleteGlobalRef(s->at_class);
+    free(s);
+    return NULL;
+  }
+
+  s->output_unit = jenv->NewGlobalRef(obj);
+  return s;
+}
+
+void
+anp_audio_deleteTrack(ANPAudioTrack* s)
+{
+  if (s == NULL) {
+    return;
+  }
+
+  s->keepGoing = false;
+
+  // deallocation happens in the AudioThread.  There is a
+  // potential leak if anp_audio_start is never called, but
+  // we do not see that from flash.
+}
+
+void
+anp_audio_start(ANPAudioTrack* s)
+{
+  if (s == NULL || s->output_unit == NULL) {
+    return;
+  }
+  
+  if (s->keepGoing) {
+    // we are already playing.  Ignore.
+    LOG("anp_audio_start called twice!");
+    return;
+  }
+
+  JNIEnv *jenv = GetJNIForThread();
+  jenv->CallVoidMethod(s->output_unit, at.play);
+
+  s->isStopped = false;
+  s->keepGoing = true;
+
+  // AudioRunnable now owns the ANPAudioTrack
+  nsRefPtr<AudioRunnable> runnable = new AudioRunnable(s);
+
+  nsCOMPtr<nsIThread> thread;
+  NS_NewThread(getter_AddRefs(thread), runnable);
+}
+
+void
+anp_audio_pause(ANPAudioTrack* s)
+{
+  if (s == NULL || s->output_unit == NULL) {
+    return;
+  }
+
+  JNIEnv *jenv = GetJNIForThread();
+  jenv->CallVoidMethod(s->output_unit, at.pause);
+}
+
+void
+anp_audio_stop(ANPAudioTrack* s)
+{
+  if (s == NULL || s->output_unit == NULL) {
+    return;
+  }
+
+  s->isStopped = true;
+  JNIEnv *jenv = GetJNIForThread();
+  jenv->CallVoidMethod(s->output_unit, at.stop);
+}
+
+bool
+anp_audio_isStopped(ANPAudioTrack* s)
+{
+  return s->isStopped;
+}
+
+void InitAudioTrackInterface(ANPAudioTrackInterfaceV0 *i) {
+  _assert(i->inSize == sizeof(*i));
+  ASSIGN(i, newTrack);
+  ASSIGN(i, deleteTrack);
+  ASSIGN(i, start);
+  ASSIGN(i, pause);
+  ASSIGN(i, stop);
+  ASSIGN(i, isStopped);
+}
new file mode 100644
--- /dev/null
+++ b/dom/plugins/base/android/ANPBase.h
@@ -0,0 +1,90 @@
+/* -*- Mode: IDL; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* ***** 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 Android NPAPI support code
+ *
+ * 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):
+ *   Doug Turner <dougt@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 "android_npapi.h"
+#include <stdlib.h>
+#include "nsAutoPtr.h"
+#include "gfxFont.h"
+
+#define NOT_IMPLEMENTED_FATAL() do {                                    \
+    __android_log_print(ANDROID_LOG_ERROR, "GeckoPlugins",              \
+                        "%s not implemented %s, %d",                    \
+                        __PRETTY_FUNCTION__, __FILE__, __LINE__);       \
+    abort();                                                            \
+  } while(0)
+
+#define NOT_IMPLEMENTED()                                               \
+    __android_log_print(ANDROID_LOG_ERROR, "GeckoPlugins",              \
+                        "!!!!!!!!!!!!!!  %s not implemented %s, %d",    \
+                        __PRETTY_FUNCTION__, __FILE__, __LINE__);       \
+
+class gfxFont;
+
+void InitAudioTrackInterface(ANPAudioTrackInterfaceV0 *i);
+void InitBitmapInterface(ANPBitmapInterfaceV0 *i);
+void InitCanvasInterface(ANPCanvasInterfaceV0 *i);
+void InitEventInterface(ANPEventInterfaceV0 *i);
+void InitLogInterface(ANPLogInterfaceV0 *i);
+void InitMatrixInterface(ANPMatrixInterfaceV0 *i);
+void InitPaintInterface(ANPPaintInterfaceV0 *i);
+void InitPathInterface(ANPPathInterfaceV0 *i);
+void InitSurfaceInterface(ANPSurfaceInterfaceV0 *i);
+void InitSystemInterface(ANPSystemInterfaceV0 *i);
+void InitTypeFaceInterface(ANPTypefaceInterfaceV0 *i);
+void InitWindowInterface(ANPWindowInterfaceV0 *i);
+
+struct ANPTypeface {
+  nsRefPtr<gfxFont> mFont;
+};
+
+
+typedef struct {
+  ANPMatrixFlag flags;
+  ANPColor color;
+  ANPPaintStyle style;
+  float strokeWidth;
+  float strokeMiter;
+  ANPPaintCap paintCap;
+  ANPPaintJoin paintJoin;
+  ANPTextEncoding textEncoding;
+  ANPPaintAlign paintAlign;
+  float textSize;
+  float textScaleX;
+  float textSkewX;
+  ANPTypeface typeface;
+} ANPPaintPrivate;
new file mode 100644
--- /dev/null
+++ b/dom/plugins/base/android/ANPBitmap.cpp
@@ -0,0 +1,118 @@
+/* -*- Mode: IDL; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* ***** 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 Android NPAPI support code
+ *
+ * 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):
+ *   Doug Turner <dougt@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 "assert.h"
+#include "ANPBase.h"
+#include <android/log.h>
+
+#define LOG(args...)  __android_log_print(ANDROID_LOG_INFO, "GeckoPlugins" , ## args)
+#define ASSIGN(obj, name)   (obj)->name = anp_bitmap_##name
+
+
+#define SK_A32_BITS     8
+#define SK_R32_BITS     8
+#define SK_G32_BITS     8
+#define SK_B32_BITS     8
+
+#ifdef IS_BIG_ENDIAN
+#define SK_R32_SHIFT    24
+#define SK_G32_SHIFT    16
+#define SK_B32_SHIFT    8
+#define SK_A32_SHIFT    0
+#else
+#define SK_R32_SHIFT    0
+#define SK_G32_SHIFT    8
+#define SK_B32_SHIFT    16
+#define SK_A32_SHIFT    24
+#endif
+
+#define SK_A32_MASK     ((1 << SK_A32_BITS) - 1)
+#define SK_R32_MASK     ((1 << SK_R32_BITS) - 1)
+#define SK_G32_MASK     ((1 << SK_G32_BITS) - 1)
+#define SK_B32_MASK     ((1 << SK_B32_BITS) - 1)
+
+#define SK_R16_BITS     5
+#define SK_G16_BITS     6
+#define SK_B16_BITS     5
+
+#define SK_R16_SHIFT    (SK_B16_BITS + SK_G16_BITS)
+#define SK_G16_SHIFT    (SK_B16_BITS)
+#define SK_B16_SHIFT    0
+
+#define SK_R16_MASK     ((1 << SK_R16_BITS) - 1)
+#define SK_G16_MASK     ((1 << SK_G16_BITS) - 1)
+#define SK_B16_MASK     ((1 << SK_B16_BITS) - 1)
+
+bool
+anp_bitmap_getPixelPacking(ANPBitmapFormat fmt, ANPPixelPacking* packing) {
+  LOG("%s", __PRETTY_FUNCTION__);
+  switch (fmt) {
+    case kRGBA_8888_ANPBitmapFormat:
+      if (packing) {
+        packing->AShift = SK_A32_SHIFT;
+        packing->ABits  = SK_A32_BITS;
+        packing->RShift = SK_R32_SHIFT;
+        packing->RBits  = SK_R32_BITS;
+        packing->GShift = SK_G32_SHIFT;
+        packing->GBits  = SK_G32_BITS;
+        packing->BShift = SK_B32_SHIFT;
+        packing->BBits  = SK_B32_BITS;
+      }
+      return true;
+    case kRGB_565_ANPBitmapFormat:
+      if (packing) {
+        packing->AShift = 0;
+        packing->ABits  = 0;
+        packing->RShift = SK_R16_SHIFT;
+        packing->RBits  = SK_R16_BITS;
+        packing->GShift = SK_G16_SHIFT;
+        packing->GBits  = SK_G16_BITS;
+        packing->BShift = SK_B16_SHIFT;
+        packing->BBits  = SK_B16_BITS;
+      }
+      return true;
+  default:
+    break;
+  }
+  return false;
+}
+
+void InitBitmapInterface(ANPBitmapInterfaceV0 *i) {
+  _assert(i->inSize == sizeof(*i));
+  ASSIGN(i, getPixelPacking);
+}
new file mode 100644
--- /dev/null
+++ b/dom/plugins/base/android/ANPCanvas.cpp
@@ -0,0 +1,373 @@
+/* -*- Mode: IDL; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* ***** 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 Android NPAPI support code
+ *
+ * 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):
+ *   Doug Turner <dougt@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 "assert.h"
+#include "ANPBase.h"
+#include <android/log.h>
+
+#include "cairo.h"
+#include "gfxPlatform.h"
+#include "gfxASurface.h"
+#include "gfxImageSurface.h"
+#include "gfxUtils.h"
+#include "gfxContext.h"
+
+#define LOG(args...)  __android_log_print(ANDROID_LOG_INFO, "GeckoPlugins" , ## args)
+#define ASSIGN(obj, name)   (obj)->name = anp_canvas_##name
+
+
+ANPCanvas*
+anp_canvas_newCanvas(const ANPBitmap* bitmap)
+{
+  PRUint32 stride;
+  gfxASurface::gfxImageFormat  format;
+
+  if (bitmap->format == ANPBitmapFormats::kRGBA_8888_ANPBitmapFormat) {
+    stride = bitmap->width * 4;
+    format = gfxImageSurface::ImageFormatARGB32;
+  }
+  else if (bitmap->format == ANPBitmapFormats::kRGB_565_ANPBitmapFormat) {
+    stride = bitmap->width * 2;
+    format = gfxImageSurface::ImageFormatRGB16_565;
+  }
+  else {
+    LOG("%s -- Unknown format", __PRETTY_FUNCTION__);
+    return nsnull;
+  }
+
+  gfxImageSurface* pluginSurface = new gfxImageSurface(static_cast<unsigned char*>(bitmap->baseAddr),
+                                                       gfxIntSize(bitmap->width,  bitmap->height), 
+                                                       stride,
+                                                       format);
+  if (pluginSurface->CairoStatus()) {
+    LOG("%s -- %d x %d FAILED to create gfxImageSurface", __PRETTY_FUNCTION__, bitmap->width, bitmap->height);
+    return nsnull;
+  }
+
+  gfxContext *pluginContext = new gfxContext(pluginSurface);
+  NS_ADDREF(pluginContext);
+  return (ANPCanvas*) pluginContext;
+}
+
+void
+anp_canvas_deleteCanvas(ANPCanvas* canvas)
+{
+  if (!canvas)
+    return;
+  gfxContext *ctx = (gfxContext*)canvas;
+  NS_RELEASE( ctx );
+}
+
+void
+anp_canvas_save(ANPCanvas* canvas)
+{
+  if (!canvas)
+    return;
+
+  gfxContext* ctx = (gfxContext*)canvas;
+  ctx->Save();
+}
+
+void
+anp_canvas_restore(ANPCanvas* canvas)
+{
+  if (!canvas)
+    return;
+
+  gfxContext* ctx = (gfxContext*)canvas;
+  ctx->Restore();
+}
+
+void
+anp_canvas_translate(ANPCanvas* canvas, float tx, float ty)
+{
+  if (!canvas)
+    return;
+
+  gfxContext* ctx = (gfxContext*)canvas;
+  ctx->Translate(gfxPoint(tx,ty));
+}
+
+void
+anp_canvas_scale(ANPCanvas* canvas, float sx, float sy)
+{
+  if (!canvas)
+    return;
+
+  gfxContext* ctx = (gfxContext*)canvas;
+  ctx->Scale(sx, sy);
+}
+
+void
+anp_canvas_rotate(ANPCanvas* canvas, float degrees)
+{
+  if (!canvas)
+    return;
+
+  gfxContext* ctx = (gfxContext*)canvas;
+  ctx->Rotate(degrees);
+}
+
+void
+anp_canvas_skew(ANPCanvas* canvas, float kx, float ky)
+{
+  if (!canvas)
+    return;
+
+  gfxContext* ctx = (gfxContext*)canvas;
+  LOG("%s is not impl.", __PRETTY_FUNCTION__);
+}
+
+void
+anp_canvas_concat(ANPCanvas* canvas, const ANPMatrix*)
+{
+  if (!canvas)
+    return;
+
+  gfxContext* ctx = (gfxContext*)canvas;
+  LOG("%s is not impl.", __PRETTY_FUNCTION__);
+}
+
+void
+anp_canvas_clipRect(ANPCanvas* canvas, const ANPRectF* r)
+{
+  if (!canvas)
+    return;
+
+  gfxContext* ctx = (gfxContext*)canvas;
+  ctx->Clip(gfxRect(r->left,
+                    r->top,
+                    r->right - r->left,
+                    r->bottom - r->top));
+}
+
+void
+anp_canvas_clipPath(ANPCanvas* canvas, const ANPPath*)
+{
+  if (!canvas)
+    return;
+
+  gfxContext* ctx = (gfxContext*)canvas;
+  LOG("%s is not impl.", __PRETTY_FUNCTION__);
+}
+
+void
+anp_canvas_getTotalMatrix(ANPCanvas* canvas, ANPMatrix*)
+{
+  if (!canvas)
+    return;
+
+  gfxContext* ctx = (gfxContext*)canvas;
+  LOG("%s is not impl.", __PRETTY_FUNCTION__);
+}
+
+bool
+anp_canvas_getLocalClipBounds(ANPCanvas* canvas, ANPRectF* bounds, bool aa)
+{
+  if (!canvas)
+    return false;
+
+  gfxContext* ctx = (gfxContext*)canvas;
+  LOG("%s is not impl.", __PRETTY_FUNCTION__);
+  return false;
+}
+
+bool
+anp_canvas_getDeviceClipBounds(ANPCanvas* canvas, ANPRectI* bounds)
+{
+  if (!canvas)
+    return false;
+
+  gfxContext* ctx = (gfxContext*)canvas;
+  LOG("%s is not impl.", __PRETTY_FUNCTION__);
+  return false;
+}
+
+void
+anp_canvas_drawColor(ANPCanvas* canvas, ANPColor c)
+{
+  if (!canvas)
+    return;
+
+  gfxContext* ctx = (gfxContext*)canvas;
+  ctx->SetDeviceColor(gfxRGBA(c, gfxRGBA::PACKED_ARGB));
+  LOG("returning from %s", __PRETTY_FUNCTION__);
+}
+
+void
+anp_canvas_drawPaint(ANPCanvas* canvas, const ANPPaint* paint)
+{
+  if (!canvas)
+    return;
+
+  gfxContext* ctx = (gfxContext*)canvas;
+  LOG("%s", "                    **************   NOT IMPLEMENTED!!!");
+}
+
+void
+anp_canvas_drawLine(ANPCanvas* canvas, float x0, float y0, float x1, float y1,
+                    const ANPPaint* paint)
+{
+  if (!canvas)
+    return;
+
+  gfxContext* ctx = (gfxContext*)canvas;
+  ctx->NewPath();
+  ctx->SetColor(((ANPPaintPrivate*)paint)->color);
+  ctx->Line(gfxPoint(x0, y0), gfxPoint(x1, y1));
+  ctx->Fill();
+}
+
+void
+anp_canvas_drawRect(ANPCanvas* canvas, const ANPRectF* r, const ANPPaint* paint)
+{
+  if (!canvas)
+    return;
+
+  gfxContext* ctx = (gfxContext*)canvas;
+
+  ctx->NewPath();
+  ctx->SetColor(((ANPPaintPrivate*)paint)->color);
+  ctx->Rectangle(gfxRect(r->left,
+                         r->top,
+                         r->right - r->left,
+                         r->bottom - r->top));
+  ctx->Fill();
+}
+
+void
+anp_canvas_drawOval(ANPCanvas* canvas, const ANPRectF* r, const ANPPaint* paint)
+{
+  if (!canvas)
+    return;
+
+  gfxContext* ctx = (gfxContext*)canvas;
+   
+  ctx->NewPath();
+  ctx->SetColor(((ANPPaintPrivate*)paint)->color);
+
+  float sizeX = (r->right   - r->left);
+  float sizeY = (r->bottom  - r->top);
+
+  ctx->Ellipse(gfxPoint(r->left + ( sizeX / 2), r->top  + ( sizeY  / 2)),
+               gfxSize(sizeX, sizeY));
+  ctx->Fill();
+}
+
+void
+anp_canvas_drawPath(ANPCanvas* canvas, const ANPPath*, const ANPPaint* paint)
+{
+  if (!canvas)
+    return;
+
+  gfxContext* ctx = (gfxContext*)canvas;
+  LOG("%s is not impl.", __PRETTY_FUNCTION__);
+}
+
+void
+anp_canvas_drawText(ANPCanvas* canvas, const void* text, uint32_t byteLength,
+                                float x, float y, const ANPPaint* paint)
+{
+  if (!canvas)
+    return;
+
+  gfxContext* ctx = (gfxContext*)canvas;
+  LOG("%s is not impl.", __PRETTY_FUNCTION__);
+}
+
+void
+anp_canvas_drawPosText(ANPCanvas* canvas, const void* text, uint32_t byteLength,
+                       const float xy[], const ANPPaint* paint)
+{
+  if (!canvas)
+    return;
+
+  gfxContext* ctx = (gfxContext*)canvas;
+  LOG("%s is not impl.", __PRETTY_FUNCTION__);
+}
+
+void
+anp_canvas_drawBitmap(ANPCanvas* canvas, const ANPBitmap*, float x, float y,
+                      const ANPPaint* paint)
+{
+  if (!canvas)
+    return;
+
+  gfxContext* ctx = (gfxContext*)canvas;
+  LOG("%s is not impl.", __PRETTY_FUNCTION__);
+}
+
+void
+anp_canvas_drawBitmapRect(ANPCanvas* canvas, const ANPBitmap*,
+                          const ANPRectI* src, const ANPRectF* dst,
+                          const ANPPaint* paint)
+{
+  if (!canvas)
+    return;
+
+  gfxContext* ctx = (gfxContext*)canvas;
+  LOG("%s is not impl.", __PRETTY_FUNCTION__);
+}
+
+void InitCanvasInterface(ANPCanvasInterfaceV0 *i) {
+  _assert(i->inSize == sizeof(*i));
+  ASSIGN(i, newCanvas);
+  ASSIGN(i, deleteCanvas);
+  ASSIGN(i, save);
+  ASSIGN(i, restore);
+  ASSIGN(i, translate);
+  ASSIGN(i, scale);
+  ASSIGN(i, rotate);
+  ASSIGN(i, skew);
+  ASSIGN(i, concat);
+  ASSIGN(i, clipRect);
+  ASSIGN(i, clipPath);
+  ASSIGN(i, getTotalMatrix);
+  ASSIGN(i, getLocalClipBounds);
+  ASSIGN(i, getDeviceClipBounds);
+  ASSIGN(i, drawColor);
+  ASSIGN(i, drawPaint);
+  ASSIGN(i, drawLine);
+  ASSIGN(i, drawRect);
+  ASSIGN(i, drawOval);
+  ASSIGN(i, drawPath);
+  ASSIGN(i, drawText);
+  ASSIGN(i, drawPosText);
+  ASSIGN(i, drawBitmap);
+  ASSIGN(i, drawBitmapRect);
+}
new file mode 100644
--- /dev/null
+++ b/dom/plugins/base/android/ANPEvent.cpp
@@ -0,0 +1,84 @@
+/* -*- Mode: IDL; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* ***** 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 Android NPAPI support code
+ *
+ * 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):
+ *   Doug Turner <dougt@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 "assert.h"
+#include "ANPBase.h"
+#include <android/log.h>
+#include "nsThreadUtils.h"
+#include "nsNPAPIPluginInstance.h"
+#include "AndroidBridge.h"
+#include "nsNPAPIPlugin.h"
+
+#define LOG(args...)  __android_log_print(ANDROID_LOG_INFO, "GeckoPlugins" , ## args)
+#define ASSIGN(obj, name)   (obj)->name = anp_event_##name
+
+class PluginEventRunnable : public nsRunnable
+{
+public:
+  PluginEventRunnable(NPP inst, ANPEvent* event, NPPluginFuncs* aFuncs)
+    : mInstance(inst), mEvent(*event), mFuncs(aFuncs) {}
+  virtual nsresult Run() {
+    (*mFuncs->event)(mInstance, &mEvent);
+    return NS_OK;
+  }
+private:
+  NPP mInstance;
+  ANPEvent mEvent;
+  NPPluginFuncs* mFuncs;
+};
+
+void
+anp_event_postEvent(NPP inst, const ANPEvent* event)
+{
+  LOG("%s", __PRETTY_FUNCTION__);
+  if (!mozilla::AndroidBridge::Bridge()) {
+    LOG("no bridge in %s!!!!", __PRETTY_FUNCTION__);
+    return;
+  }
+  nsNPAPIPluginInstance* pinst = static_cast<nsNPAPIPluginInstance*>(inst->ndata);
+  NPPluginFuncs* pluginFunctions = pinst->GetPlugin()->PluginFuncs();
+  mozilla::AndroidBridge::Bridge()->PostToJavaThread(
+    new PluginEventRunnable(inst, const_cast<ANPEvent*>(event), pluginFunctions), PR_TRUE);
+  LOG("returning from %s", __PRETTY_FUNCTION__);
+}
+
+
+void InitEventInterface(ANPEventInterfaceV0 *i) {
+  _assert(i->inSize == sizeof(*i));
+  ASSIGN(i, postEvent);
+}
new file mode 100644
--- /dev/null
+++ b/dom/plugins/base/android/ANPKeyCodes.h
@@ -0,0 +1,152 @@
+/*
+ * Copyright 2008, The Android Open Source Project
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *  * Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef ANPKeyCodes_DEFINED
+#define ANPKeyCodes_DEFINED
+
+/*  List the key codes that are set to a plugin in the ANPKeyEvent.
+ 
+    These exactly match the values in android/view/KeyEvent.java and the
+    corresponding .h file android/keycodes.h.
+*/
+enum ANPKeyCodes {
+    kUnknown_ANPKeyCode = 0,
+
+    kSoftLeft_ANPKeyCode = 1,
+    kSoftRight_ANPKeyCode = 2,
+    kHome_ANPKeyCode = 3,
+    kBack_ANPKeyCode = 4,
+    kCall_ANPKeyCode = 5,
+    kEndCall_ANPKeyCode = 6,
+    k0_ANPKeyCode = 7,
+    k1_ANPKeyCode = 8,
+    k2_ANPKeyCode = 9,
+    k3_ANPKeyCode = 10,
+    k4_ANPKeyCode = 11,
+    k5_ANPKeyCode = 12,
+    k6_ANPKeyCode = 13,
+    k7_ANPKeyCode = 14,
+    k8_ANPKeyCode = 15,
+    k9_ANPKeyCode = 16,
+    kStar_ANPKeyCode = 17,
+    kPound_ANPKeyCode = 18,
+    kDpadUp_ANPKeyCode = 19,
+    kDpadDown_ANPKeyCode = 20,
+    kDpadLeft_ANPKeyCode = 21,
+    kDpadRight_ANPKeyCode = 22,
+    kDpadCenter_ANPKeyCode = 23,
+    kVolumeUp_ANPKeyCode = 24,
+    kVolumeDown_ANPKeyCode = 25,
+    kPower_ANPKeyCode = 26,
+    kCamera_ANPKeyCode = 27,
+    kClear_ANPKeyCode = 28,
+    kA_ANPKeyCode = 29,
+    kB_ANPKeyCode = 30,
+    kC_ANPKeyCode = 31,
+    kD_ANPKeyCode = 32,
+    kE_ANPKeyCode = 33,
+    kF_ANPKeyCode = 34,
+    kG_ANPKeyCode = 35,
+    kH_ANPKeyCode = 36,
+    kI_ANPKeyCode = 37,
+    kJ_ANPKeyCode = 38,
+    kK_ANPKeyCode = 39,
+    kL_ANPKeyCode = 40,
+    kM_ANPKeyCode = 41,
+    kN_ANPKeyCode = 42,
+    kO_ANPKeyCode = 43,
+    kP_ANPKeyCode = 44,
+    kQ_ANPKeyCode = 45,
+    kR_ANPKeyCode = 46,
+    kS_ANPKeyCode = 47,
+    kT_ANPKeyCode = 48,
+    kU_ANPKeyCode = 49,
+    kV_ANPKeyCode = 50,
+    kW_ANPKeyCode = 51,
+    kX_ANPKeyCode = 52,
+    kY_ANPKeyCode = 53,
+    kZ_ANPKeyCode = 54,
+    kComma_ANPKeyCode = 55,
+    kPeriod_ANPKeyCode = 56,
+    kAltLeft_ANPKeyCode = 57,
+    kAltRight_ANPKeyCode = 58,
+    kShiftLeft_ANPKeyCode = 59,
+    kShiftRight_ANPKeyCode = 60,
+    kTab_ANPKeyCode = 61,
+    kSpace_ANPKeyCode = 62,
+    kSym_ANPKeyCode = 63,
+    kExplorer_ANPKeyCode = 64,
+    kEnvelope_ANPKeyCode = 65,
+    kNewline_ANPKeyCode = 66,
+    kDel_ANPKeyCode = 67,
+    kGrave_ANPKeyCode = 68,
+    kMinus_ANPKeyCode = 69,
+    kEquals_ANPKeyCode = 70,
+    kLeftBracket_ANPKeyCode = 71,
+    kRightBracket_ANPKeyCode = 72,
+    kBackslash_ANPKeyCode = 73,
+    kSemicolon_ANPKeyCode = 74,
+    kApostrophe_ANPKeyCode = 75,
+    kSlash_ANPKeyCode = 76,
+    kAt_ANPKeyCode = 77,
+    kNum_ANPKeyCode = 78,
+    kHeadSetHook_ANPKeyCode = 79,
+    kFocus_ANPKeyCode = 80,
+    kPlus_ANPKeyCode = 81,
+    kMenu_ANPKeyCode = 82,
+    kNotification_ANPKeyCode = 83,
+    kSearch_ANPKeyCode = 84,
+    kMediaPlayPause_ANPKeyCode = 85,
+    kMediaStop_ANPKeyCode = 86,
+    kMediaNext_ANPKeyCode = 87,
+    kMediaPrevious_ANPKeyCode = 88,
+    kMediaRewind_ANPKeyCode = 89,
+    kMediaFastForward_ANPKeyCode = 90,
+    kMute_ANPKeyCode = 91,
+    kPageUp_ANPKeyCode = 92,
+    kPageDown_ANPKeyCode = 93,
+    kPictsymbols_ANPKeyCode = 94,
+    kSwitchCharset_ANPKeyCode = 95,
+    kButtonA_ANPKeyCode = 96,
+    kButtonB_ANPKeyCode = 97,
+    kButtonC_ANPKeyCode = 98,
+    kButtonX_ANPKeyCode = 99,
+    kButtonY_ANPKeyCode = 100,
+    kButtonZ_ANPKeyCode = 101,
+    kButtonL1_ANPKeyCode = 102,
+    kButtonR1_ANPKeyCode = 103,
+    kButtonL2_ANPKeyCode = 104,
+    kButtonR2_ANPKeyCode = 105,
+    kButtonThumbL_ANPKeyCode = 106,
+    kButtonThumbR_ANPKeyCode = 107,
+    kButtonStart_ANPKeyCode = 108,
+    kButtonSelect_ANPKeyCode = 109,
+    kButtonMode_ANPKeyCode = 110,
+
+    // NOTE: If you add a new keycode here you must also add it to several other files.
+    //       Refer to frameworks/base/core/java/android/view/KeyEvent.java for the full list.
+};
+
+#endif
new file mode 100644
--- /dev/null
+++ b/dom/plugins/base/android/ANPLog.cpp
@@ -0,0 +1,59 @@
+/* -*- Mode: IDL; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* ***** 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 Android NPAPI support code
+ *
+ * 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):
+ *   Doug Turner <dougt@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 "assert.h"
+#include "ANPBase.h"
+#include <android/log.h>
+
+#define LOG(args...)  __android_log_print(ANDROID_LOG_INFO, "GeckoPlugins" , ## args)
+#define ASSIGN(obj, name)   (obj)->name = anp_log_##name
+
+void
+anp_log_log(ANPLogType type, const char format[], ...) {
+
+  va_list argp;
+  va_start(argp,format);
+  __android_log_vprint(type == kError_ANPLogType ? ANDROID_LOG_ERROR : type == kWarning_ANPLogType ?
+                       ANDROID_LOG_WARN : ANDROID_LOG_INFO, "GeckoPluginLog", format, argp);
+  va_end(argp);
+}
+
+void InitLogInterface(ANPLogInterfaceV0 *i) {
+      _assert(i->inSize == sizeof(*i));
+      ASSIGN(i, log);
+}
new file mode 100644
--- /dev/null
+++ b/dom/plugins/base/android/ANPMatrix.cpp
@@ -0,0 +1,197 @@
+/* -*- Mode: IDL; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* ***** 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 Android NPAPI support code
+ *
+ * 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):
+ *   Doug Turner <dougt@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 "assert.h"
+#include "ANPBase.h"
+#include <android/log.h>
+
+#define LOG(args...)  __android_log_print(ANDROID_LOG_INFO, "GeckoPlugins" , ## args)
+#define ASSIGN(obj, name)   (obj)->name = anp_matrix_##name
+
+/** Return a new identity matrix
+ */
+ANPMatrix*
+anp_matrix_newMatrix()
+{
+  NOT_IMPLEMENTED();
+  return 0;
+}
+
+/** Delete a matrix previously allocated by newMatrix()
+ */
+void
+anp_matrix_deleteMatrix(ANPMatrix*)
+{
+  NOT_IMPLEMENTED();
+}
+
+
+ANPMatrixFlag
+anp_matrix_getFlags(const ANPMatrix*)
+{
+  NOT_IMPLEMENTED();
+  return 0;
+}
+
+
+void
+anp_matrix_copy(ANPMatrix* dst, const ANPMatrix* src)
+{
+  NOT_IMPLEMENTED();
+}
+
+
+void
+anp_matrix_get3x3(const ANPMatrix*, float[9])
+{
+  NOT_IMPLEMENTED();
+}
+
+void
+anp_matrix_set3x3(ANPMatrix*, const float[9])
+{
+  NOT_IMPLEMENTED();
+}
+
+
+void
+anp_matrix_setIdentity(ANPMatrix*)
+{
+  NOT_IMPLEMENTED();
+}
+
+void
+anp_matrix_preTranslate(ANPMatrix*, float tx, float ty)
+{
+  NOT_IMPLEMENTED();
+}
+
+void
+anp_matrix_postTranslate(ANPMatrix*, float tx, float ty)
+{
+  NOT_IMPLEMENTED();
+}
+
+void
+anp_matrix_preScale(ANPMatrix*, float sx, float sy)
+{
+  NOT_IMPLEMENTED();
+}
+
+void
+anp_matrix_postScale(ANPMatrix*, float sx, float sy)
+{
+  NOT_IMPLEMENTED();
+}
+
+void
+anp_matrix_preSkew(ANPMatrix*, float kx, float ky)
+{
+  NOT_IMPLEMENTED();
+}
+
+void
+anp_matrix_postSkew(ANPMatrix*, float kx, float ky)
+{
+  NOT_IMPLEMENTED();
+}
+
+void
+anp_matrix_preRotate(ANPMatrix*, float degrees)
+{
+  NOT_IMPLEMENTED();
+}
+
+void
+anp_matrix_postRotate(ANPMatrix*, float degrees)
+{
+  NOT_IMPLEMENTED();
+}
+
+void
+anp_matrix_preConcat(ANPMatrix*, const ANPMatrix*)
+{
+  NOT_IMPLEMENTED();
+}
+
+void
+anp_matrix_postConcat(ANPMatrix*, const ANPMatrix*)
+{
+  NOT_IMPLEMENTED();
+}
+
+
+bool
+anp_matrix_invert(ANPMatrix* dst, const ANPMatrix* src)
+{
+  NOT_IMPLEMENTED();
+  return false;
+}
+
+void
+anp_matrix_mapPoints(ANPMatrix*, float dst[], const float src[],
+                                 int32_t count)
+{
+  NOT_IMPLEMENTED();
+}
+
+
+void InitMatrixInterface(ANPMatrixInterfaceV0 *i) {
+  _assert(i->inSize == sizeof(*i));
+  ASSIGN(i, newMatrix);
+  ASSIGN(i, deleteMatrix);
+  ASSIGN(i, getFlags);
+  ASSIGN(i, copy);
+  ASSIGN(i, get3x3);
+  ASSIGN(i, set3x3);
+  ASSIGN(i, setIdentity);
+  ASSIGN(i, preTranslate);
+  ASSIGN(i, postTranslate);
+  ASSIGN(i, preScale);
+  ASSIGN(i, postScale);
+  ASSIGN(i, preSkew);
+  ASSIGN(i, postSkew);
+  ASSIGN(i, preRotate);
+  ASSIGN(i, postRotate);
+  ASSIGN(i, preConcat);
+  ASSIGN(i, postConcat);
+  ASSIGN(i, invert);
+  ASSIGN(i, mapPoints);
+}
+
+
new file mode 100644
--- /dev/null
+++ b/dom/plugins/base/android/ANPPaint.cpp
@@ -0,0 +1,454 @@
+/* -*- Mode: IDL; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* ***** 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 Android NPAPI support code
+ *
+ * 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):
+ *   Doug Turner <dougt@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 <assert.h>
+#include <android/log.h>
+#include "ANPBase.h"
+
+#define LOG(args...)  
+//__android_log_print(ANDROID_LOG_INFO, "GeckoPlugins" , ## args)
+#define ASSIGN(obj, name)   (obj)->name = anp_paint_##name
+
+ANPPaint*
+anp_paint_newPaint()
+{
+  LOG("%s", __PRETTY_FUNCTION__);
+
+  ANPPaintPrivate* p = (ANPPaintPrivate*) calloc(1, sizeof(ANPPaintPrivate));
+  return (ANPPaint*) p;
+}
+
+void
+anp_paint_deletePaint(ANPPaint* paint)
+{
+  LOG("%s", __PRETTY_FUNCTION__);
+  if (!paint)
+    return;
+
+  ANPPaintPrivate* p = (ANPPaintPrivate*) paint;
+  free((void*)p);
+}
+
+
+ANPPaintFlags
+anp_paint_getFlags(const ANPPaint* paint)
+{
+  LOG("%s", __PRETTY_FUNCTION__);
+  if (!paint)
+    return kAntiAlias_ANPPaintFlag;
+
+  ANPPaintPrivate* p = (ANPPaintPrivate*) paint;
+  return p->flags;
+}
+
+void
+anp_paint_setFlags(ANPPaint* paint, ANPPaintFlags flags)
+{
+  LOG("%s", __PRETTY_FUNCTION__);
+  if (!paint)
+    return;
+
+  ANPPaintPrivate* p = (ANPPaintPrivate*) paint;  
+  p->flags = flags;
+}
+
+
+ANPColor
+anp_paint_getColor(const ANPPaint* paint)
+{
+  LOG("%s", __PRETTY_FUNCTION__);
+  if (!paint)
+    return ANP_MAKE_COLOR(1, 255, 255, 255);
+
+  ANPPaintPrivate* p = (ANPPaintPrivate*) paint;
+  return p->color;
+}
+
+void
+anp_paint_setColor(ANPPaint* paint, ANPColor color)
+{
+  LOG("%s", __PRETTY_FUNCTION__);
+  if (!paint)
+    return;
+
+  ANPPaintPrivate* p = (ANPPaintPrivate*) paint;
+  p->color = color;
+}
+
+
+ANPPaintStyle
+anp_paint_getStyle(const ANPPaint* paint)
+{
+  LOG("%s", __PRETTY_FUNCTION__);
+  if (!paint)
+    return kFill_ANPPaintStyle;
+
+  ANPPaintPrivate* p = (ANPPaintPrivate*) paint;
+  return p->style;
+}
+
+void
+anp_paint_setStyle(ANPPaint* paint, ANPPaintStyle style)
+{
+  LOG("%s", __PRETTY_FUNCTION__);
+  if (!paint)
+    return;
+
+  ANPPaintPrivate* p = (ANPPaintPrivate*) paint;
+  p->style = style;
+}
+
+float
+anp_paint_getStrokeWidth(const ANPPaint* paint)
+{
+  LOG("%s", __PRETTY_FUNCTION__);
+  if (!paint)
+    return 0;
+
+  ANPPaintPrivate* p = (ANPPaintPrivate*) paint;
+  return p->strokeWidth;
+}
+
+float
+anp_paint_getStrokeMiter(const ANPPaint* paint)
+{
+  LOG("%s", __PRETTY_FUNCTION__);
+  if (!paint)
+    return 0;
+
+  ANPPaintPrivate* p = (ANPPaintPrivate*) paint;
+  return p->strokeMiter;
+}
+
+ANPPaintCap
+anp_paint_getStrokeCap(const ANPPaint* paint)
+{
+  LOG("%s", __PRETTY_FUNCTION__);
+  if (!paint)
+    return kButt_ANPPaintCap;
+
+  ANPPaintPrivate* p = (ANPPaintPrivate*) paint;
+  return p->paintCap;
+}
+
+ANPPaintJoin
+anp_paint_getStrokeJoin(const ANPPaint* paint)
+{
+  LOG("%s", __PRETTY_FUNCTION__);
+  if (!paint)
+    return kMiter_ANPPaintJoin;
+
+  ANPPaintPrivate* p = (ANPPaintPrivate*) paint;
+  return p->paintJoin;
+}
+
+void
+anp_paint_setStrokeWidth(ANPPaint* paint, float width)
+{
+  LOG("%s", __PRETTY_FUNCTION__);
+  if (!paint)
+    return;
+
+  ANPPaintPrivate* p = (ANPPaintPrivate*) paint;
+  p->strokeWidth = width;
+}
+
+void
+anp_paint_setStrokeMiter(ANPPaint* paint, float miter)
+{
+  LOG("%s", __PRETTY_FUNCTION__);
+  if (!paint)
+    return;
+
+  ANPPaintPrivate* p = (ANPPaintPrivate*) paint;
+  p->strokeMiter = miter;
+}
+
+void
+anp_paint_setStrokeCap(ANPPaint* paint, ANPPaintCap cap)
+{
+  LOG("%s", __PRETTY_FUNCTION__);
+  if (!paint)
+    return;
+
+  ANPPaintPrivate* p = (ANPPaintPrivate*) paint;
+  p->paintCap = cap;
+}
+
+void
+anp_paint_setStrokeJoin(ANPPaint* paint, ANPPaintJoin join)
+{
+  LOG("%s", __PRETTY_FUNCTION__);
+  if (!paint)
+    return;
+
+  ANPPaintPrivate* p = (ANPPaintPrivate*) paint;
+  p->paintJoin = join;
+}
+
+
+ANPTextEncoding
+anp_paint_getTextEncoding(const ANPPaint* paint)
+{
+  LOG("%s", __PRETTY_FUNCTION__);
+  if (!paint)
+    return kUTF8_ANPTextEncoding;
+
+  ANPPaintPrivate* p = (ANPPaintPrivate*) paint;
+  return p->textEncoding;
+}
+
+ANPPaintAlign
+anp_paint_getTextAlign(const ANPPaint* paint)
+{
+  LOG("%s", __PRETTY_FUNCTION__);
+  if (!paint)
+    return kLeft_ANPPaintAlign;
+
+  ANPPaintPrivate* p = (ANPPaintPrivate*) paint;
+  return p->paintAlign;
+}
+
+float
+anp_paint_getTextSize(const ANPPaint* paint)
+{
+  LOG("%s", __PRETTY_FUNCTION__);
+  if (!paint)
+    return 0;
+
+  ANPPaintPrivate* p = (ANPPaintPrivate*) paint;
+  return p->textSize;
+}
+
+float
+anp_paint_getTextScaleX(const ANPPaint* paint)
+{
+  LOG("%s", __PRETTY_FUNCTION__);
+  if (!paint)
+    return 0;
+
+  ANPPaintPrivate* p = (ANPPaintPrivate*) paint;
+  return p->textScaleX;
+}
+
+float
+anp_paint_getTextSkewX(const ANPPaint* paint)
+{
+  LOG("%s", __PRETTY_FUNCTION__);
+  if (!paint)
+    return 0;
+
+  ANPPaintPrivate* p = (ANPPaintPrivate*) paint;
+  return p->textSkewX;
+}
+
+void
+anp_paint_setTextEncoding(ANPPaint* paint, ANPTextEncoding encoding)
+{
+  LOG("%s", __PRETTY_FUNCTION__);
+  if (!paint)
+    return;
+
+  ANPPaintPrivate* p = (ANPPaintPrivate*) paint;
+  p->textEncoding = encoding;
+}
+
+void
+anp_paint_setTextAlign(ANPPaint* paint, ANPPaintAlign align)
+{
+  LOG("%s", __PRETTY_FUNCTION__);
+  if (!paint)
+    return;
+
+  ANPPaintPrivate* p = (ANPPaintPrivate*) paint;
+  p->paintAlign = align;  
+}
+
+void
+anp_paint_setTextSize(ANPPaint* paint, float size)
+{
+  LOG("%s", __PRETTY_FUNCTION__);
+  if (!paint)
+    return;
+
+  ANPPaintPrivate* p = (ANPPaintPrivate*) paint;
+  p->textSize = size;
+}
+
+void
+anp_paint_setTextScaleX(ANPPaint* paint, float scale)
+{
+  LOG("%s", __PRETTY_FUNCTION__);
+  if (!paint)
+    return;
+
+  ANPPaintPrivate* p = (ANPPaintPrivate*) paint;
+  p->textScaleX = scale;
+}
+
+void
+anp_paint_setTextSkewX(ANPPaint* paint, float skew)
+{
+  LOG("%s", __PRETTY_FUNCTION__);
+  if (!paint)
+    return;
+
+  ANPPaintPrivate* p = (ANPPaintPrivate*) paint;
+  p->textSkewX = skew;
+}
+
+
+/** Return the typeface in paint, or null if there is none. This does not
+    modify the owner count of the returned typeface.
+*/
+ANPTypeface*
+anp_paint_getTypeface(const ANPPaint* paint)
+{
+  LOG("%s", __PRETTY_FUNCTION__);
+  if (!paint)
+    return NULL;
+
+  ANPPaintPrivate* p = (ANPPaintPrivate*) paint;
+  return &p->typeface;
+}
+
+
+/** Set the paint's typeface. If the paint already had a non-null typeface,
+    its owner count is decremented. If the new typeface is non-null, its
+    owner count is incremented.
+*/
+void
+anp_paint_setTypeface(ANPPaint* paint, ANPTypeface* typeface)
+{
+  LOG("%s", __PRETTY_FUNCTION__);
+  if (!paint)
+    return;
+
+  ANPPaintPrivate* p = (ANPPaintPrivate*) paint;
+  LOG("%s is not impl.", __PRETTY_FUNCTION__);
+}
+
+/** Return the width of the text. If bounds is not null, return the bounds
+    of the text in that rectangle.
+*/
+float
+anp_paint_measureText(ANPPaint* paint, const void* text, uint32_t byteLength,
+                      ANPRectF* bounds)
+{
+  LOG("%s", __PRETTY_FUNCTION__);
+  if (!paint)
+    return 0;
+
+  ANPPaintPrivate* p = (ANPPaintPrivate*) paint;
+
+  LOG("%s is not impl.", __PRETTY_FUNCTION__);
+  return 0;
+}
+
+
+/** Return the number of unichars specifed by the text.
+    If widths is not null, returns the array of advance widths for each
+    unichar.
+    If bounds is not null, returns the array of bounds for each unichar.
+*/
+int
+anp_paint_getTextWidths(ANPPaint* paint, const void* text, uint32_t byteLength,
+                        float widths[], ANPRectF bounds[])
+{
+  LOG("%s", __PRETTY_FUNCTION__);
+  if (!paint)
+    return 0;
+
+  ANPPaintPrivate* p = (ANPPaintPrivate*) paint;
+  LOG("%s is not impl.", __PRETTY_FUNCTION__);
+  return 0;
+}
+
+
+/** Return in metrics the spacing values for text, respecting the paint's
+    typeface and pointsize, and return the spacing between lines
+    (descent - ascent + leading). If metrics is NULL, it will be ignored.
+*/
+float
+anp_paint_getFontMetrics(ANPPaint* paint, ANPFontMetrics* metrics)
+{
+  LOG("%s", __PRETTY_FUNCTION__);
+  if (!paint)
+    return 0;
+
+  ANPPaintPrivate* p = (ANPPaintPrivate*) paint;
+  LOG("%s is not impl.", __PRETTY_FUNCTION__);
+  return 0;
+}
+
+
+void InitPaintInterface(ANPPaintInterfaceV0 *i) {
+  _assert(i->inSize == sizeof(*i));
+  ASSIGN(i, newPaint);
+  ASSIGN(i, deletePaint);
+  ASSIGN(i, getFlags);
+  ASSIGN(i, setFlags);
+  ASSIGN(i, getColor);
+  ASSIGN(i, setColor);
+  ASSIGN(i, getStyle);
+  ASSIGN(i, setStyle);
+  ASSIGN(i, getStrokeWidth);
+  ASSIGN(i, getStrokeMiter);
+  ASSIGN(i, getStrokeCap);
+  ASSIGN(i, getStrokeJoin);
+  ASSIGN(i, setStrokeWidth);
+  ASSIGN(i, setStrokeMiter);
+  ASSIGN(i, setStrokeCap);
+  ASSIGN(i, setStrokeJoin);
+  ASSIGN(i, getTextEncoding);
+  ASSIGN(i, getTextAlign);
+  ASSIGN(i, getTextSize);
+  ASSIGN(i, getTextScaleX);
+  ASSIGN(i, getTextSkewX);
+  ASSIGN(i, setTextEncoding);
+  ASSIGN(i, setTextAlign);
+  ASSIGN(i, setTextSize);
+  ASSIGN(i, setTextScaleX);
+  ASSIGN(i, setTextSkewX);
+  ASSIGN(i, getTypeface);
+  ASSIGN(i, setTypeface);
+  ASSIGN(i, measureText);
+  ASSIGN(i, getTextWidths);
+  ASSIGN(i, getFontMetrics);
+}
new file mode 100644
--- /dev/null
+++ b/dom/plugins/base/android/ANPPath.cpp
@@ -0,0 +1,171 @@
+/* -*- Mode: IDL; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* ***** 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 Android NPAPI support code
+ *
+ * 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):
+ *   Doug Turner <dougt@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 "assert.h"
+#include "ANPBase.h"
+#include <android/log.h>
+
+#define LOG(args...)  __android_log_print(ANDROID_LOG_INFO, "GeckoPlugins" , ## args)
+#define ASSIGN(obj, name)   (obj)->name = anp_path_##name
+
+
+// maybe this should store a list of actions (lineTo,
+// moveTo), and when canvas_drawPath() we apply all of these
+// actions to the gfxContext.
+
+ANPPath*
+anp_path_newPath()
+{
+  LOG("%s - NOT IMPL.", __PRETTY_FUNCTION__);
+  return 0;
+}
+
+
+void
+anp_path_deletePath(ANPPath* p)
+{
+  LOG("%s - NOT IMPL.", __PRETTY_FUNCTION__);
+}
+
+
+void
+anp_path_copy(ANPPath* dst, const ANPPath* src)
+{
+  LOG("%s - NOT IMPL.", __PRETTY_FUNCTION__);
+}
+
+
+bool
+anp_path_equal(const ANPPath* path0, const ANPPath* path1)
+{
+  LOG("%s - NOT IMPL.", __PRETTY_FUNCTION__);
+  return false;
+}
+
+
+void
+anp_path_reset(ANPPath* p)
+{
+  LOG("%s - NOT IMPL.", __PRETTY_FUNCTION__);
+}
+
+
+bool
+anp_path_isEmpty(const ANPPath* p)
+{
+  LOG("%s - NOT IMPL.", __PRETTY_FUNCTION__);
+  return false;
+}
+
+
+void
+anp_path_getBounds(const ANPPath* p, ANPRectF* bounds)
+{
+  LOG("%s - NOT IMPL.", __PRETTY_FUNCTION__);
+
+  bounds->left = 0;
+  bounds->top = 0;
+  bounds->right = 1000;
+  bounds->left = 1000;
+}
+
+
+void
+anp_path_moveTo(ANPPath* p, float x, float y)
+{
+  LOG("%s - NOT IMPL.", __PRETTY_FUNCTION__);
+}
+
+void
+anp_path_lineTo(ANPPath* p, float x, float y)
+{
+  LOG("%s - NOT IMPL.", __PRETTY_FUNCTION__);
+}
+
+void
+anp_path_quadTo(ANPPath* p, float x0, float y0, float x1, float y1)
+{
+  LOG("%s - NOT IMPL.", __PRETTY_FUNCTION__);
+}
+
+void
+anp_path_cubicTo(ANPPath* p, float x0, float y0, float x1, float y1,
+                      float x2, float y2)
+{
+  LOG("%s - NOT IMPL.", __PRETTY_FUNCTION__);
+}
+
+void
+anp_path_close(ANPPath* p)
+{
+  LOG("%s - NOT IMPL.", __PRETTY_FUNCTION__);
+}
+
+
+void
+anp_path_offset(ANPPath* src, float dx, float dy, ANPPath* dst)
+{
+  LOG("%s - NOT IMPL.", __PRETTY_FUNCTION__);
+}
+
+
+void
+anp_path_transform(ANPPath* src, const ANPMatrix*, ANPPath* dst)
+{
+  LOG("%s - NOT IMPL.", __PRETTY_FUNCTION__);
+}
+
+
+
+void InitPathInterface(ANPPathInterfaceV0 *i) {
+  _assert(i->inSize == sizeof(*i));
+  ASSIGN(i, newPath);
+  ASSIGN(i, deletePath);
+  ASSIGN(i, copy);
+  ASSIGN(i, equal);
+  ASSIGN(i, reset);
+  ASSIGN(i, isEmpty);
+  ASSIGN(i, getBounds);
+  ASSIGN(i, moveTo);
+  ASSIGN(i, lineTo);
+  ASSIGN(i, quadTo);
+  ASSIGN(i, cubicTo);
+  ASSIGN(i, close);
+  ASSIGN(i, offset);
+  ASSIGN(i, transform);
+}
new file mode 100644
--- /dev/null
+++ b/dom/plugins/base/android/ANPSurface.cpp
@@ -0,0 +1,189 @@
+/* -*- Mode: IDL; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* ***** 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 Android NPAPI support code
+ *
+ * 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):
+ *   Doug Turner <dougt@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 "assert.h"
+#include "ANPBase.h"
+#include <android/log.h>
+#include "AndroidBridge.h"
+#include "gfxImageSurface.h"
+#include "gfxContext.h"
+
+#define LOG(args...)  __android_log_print(ANDROID_LOG_INFO, "GeckoPlugins" , ## args)
+#define ASSIGN(obj, name)   (obj)->name = anp_surface_##name
+
+
+// used to cache JNI method and field IDs for Surface Objects
+static struct ANPSurfaceInterfaceJavaGlue {
+  bool        initialized;
+  jclass geckoAppShellClass;
+  jclass lockInfoCls;
+  jmethodID lockSurfaceANP;
+  jmethodID jUnlockSurfaceANP;
+  jfieldID jDirtyTop;
+  jfieldID jDirtyLeft;
+  jfieldID jDirtyBottom;
+  jfieldID jDirtyRight;
+  jfieldID jFormat;
+  jfieldID jWidth ;
+  jfieldID jHeight;
+  jfieldID jBuffer;
+} gSurfaceJavaGlue;
+
+#define getClassGlobalRef(env, cname)                                    \
+     (jClass = jclass(env->NewGlobalRef(env->FindClass(cname))))
+
+static void init(JNIEnv* env) {
+  if (gSurfaceJavaGlue.initialized)
+    return;
+  
+  gSurfaceJavaGlue.geckoAppShellClass = mozilla::AndroidBridge::GetGeckoAppShellClass();
+  
+  jmethodID getClass = env->GetStaticMethodID(gSurfaceJavaGlue.geckoAppShellClass, 
+                                              "getSurfaceLockInfoClass",
+                                              "()Ljava/lang/Class;");
+
+  gSurfaceJavaGlue.lockInfoCls = (jclass) env->NewGlobalRef(env->CallStaticObjectMethod(gSurfaceJavaGlue.geckoAppShellClass, getClass));
+
+  gSurfaceJavaGlue.jDirtyTop = env->GetFieldID(gSurfaceJavaGlue.lockInfoCls, "dirtyTop", "I");
+  gSurfaceJavaGlue.jDirtyLeft = env->GetFieldID(gSurfaceJavaGlue.lockInfoCls, "dirtyLeft", "I");
+  gSurfaceJavaGlue.jDirtyBottom = env->GetFieldID(gSurfaceJavaGlue.lockInfoCls, "dirtyBottom", "I");
+  gSurfaceJavaGlue.jDirtyRight = env->GetFieldID(gSurfaceJavaGlue.lockInfoCls, "dirtyRight", "I");
+
+  gSurfaceJavaGlue.jFormat = env->GetFieldID(gSurfaceJavaGlue.lockInfoCls, "format", "I");
+  gSurfaceJavaGlue.jWidth = env->GetFieldID(gSurfaceJavaGlue.lockInfoCls, "width", "I");
+  gSurfaceJavaGlue.jHeight = env->GetFieldID(gSurfaceJavaGlue.lockInfoCls, "height", "I");
+
+  gSurfaceJavaGlue.jBuffer = env->GetFieldID(gSurfaceJavaGlue.lockInfoCls, "buffer", "Ljava/nio/Buffer;");
+  gSurfaceJavaGlue.lockSurfaceANP = env->GetStaticMethodID(gSurfaceJavaGlue.geckoAppShellClass, "lockSurfaceANP", "(Landroid/view/SurfaceView;IIII)Lorg/mozilla/gecko/SurfaceLockInfo;");
+  gSurfaceJavaGlue.jUnlockSurfaceANP = env->GetStaticMethodID(gSurfaceJavaGlue.geckoAppShellClass, "unlockSurfaceANP", "(Landroid/view/SurfaceView;)V");
+  gSurfaceJavaGlue.initialized = true;
+}
+
+static bool anp_lock(JNIEnv* env, jobject surfaceView, ANPBitmap* bitmap, ANPRectI* dirtyRect) {
+  LOG("%s", __PRETTY_FUNCTION__);
+  if (!bitmap || !surfaceView) {
+    LOG("%s, null bitmap or surface, exiting", __PRETTY_FUNCTION__);
+    return false;
+  }
+
+  init(env);
+
+  jvalue args[5];
+  args[0].l = surfaceView;
+  if (dirtyRect) {
+    args[1].i = dirtyRect->top;
+    args[2].i = dirtyRect->left;
+    args[3].i = dirtyRect->bottom;
+    args[4].i = dirtyRect->right;
+    LOG("dirty rect: %d, %d, %d, %d", dirtyRect->top, dirtyRect->left, dirtyRect->bottom, dirtyRect->right);
+  } else {
+    args[1].i = args[2].i = args[3].i = args[4].i = 0;
+  }
+  
+  jobject info = env->CallStaticObjectMethod(gSurfaceJavaGlue.geckoAppShellClass,
+                                             gSurfaceJavaGlue.lockSurfaceANP, 
+                                             surfaceView, args[1].i, args[2].i, args[3].i, args[4].i);
+
+  LOG("info: %p", info);
+  if (!info)
+    return false;
+
+  // the surface may have expanded the dirty region so we must to pass that
+  // information back to the plugin.
+  if (dirtyRect) {
+    dirtyRect->left   = env->GetIntField(info, gSurfaceJavaGlue.jDirtyLeft);
+    dirtyRect->right  = env->GetIntField(info, gSurfaceJavaGlue.jDirtyRight);
+    dirtyRect->top    = env->GetIntField(info, gSurfaceJavaGlue.jDirtyTop);
+    dirtyRect->bottom = env->GetIntField(info, gSurfaceJavaGlue.jDirtyBottom);
+    LOG("dirty rect: %d, %d, %d, %d", dirtyRect->top, dirtyRect->left, dirtyRect->bottom, dirtyRect->right);
+  }
+
+  bitmap->width  = env->GetIntField(info, gSurfaceJavaGlue.jWidth);
+  bitmap->height = env->GetIntField(info, gSurfaceJavaGlue.jHeight);
+
+  int format = env->GetIntField(info, gSurfaceJavaGlue.jFormat);
+
+  // format is PixelFormat
+  if (format & 0x00000001) {
+    bitmap->format = kRGBA_8888_ANPBitmapFormat;
+    bitmap->rowBytes = bitmap->width * 4;
+  }
+  else if (format & 0x00000004) {
+    bitmap->format = kRGB_565_ANPBitmapFormat;
+    bitmap->rowBytes = bitmap->width * 2;
+  }
+  else {
+    LOG("format from glue is unknown %d\n", format);
+    return false;
+  }
+
+  jobject buf = env->GetObjectField(info, gSurfaceJavaGlue.jBuffer);
+  bitmap->baseAddr = env->GetDirectBufferAddress(buf);
+  
+  LOG("format: %d, width: %d, height: %d",  bitmap->format,  bitmap->width,  bitmap->height);
+  env->DeleteLocalRef(info);
+  env->DeleteLocalRef(buf);
+  return ( bitmap->width > 0 && bitmap->height > 0 );
+}
+
+static void anp_unlock(JNIEnv* env, jobject surfaceView) {
+  LOG("%s", __PRETTY_FUNCTION__);
+
+  if (!surfaceView) {
+    LOG("null surface, exiting %s", __PRETTY_FUNCTION__);
+    return;
+  }
+
+  init(env);
+  env->CallStaticVoidMethod(gSurfaceJavaGlue.geckoAppShellClass, gSurfaceJavaGlue.jUnlockSurfaceANP, surfaceView);
+  LOG("returning from %s", __PRETTY_FUNCTION__);
+
+}
+
+///////////////////////////////////////////////////////////////////////////////
+
+#define ASSIGN(obj, name)   (obj)->name = anp_##name
+
+void InitSurfaceInterface(ANPSurfaceInterfaceV0 *i) {
+
+  ASSIGN(i, lock);
+  ASSIGN(i, unlock);
+
+  // setup the java glue struct
+  gSurfaceJavaGlue.initialized = false;
+}
new file mode 100644
--- /dev/null
+++ b/dom/plugins/base/android/ANPSystem.cpp
@@ -0,0 +1,86 @@
+/* -*- Mode: IDL; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* ***** 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 Android NPAPI support code
+ *
+ * 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):
+ *   Doug Turner <dougt@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 "base/basictypes.h"
+
+#include "assert.h"
+#include "ANPBase.h"
+#include <android/log.h>
+#include "nsNPAPIPluginInstance.h"
+#include "AndroidBridge.h"
+#include "nsNPAPIPlugin.h"
+#include "PluginPRLibrary.h"
+
+#define LOG(args...)  __android_log_print(ANDROID_LOG_INFO, "GeckoPlugins" , ## args)
+#define ASSIGN(obj, name)   (obj)->name = anp_system_##name
+
+const char*
+anp_system_getApplicationDataDirectory()
+{
+  LOG("getApplicationDataDirectory return /data/data/org.mozilla.%s", MOZ_APP_NAME);
+  return "/data/data/org.mozilla." MOZ_APP_NAME;
+}
+
+jclass anp_system_loadJavaClass(NPP instance, const char* className)
+{
+  LOG("%s", __PRETTY_FUNCTION__);
+
+  JNIEnv* env = GetJNIForThread();
+  jclass cls = env->FindClass("org/mozilla/gecko/GeckoAppShell");
+  jmethodID method = env->GetStaticMethodID(cls,
+                                            "loadPluginClass",
+                                            "(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/Class;");
+
+  // pass libname and classname, gotta create java strings
+  nsNPAPIPluginInstance* pinst = static_cast<nsNPAPIPluginInstance*>(instance->ndata);
+  mozilla::PluginPRLibrary* lib = static_cast<mozilla::PluginPRLibrary*>(pinst->GetPlugin()->GetLibrary());
+
+  nsCString libName;
+  lib->GetLibraryPath(libName);
+
+  jstring jclassName = env->NewStringUTF(className);
+  jstring jlibName = env->NewStringUTF(libName.get());
+  jobject obj = env->CallStaticObjectMethod(cls, method, jclassName, jlibName);
+  return reinterpret_cast<jclass>(obj);
+}
+
+void InitSystemInterface(ANPSystemInterfaceV0 *i) {
+  _assert(i->inSize == sizeof(*i));
+  ASSIGN(i, getApplicationDataDirectory);
+  ASSIGN(i, loadJavaClass);
+}
new file mode 100644
--- /dev/null
+++ b/dom/plugins/base/android/ANPTypeface.cpp
@@ -0,0 +1,151 @@
+/* -*- Mode: IDL; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* ***** 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 Android NPAPI support code
+ *
+ * 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):
+ *   Doug Turner <dougt@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 "assert.h"
+#include "ANPBase.h"
+#include <android/log.h>
+#include "gfxAndroidPlatform.h"
+
+#define LOG(args...)  __android_log_print(ANDROID_LOG_INFO, "GeckoPlugins" , ## args)
+#define ASSIGN(obj, name)   (obj)->name = anp_typeface_##name
+
+ANPTypeface*
+anp_typeface_createFromName(const char name[], ANPTypefaceStyle aStyle)
+{
+  LOG("%s - %s\n", __PRETTY_FUNCTION__, name);
+
+  gfxFontStyle style (aStyle == kItalic_ANPTypefaceStyle ? FONT_STYLE_ITALIC :
+                      FONT_STYLE_NORMAL,
+                      NS_FONT_STRETCH_NORMAL,
+                      aStyle == kBold_ANPTypefaceStyle ? 700 : 400,
+                      16.0,
+                      NS_NewPermanentAtom(NS_LITERAL_STRING("en")),
+                      0.0,
+                      PR_FALSE, PR_FALSE,
+                      NS_LITERAL_STRING(""),
+                      NS_LITERAL_STRING(""));
+  ANPTypeface* tf = new ANPTypeface;
+  gfxAndroidPlatform * p = (gfxAndroidPlatform*)gfxPlatform::GetPlatform();
+  tf->mFont = gfxFT2Font::GetOrMakeFont(NS_ConvertASCIItoUTF16(name), &style);
+  return tf;
+}
+
+ANPTypeface*
+anp_typeface_createFromTypeface(const ANPTypeface* family,
+                                ANPTypefaceStyle)
+{
+  NOT_IMPLEMENTED();
+  return 0;
+}
+
+int32_t
+anp_typeface_getRefCount(const ANPTypeface*)
+{
+  NOT_IMPLEMENTED();
+  return 0;
+}
+
+void
+anp_typeface_ref(ANPTypeface* tf)
+{
+  LOG("%s\n", __PRETTY_FUNCTION__);
+  if (tf->mFont)
+    tf->mFont->AddRef();
+
+}
+
+void
+anp_typeface_unref(ANPTypeface* tf)
+{
+  LOG("%s\n", __PRETTY_FUNCTION__);
+  if (tf->mFont)
+    tf->mFont->Release();
+}
+
+ANPTypefaceStyle
+anp_typeface_getStyle(const ANPTypeface* ft)
+{
+  LOG("%s\n", __PRETTY_FUNCTION__);
+  return kBold_ANPTypefaceStyle;
+}
+
+int32_t
+anp_typeface_getFontPath(const ANPTypeface*, char path[], int32_t length,
+                         int32_t* index)
+{
+  NOT_IMPLEMENTED();
+  return 0;
+}
+
+static const char* gFontDir;
+#define FONT_DIR_SUFFIX     "/fonts/"
+
+const char*
+anp_typeface_getFontDirectoryPath()
+{
+  LOG("%s\n", __PRETTY_FUNCTION__);
+  if (NULL == gFontDir) {
+    const char* root = getenv("ANDROID_ROOT");
+    size_t len = strlen(root);
+    char* storage = (char*)malloc(len + sizeof(FONT_DIR_SUFFIX));
+    if (NULL == storage) {
+      return NULL;
+    }
+    memcpy(storage, root, len);
+    memcpy(storage + len, FONT_DIR_SUFFIX, sizeof(FONT_DIR_SUFFIX));
+    // save this assignment for last, so that if multiple threads call us
+    // (which should never happen), we never return an incomplete global.
+    // At worst, we would allocate storage for the path twice.
+    gFontDir = storage;
+  }
+
+  return 0;
+}
+
+void InitTypeFaceInterface(ANPTypefaceInterfaceV0 *i) {
+  _assert(i->inSize == sizeof(*i));
+  ASSIGN(i, createFromName);
+  ASSIGN(i, createFromTypeface);
+  ASSIGN(i, getRefCount);
+  ASSIGN(i, ref);
+  ASSIGN(i, unref);
+  ASSIGN(i, getStyle);
+  ASSIGN(i, getFontPath);
+  ASSIGN(i, getFontDirectoryPath);
+}
+
new file mode 100644
--- /dev/null
+++ b/dom/plugins/base/android/ANPWindow.cpp
@@ -0,0 +1,91 @@
+/* -*- Mode: IDL; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* ***** 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 Android NPAPI support code
+ *
+ * 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):
+ *   Doug Turner <dougt@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 "assert.h"
+#include "ANPBase.h"
+#include <android/log.h>
+
+#define LOG(args...)  __android_log_print(ANDROID_LOG_INFO, "GeckoPlugins" , ## args)
+#define ASSIGN(obj, name)   (obj)->name = anp_window_##name
+
+void
+anp_window_setVisibleRects(NPP instance, const ANPRectI rects[], int32_t count)
+{
+  NOT_IMPLEMENTED();
+}
+
+void
+anp_window_clearVisibleRects(NPP instance)
+{
+  NOT_IMPLEMENTED();
+}
+
+void
+anp_window_showKeyboard(NPP instance, bool value)
+{
+  NOT_IMPLEMENTED();
+}
+
+void
+anp_window_requestFullScreen(NPP instance)
+{
+  NOT_IMPLEMENTED();
+}
+
+void
+anp_window_exitFullScreen(NPP instance)
+{
+  NOT_IMPLEMENTED();
+}
+
+void
+anp_window_requestCenterFitZoom(NPP instance)
+{
+  NOT_IMPLEMENTED();
+}
+
+void InitWindowInterface(ANPWindowInterfaceV0 *i) {
+  _assert(i->inSize == sizeof(*i));
+  ASSIGN(i, setVisibleRects);
+  ASSIGN(i, clearVisibleRects);
+  ASSIGN(i, showKeyboard);
+  ASSIGN(i, requestFullScreen);
+  ASSIGN(i, exitFullScreen);
+  ASSIGN(i, requestCenterFitZoom);
+}
+
new file mode 100644
--- /dev/null
+++ b/dom/plugins/base/android/Makefile.in
@@ -0,0 +1,81 @@
+#
+# ***** 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):
+#
+# 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		= plugin
+LIBRARY_NAME	= gkpluginandroid_s
+
+LIBXUL_LIBRARY   = 1
+FORCE_STATIC_LIB = 1
+EXPORT_LIBRARY = 1
+
+include $(topsrcdir)/config/config.mk
+include $(topsrcdir)/ipc/chromium/chromium-config.mk
+
+EXPORTS = \
+  android_npapi.h \
+  $(NULL)
+
+CPPSRCS += ANPAudio.cpp    \
+           ANPCanvas.cpp   \
+           ANPEvent.cpp    \
+           ANPMatrix.cpp   \
+           ANPPath.cpp     \
+           ANPSystem.cpp   \
+           ANPWindow.cpp   \
+           ANPBitmap.cpp   \
+           ANPLog.cpp      \
+           ANPPaint.cpp    \
+           ANPSurface.cpp  \
+           ANPTypeface.cpp \
+           $(NULL)
+
+LOCAL_INCLUDES += \
+  -I$(topsrcdir)/dom/plugins/base \
+  $(MOZ_CAIRO_CFLAGS) \
+  $(NULL)
+
+DEFINES += -DMOZ_APP_NAME='"$(MOZ_APP_NAME)"'
+
+include $(topsrcdir)/config/rules.mk
+
new file mode 100644
--- /dev/null
+++ b/dom/plugins/base/android/android_npapi.h
@@ -0,0 +1,979 @@
+/*
+ * Copyright 2009, The Android Open Source Project
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *  * Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/*  Defines the android-specific types and functions as part of npapi
+
+    In particular, defines the window and event types that are passed to
+    NPN_GetValue, NPP_SetWindow and NPP_HandleEvent.
+
+    To minimize what native libraries the plugin links against, some
+    functionality is provided via function-ptrs (e.g. time, sound)
+ */
+
+#ifndef android_npapi_H
+#define android_npapi_H
+
+#include <stdint.h>
+#include "npapi.h"
+#include <jni.h>
+
+///////////////////////////////////////////////////////////////////////////////
+// General types
+
+enum ANPBitmapFormats {
+    kUnknown_ANPBitmapFormat    = 0,
+    kRGBA_8888_ANPBitmapFormat  = 1,
+    kRGB_565_ANPBitmapFormat    = 2
+};
+typedef int32_t ANPBitmapFormat;
+
+struct ANPPixelPacking {
+    uint8_t AShift;
+    uint8_t ABits;
+    uint8_t RShift;
+    uint8_t RBits;
+    uint8_t GShift;
+    uint8_t GBits;
+    uint8_t BShift;
+    uint8_t BBits;
+};
+
+struct ANPBitmap {
+    void*           baseAddr;
+    ANPBitmapFormat format;
+    int32_t         width;
+    int32_t         height;
+    int32_t         rowBytes;
+};
+
+struct ANPRectF {
+    float   left;
+    float   top;
+    float   right;
+    float   bottom;
+};
+
+struct ANPRectI {
+    int32_t left;
+    int32_t top;
+    int32_t right;
+    int32_t bottom;
+};
+
+struct ANPCanvas;
+struct ANPMatrix;
+struct ANPPaint;
+struct ANPPath;
+struct ANPRegion;
+struct ANPTypeface;
+
+enum ANPMatrixFlags {
+    kIdentity_ANPMatrixFlag     = 0,
+    kTranslate_ANPMatrixFlag    = 0x01,
+    kScale_ANPMatrixFlag        = 0x02,
+    kAffine_ANPMatrixFlag       = 0x04,
+    kPerspective_ANPMatrixFlag  = 0x08,
+};
+typedef uint32_t ANPMatrixFlag;
+
+///////////////////////////////////////////////////////////////////////////////
+// NPN_GetValue
+
+/** queries for a specific ANPInterface.
+
+    Maybe called with NULL for the NPP instance
+
+    NPN_GetValue(inst, interface_enum, ANPInterface*)
+ */
+#define kLogInterfaceV0_ANPGetValue         ((NPNVariable)1000)
+#define kAudioTrackInterfaceV0_ANPGetValue  ((NPNVariable)1001)
+#define kCanvasInterfaceV0_ANPGetValue      ((NPNVariable)1002)
+#define kMatrixInterfaceV0_ANPGetValue      ((NPNVariable)1003)
+#define kPaintInterfaceV0_ANPGetValue       ((NPNVariable)1004)
+#define kPathInterfaceV0_ANPGetValue        ((NPNVariable)1005)
+#define kTypefaceInterfaceV0_ANPGetValue    ((NPNVariable)1006)
+#define kWindowInterfaceV0_ANPGetValue      ((NPNVariable)1007)
+#define kBitmapInterfaceV0_ANPGetValue      ((NPNVariable)1008)
+#define kSurfaceInterfaceV0_ANPGetValue     ((NPNVariable)1009)
+#define kSystemInterfaceV0_ANPGetValue      ((NPNVariable)1010)
+#define kEventInterfaceV0_ANPGetValue       ((NPNVariable)1011)
+
+/** queries for the drawing models supported on this device.
+
+    NPN_GetValue(inst, kSupportedDrawingModel_ANPGetValue, uint32_t* bits)
+ */
+#define kSupportedDrawingModel_ANPGetValue  ((NPNVariable)2000)
+
+/** queries for the context (android.content.Context) of the plugin. If no
+    instance is specified the application's context is returned. If the instance
+    is given then the context returned is identical to the context used to
+    create the webview in which that instance resides.
+
+    NOTE: Holding onto a non-application context after your instance has been
+    destroyed will cause a memory leak.  Refer to the android documentation to
+    determine what context is best suited for your particular scenario.
+
+    NPN_GetValue(inst, kJavaContext_ANPGetValue, jobject context)
+ */
+#define kJavaContext_ANPGetValue            ((NPNVariable)2001)
+
+///////////////////////////////////////////////////////////////////////////////
+// NPN_SetValue
+
+/** Request to set the drawing model. SetValue will return false if the drawing
+    model is not supported or has insufficient information for configuration.
+
+    NPN_SetValue(inst, kRequestDrawingModel_ANPSetValue, (void*)foo_ANPDrawingModel)
+ */
+#define kRequestDrawingModel_ANPSetValue    ((NPPVariable)1000)
+
+/** These are used as bitfields in ANPSupportedDrawingModels_EnumValue,
+    and as-is in ANPRequestDrawingModel_EnumValue. The drawing model determines
+    how to interpret the ANPDrawingContext provided in the Draw event and how
+    to interpret the NPWindow->window field.
+ */
+enum ANPDrawingModels {
+    /** Draw into a bitmap from the browser thread in response to a Draw event.
+        NPWindow->window is reserved (ignore)
+     */
+    kBitmap_ANPDrawingModel  = 1 << 0,
+    /** Draw into a surface (e.g. raster, openGL, etc.) using the Java surface
+        interface. When this model is used the browser will invoke the Java
+        class specified in the plugin's apk manifest. From that class the browser
+        will invoke the appropriate method to return an an instance of a android
+        Java View. The instance is then embedded in the html. The plugin can then
+        manipulate the view as it would any normal Java View in android.
+
+        Unlike the bitmap model, a surface model is opaque so no html content
+        behind the plugin will be  visible. Unless the plugin needs to be
+        transparent the surface model should be chosen over the bitmap model as
+        it will have better performance.
+
+        Further, a plugin can manipulate some surfaces in native code using the
+        ANPSurfaceInterface.  This interface can be used to manipulate Java
+        objects that extend Surface.class by allowing them to access the
+        surface's underlying bitmap in native code.  For instance, if a raster
+        surface is used the plugin can lock, draw directly into the bitmap, and
+        unlock the surface in native code without making JNI calls to the Java
+        surface object.
+     */
+    kSurface_ANPDrawingModel = 1 << 1,
+};
+typedef int32_t ANPDrawingModel;
+
+/** Request to receive/disable events. If the pointer is NULL then all flags will
+    be disabled. Otherwise, the event type will be enabled iff its corresponding
+    bit in the EventFlags bit field is set.
+
+    NPN_SetValue(inst, ANPAcceptEvents, (void*)EventFlags)
+ */
+#define kAcceptEvents_ANPSetValue           ((NPPVariable)1001)
+
+/** The EventFlags are a set of bits used to determine which types of events the
+    plugin wishes to receive. For example, if the value is 0x03 then both key
+    and touch events will be provided to the plugin.
+ */
+enum ANPEventFlag {
+    kKey_ANPEventFlag               = 0x01,
+    kTouch_ANPEventFlag             = 0x02,
+};
+typedef uint32_t ANPEventFlags;
+
+///////////////////////////////////////////////////////////////////////////////
+// NPP_GetValue
+
+/** Requests that the plugin return a java surface to be displayed. This will
+    only be used if the plugin has choosen the kSurface_ANPDrawingModel.
+
+    NPP_GetValue(inst, kJavaSurface_ANPGetValue, jobject surface)
+ */
+#define kJavaSurface_ANPGetValue            ((NPPVariable)2000)
+
+
+///////////////////////////////////////////////////////////////////////////////
+// ANDROID INTERFACE DEFINITIONS
+
+/** Interfaces provide additional functionality to the plugin via function ptrs.
+    Once an interface is retrieved, it is valid for the lifetime of the plugin
+    (just like browserfuncs).
+
+    All ANPInterfaces begin with an inSize field, which must be set by the
+    caller (plugin) with the number of bytes allocated for the interface.
+    e.g. SomeInterface si; si.inSize = sizeof(si); browser->getvalue(..., &si);
+ */
+struct ANPInterface {
+    uint32_t    inSize;     // size (in bytes) of this struct
+};
+
+enum ANPLogTypes {
+    kError_ANPLogType   = 0,    // error
+    kWarning_ANPLogType = 1,    // warning
+    kDebug_ANPLogType   = 2     // debug only (informational)
+};
+typedef int32_t ANPLogType;
+
+struct ANPLogInterfaceV0 : ANPInterface {
+    /** dumps printf messages to the log file
+        e.g. interface->log(instance, kWarning_ANPLogType, "value is %d", value);
+     */
+    void (*log)(ANPLogType, const char format[], ...);
+};
+
+struct ANPBitmapInterfaceV0 : ANPInterface {
+    /** Returns true if the specified bitmap format is supported, and if packing
+        is non-null, sets it to the packing info for that format.
+     */
+    bool (*getPixelPacking)(ANPBitmapFormat, ANPPixelPacking* packing);
+};
+
+struct ANPMatrixInterfaceV0 : ANPInterface {
+    /** Return a new identity matrix
+     */
+    ANPMatrix*  (*newMatrix)();
+    /** Delete a matrix previously allocated by newMatrix()
+     */
+    void        (*deleteMatrix)(ANPMatrix*);
+
+    ANPMatrixFlag (*getFlags)(const ANPMatrix*);
+
+    void        (*copy)(ANPMatrix* dst, const ANPMatrix* src);
+
+    /** Return the matrix values in a float array (allcoated by the caller),
+        where the values are treated as follows:
+        w  = x * [6] + y * [7] + [8];
+        x' = (x * [0] + y * [1] + [2]) / w;
+        y' = (x * [3] + y * [4] + [5]) / w;
+     */
+    void        (*get3x3)(const ANPMatrix*, float[9]);
+    /** Initialize the matrix from values in a float array,
+        where the values are treated as follows:
+         w  = x * [6] + y * [7] + [8];
+         x' = (x * [0] + y * [1] + [2]) / w;
+         y' = (x * [3] + y * [4] + [5]) / w;
+     */
+    void        (*set3x3)(ANPMatrix*, const float[9]);
+
+    void        (*setIdentity)(ANPMatrix*);
+    void        (*preTranslate)(ANPMatrix*, float tx, float ty);
+    void        (*postTranslate)(ANPMatrix*, float tx, float ty);
+    void        (*preScale)(ANPMatrix*, float sx, float sy);
+    void        (*postScale)(ANPMatrix*, float sx, float sy);
+    void        (*preSkew)(ANPMatrix*, float kx, float ky);
+    void        (*postSkew)(ANPMatrix*, float kx, float ky);
+    void        (*preRotate)(ANPMatrix*, float degrees);
+    void        (*postRotate)(ANPMatrix*, float degrees);
+    void        (*preConcat)(ANPMatrix*, const ANPMatrix*);
+    void        (*postConcat)(ANPMatrix*, const ANPMatrix*);
+
+    /** Return true if src is invertible, and if so, return its inverse in dst.
+        If src is not invertible, return false and ignore dst.
+     */
+    bool        (*invert)(ANPMatrix* dst, const ANPMatrix* src);
+
+    /** Transform the x,y pairs in src[] by this matrix, and store the results
+        in dst[]. The count parameter is treated as the number of pairs in the
+        array. It is legal for src and dst to point to the same memory, but
+        illegal for the two arrays to partially overlap.
+     */
+    void        (*mapPoints)(ANPMatrix*, float dst[], const float src[],
+                             int32_t count);
+};
+
+struct ANPPathInterfaceV0 : ANPInterface {
+    /** Return a new path */
+    ANPPath* (*newPath)();
+
+    /** Delete a path previously allocated by ANPPath() */
+    void (*deletePath)(ANPPath*);
+
+    /** Make a deep copy of the src path, into the dst path (already allocated
+        by the caller).
+     */
+    void (*copy)(ANPPath* dst, const ANPPath* src);
+
+    /** Returns true if the two paths are the same (i.e. have the same points)
+     */
+    bool (*equal)(const ANPPath* path0, const ANPPath* path1);
+
+    /** Remove any previous points, initializing the path back to empty. */
+    void (*reset)(ANPPath*);
+
+    /** Return true if the path is empty (has no lines, quads or cubics). */
+    bool (*isEmpty)(const ANPPath*);
+
+    /** Return the path's bounds in bounds. */
+    void (*getBounds)(const ANPPath*, ANPRectF* bounds);
+
+    void (*moveTo)(ANPPath*, float x, float y);
+    void (*lineTo)(ANPPath*, float x, float y);
+    void (*quadTo)(ANPPath*, float x0, float y0, float x1, float y1);
+    void (*cubicTo)(ANPPath*, float x0, float y0, float x1, float y1,
+                    float x2, float y2);
+    void (*close)(ANPPath*);
+
+    /** Offset the src path by [dx, dy]. If dst is null, apply the
+        change directly to the src path. If dst is not null, write the
+        changed path into dst, and leave the src path unchanged. In that case
+        dst must have been previously allocated by the caller.
+     */
+    void (*offset)(ANPPath* src, float dx, float dy, ANPPath* dst);
+
+    /** Transform the path by the matrix. If dst is null, apply the
+        change directly to the src path. If dst is not null, write the
+        changed path into dst, and leave the src path unchanged. In that case
+        dst must have been previously allocated by the caller.
+     */
+    void (*transform)(ANPPath* src, const ANPMatrix*, ANPPath* dst);
+};
+
+/** ANPColor is always defined to have the same packing on all platforms, and
+    it is always unpremultiplied.
+
+    This is in contrast to 32bit format(s) in bitmaps, which are premultiplied,
+    and their packing may vary depending on the platform, hence the need for
+    ANPBitmapInterface::getPixelPacking()
+ */
+typedef uint32_t ANPColor;
+#define ANPColor_ASHIFT     24
+#define ANPColor_RSHIFT     16
+#define ANPColor_GSHIFT     8
+#define ANPColor_BSHIFT     0
+#define ANP_MAKE_COLOR(a, r, g, b)  \
+                   (((a) << ANPColor_ASHIFT) |  \
+                    ((r) << ANPColor_RSHIFT) |  \
+                    ((g) << ANPColor_GSHIFT) |  \
+                    ((b) << ANPColor_BSHIFT))
+
+enum ANPPaintFlag {
+    kAntiAlias_ANPPaintFlag         = 1 << 0,
+    kFilterBitmap_ANPPaintFlag      = 1 << 1,
+    kDither_ANPPaintFlag            = 1 << 2,
+    kUnderlineText_ANPPaintFlag     = 1 << 3,
+    kStrikeThruText_ANPPaintFlag    = 1 << 4,
+    kFakeBoldText_ANPPaintFlag      = 1 << 5,
+};
+typedef uint32_t ANPPaintFlags;
+
+enum ANPPaintStyles {
+    kFill_ANPPaintStyle             = 0,
+    kStroke_ANPPaintStyle           = 1,
+    kFillAndStroke_ANPPaintStyle    = 2
+};
+typedef int32_t ANPPaintStyle;
+
+enum ANPPaintCaps {
+    kButt_ANPPaintCap   = 0,
+    kRound_ANPPaintCap  = 1,
+    kSquare_ANPPaintCap = 2
+};
+typedef int32_t ANPPaintCap;
+
+enum ANPPaintJoins {
+    kMiter_ANPPaintJoin = 0,
+    kRound_ANPPaintJoin = 1,
+    kBevel_ANPPaintJoin = 2
+};
+typedef int32_t ANPPaintJoin;
+
+enum ANPPaintAligns {
+    kLeft_ANPPaintAlign     = 0,
+    kCenter_ANPPaintAlign   = 1,
+    kRight_ANPPaintAlign    = 2
+};
+typedef int32_t ANPPaintAlign;
+
+enum ANPTextEncodings {
+    kUTF8_ANPTextEncoding   = 0,
+    kUTF16_ANPTextEncoding  = 1,
+};
+typedef int32_t ANPTextEncoding;
+
+enum ANPTypefaceStyles {
+    kBold_ANPTypefaceStyle      = 1 << 0,
+    kItalic_ANPTypefaceStyle    = 1 << 1
+};
+typedef uint32_t ANPTypefaceStyle;
+
+typedef uint32_t ANPFontTableTag;
+
+struct ANPFontMetrics {
+    /** The greatest distance above the baseline for any glyph (will be <= 0) */
+    float   fTop;
+    /** The recommended distance above the baseline (will be <= 0) */
+    float   fAscent;
+    /** The recommended distance below the baseline (will be >= 0) */
+    float   fDescent;
+    /** The greatest distance below the baseline for any glyph (will be >= 0) */
+    float   fBottom;
+    /** The recommended distance to add between lines of text (will be >= 0) */
+    float   fLeading;
+};
+
+struct ANPTypefaceInterfaceV0 : ANPInterface {
+    /** Return a new reference to the typeface that most closely matches the
+        requested name and style. Pass null as the name to return
+        the default font for the requested style. Will never return null
+
+        The 5 generic font names "serif", "sans-serif", "monospace", "cursive",
+        "fantasy" are recognized, and will be mapped to their logical font
+        automatically by this call.
+
+        @param name     May be NULL. The name of the font family.
+        @param style    The style (normal, bold, italic) of the typeface.
+        @return reference to the closest-matching typeface. Caller must call
+                unref() when they are done with the typeface.
+     */
+    ANPTypeface* (*createFromName)(const char name[], ANPTypefaceStyle);
+
+    /** Return a new reference to the typeface that most closely matches the
+        requested typeface and specified Style. Use this call if you want to
+        pick a new style from the same family of the existing typeface.
+        If family is NULL, this selects from the default font's family.
+
+        @param family  May be NULL. The name of the existing type face.
+        @param s       The style (normal, bold, italic) of the type face.
+        @return reference to the closest-matching typeface. Call must call
+                unref() when they are done.
+     */
+    ANPTypeface* (*createFromTypeface)(const ANPTypeface* family,
+                                       ANPTypefaceStyle);
+
+    /** Return the owner count of the typeface. A newly created typeface has an
+        owner count of 1. When the owner count is reaches 0, the typeface is
+        deleted.
+     */
+    int32_t (*getRefCount)(const ANPTypeface*);
+
+    /** Increment the owner count on the typeface
+     */
+    void (*ref)(ANPTypeface*);
+
+    /** Decrement the owner count on the typeface. When the count goes to 0,
+        the typeface is deleted.
+     */
+    void (*unref)(ANPTypeface*);
+
+    /** Return the style bits for the specified typeface
+     */
+    ANPTypefaceStyle (*getStyle)(const ANPTypeface*);
+
+    /** Some fonts are stored in files. If that is true for the fontID, then
+        this returns the byte length of the full file path. If path is not null,
+        then the full path is copied into path (allocated by the caller), up to
+        length bytes. If index is not null, then it is set to the truetype
+        collection index for this font, or 0 if the font is not in a collection.
+
+        Note: getFontPath does not assume that path is a null-terminated string,
+        so when it succeeds, it only copies the bytes of the file name and
+        nothing else (i.e. it copies exactly the number of bytes returned by the
+        function. If the caller wants to treat path[] as a C string, it must be
+        sure that it is allocated at least 1 byte larger than the returned size,
+        and it must copy in the terminating 0.
+
+        If the fontID does not correspond to a file, then the function returns
+        0, and the path and index parameters are ignored.
+
+        @param fontID  The font whose file name is being queried
+        @param path    Either NULL, or storage for receiving up to length bytes
+                       of the font's file name. Allocated by the caller.
+        @param length  The maximum space allocated in path (by the caller).
+                       Ignored if path is NULL.
+        @param index   Either NULL, or receives the TTC index for this font.
+                       If the font is not a TTC, then will be set to 0.
+        @return The byte length of th font's file name, or 0 if the font is not
+                baked by a file.
+     */
+    int32_t (*getFontPath)(const ANPTypeface*, char path[], int32_t length,
+                           int32_t* index);
+
+    /** Return a UTF8 encoded path name for the font directory, or NULL if not
+        supported. If returned, this string address will be valid for the life
+        of the plugin instance. It will always end with a '/' character.
+     */
+    const char* (*getFontDirectoryPath)();
+};
+
+struct ANPPaintInterfaceV0 : ANPInterface {
+    /** Return a new paint object, which holds all of the color and style
+        attributes that affect how things (geometry, text, bitmaps) are drawn
+        in a ANPCanvas.
+
+        The paint that is returned is not tied to any particular plugin
+        instance, but it must only be accessed from one thread at a time.
+     */
+    ANPPaint*   (*newPaint)();
+    void        (*deletePaint)(ANPPaint*);
+
+    ANPPaintFlags (*getFlags)(const ANPPaint*);
+    void        (*setFlags)(ANPPaint*, ANPPaintFlags);
+
+    ANPColor    (*getColor)(const ANPPaint*);
+    void        (*setColor)(ANPPaint*, ANPColor);
+
+    ANPPaintStyle (*getStyle)(const ANPPaint*);
+    void        (*setStyle)(ANPPaint*, ANPPaintStyle);
+
+    float       (*getStrokeWidth)(const ANPPaint*);
+    float       (*getStrokeMiter)(const ANPPaint*);
+    ANPPaintCap (*getStrokeCap)(const ANPPaint*);
+    ANPPaintJoin (*getStrokeJoin)(const ANPPaint*);
+    void        (*setStrokeWidth)(ANPPaint*, float);
+    void        (*setStrokeMiter)(ANPPaint*, float);
+    void        (*setStrokeCap)(ANPPaint*, ANPPaintCap);
+    void        (*setStrokeJoin)(ANPPaint*, ANPPaintJoin);
+
+    ANPTextEncoding (*getTextEncoding)(const ANPPaint*);
+    ANPPaintAlign (*getTextAlign)(const ANPPaint*);
+    float       (*getTextSize)(const ANPPaint*);
+    float       (*getTextScaleX)(const ANPPaint*);
+    float       (*getTextSkewX)(const ANPPaint*);
+    void        (*setTextEncoding)(ANPPaint*, ANPTextEncoding);
+    void        (*setTextAlign)(ANPPaint*, ANPPaintAlign);
+    void        (*setTextSize)(ANPPaint*, float);
+    void        (*setTextScaleX)(ANPPaint*, float);
+    void        (*setTextSkewX)(ANPPaint*, float);
+
+    /** Return the typeface ine paint, or null if there is none. This does not
+        modify the owner count of the returned typeface.
+     */
+    ANPTypeface* (*getTypeface)(const ANPPaint*);
+
+    /** Set the paint's typeface. If the paint already had a non-null typeface,
+        its owner count is decremented. If the new typeface is non-null, its
+        owner count is incremented.
+     */
+    void (*setTypeface)(ANPPaint*, ANPTypeface*);
+
+    /** Return the width of the text. If bounds is not null, return the bounds
+        of the text in that rectangle.
+     */
+    float (*measureText)(ANPPaint*, const void* text, uint32_t byteLength,
+                         ANPRectF* bounds);
+
+    /** Return the number of unichars specifed by the text.
+        If widths is not null, returns the array of advance widths for each
+            unichar.
+        If bounds is not null, returns the array of bounds for each unichar.
+     */
+    int (*getTextWidths)(ANPPaint*, const void* text, uint32_t byteLength,
+                         float widths[], ANPRectF bounds[]);
+
+    /** Return in metrics the spacing values for text, respecting the paint's
+        typeface and pointsize, and return the spacing between lines
+        (descent - ascent + leading). If metrics is NULL, it will be ignored.
+     */
+    float (*getFontMetrics)(ANPPaint*, ANPFontMetrics* metrics);
+};
+
+struct ANPCanvasInterfaceV0 : ANPInterface {
+    /** Return a canvas that will draw into the specified bitmap. Note: the
+        canvas copies the fields of the bitmap, so it need not persist after
+        this call, but the canvas DOES point to the same pixel memory that the
+        bitmap did, so the canvas should not be used after that pixel memory
+        goes out of scope. In the case of creating a canvas to draw into the
+        pixels provided by kDraw_ANPEventType, those pixels are only while
+        handling that event.
+
+        The canvas that is returned is not tied to any particular plugin
+        instance, but it must only be accessed from one thread at a time.
+     */
+    ANPCanvas*  (*newCanvas)(const ANPBitmap*);
+    void        (*deleteCanvas)(ANPCanvas*);
+
+    void        (*save)(ANPCanvas*);
+    void        (*restore)(ANPCanvas*);
+    void        (*translate)(ANPCanvas*, float tx, float ty);
+    void        (*scale)(ANPCanvas*, float sx, float sy);
+    void        (*rotate)(ANPCanvas*, float degrees);
+    void        (*skew)(ANPCanvas*, float kx, float ky);
+    void        (*concat)(ANPCanvas*, const ANPMatrix*);
+    void        (*clipRect)(ANPCanvas*, const ANPRectF*);
+    void        (*clipPath)(ANPCanvas*, const ANPPath*);
+
+    /** Return the current matrix on the canvas
+     */
+    void        (*getTotalMatrix)(ANPCanvas*, ANPMatrix*);
+    /** Return the current clip bounds in local coordinates, expanding it to
+        account for antialiasing edge effects if aa is true. If the
+        current clip is empty, return false and ignore the bounds argument.
+     */
+    bool        (*getLocalClipBounds)(ANPCanvas*, ANPRectF* bounds, bool aa);
+    /** Return the current clip bounds in device coordinates in bounds. If the
+        current clip is empty, return false and ignore the bounds argument.
+     */
+    bool        (*getDeviceClipBounds)(ANPCanvas*, ANPRectI* bounds);
+
+    void        (*drawColor)(ANPCanvas*, ANPColor);
+    void        (*drawPaint)(ANPCanvas*, const ANPPaint*);
+    void        (*drawLine)(ANPCanvas*, float x0, float y0, float x1, float y1,
+                            const ANPPaint*);
+    void        (*drawRect)(ANPCanvas*, const ANPRectF*, const ANPPaint*);
+    void        (*drawOval)(ANPCanvas*, const ANPRectF*, const ANPPaint*);
+    void        (*drawPath)(ANPCanvas*, const ANPPath*, const ANPPaint*);
+    void        (*drawText)(ANPCanvas*, const void* text, uint32_t byteLength,
+                            float x, float y, const ANPPaint*);
+    void       (*drawPosText)(ANPCanvas*, const void* text, uint32_t byteLength,
+                               const float xy[], const ANPPaint*);
+    void        (*drawBitmap)(ANPCanvas*, const ANPBitmap*, float x, float y,
+                              const ANPPaint*);
+    void        (*drawBitmapRect)(ANPCanvas*, const ANPBitmap*,
+                                  const ANPRectI* src, const ANPRectF* dst,
+                                  const ANPPaint*);
+};
+
+struct ANPWindowInterfaceV0 : ANPInterface {
+    /** Registers a set of rectangles that the plugin would like to keep on
+        screen. The rectangles are listed in order of priority with the highest
+        priority rectangle in location rects[0].  The browser will attempt to keep
+        as many of the rectangles on screen as possible and will scroll them into
+        view in response to the invocation of this method and other various events.
+        The count specifies how many rectangles are in the array. If the count is
+        zero it signals the browser that any existing rectangles should be cleared
+        and no rectangles will be tracked.
+     */
+    void (*setVisibleRects)(NPP instance, const ANPRectI rects[], int32_t count);
+    /** Clears any rectangles that are being tracked as a result of a call to
+        setVisibleRects. This call is equivalent to setVisibleRect(inst, NULL, 0).
+     */
+    void    (*clearVisibleRects)(NPP instance);
+    /** Given a boolean value of true the device will be requested to provide
+        a keyboard. A value of false will result in a request to hide the
+        keyboard. Further, the on-screen keyboard will not be displayed if a
+        physical keyboard is active.
+     */
+    void    (*showKeyboard)(NPP instance, bool value);
+    /** Called when a plugin wishes to enter into full screen mode. The plugin's
+        Java class (defined in the plugin's apk manifest) will be called
+        asynchronously to provide a View object to be displayed full screen.
+     */
+    void    (*requestFullScreen)(NPP instance);
+    /** Called when a plugin wishes to exit from full screen mode. As a result,
+        the plugin's full screen view will be discarded by the view system.
+     */
+    void    (*exitFullScreen)(NPP instance);
+    /** Called when a plugin wishes to be zoomed and centered in the current view.
+     */
+    void    (*requestCenterFitZoom)(NPP instance);
+};
+
+///////////////////////////////////////////////////////////////////////////////
+
+enum ANPSampleFormats {
+    kUnknown_ANPSamleFormat     = 0,
+    kPCM16Bit_ANPSampleFormat   = 1,
+    kPCM8Bit_ANPSampleFormat    = 2
+};
+typedef int32_t ANPSampleFormat;
+
+/** The audio buffer is passed to the callback proc to request more samples.
+    It is owned by the system, and the callback may read it, but should not
+    maintain a pointer to it outside of the scope of the callback proc.
+ */
+struct ANPAudioBuffer {
+    // RO - repeat what was specified in newTrack()
+    int32_t     channelCount;
+    // RO - repeat what was specified in newTrack()
+    ANPSampleFormat  format;
+    /** This buffer is owned by the caller. Inside the callback proc, up to
+        "size" bytes of sample data should be written into this buffer. The
+        address is only valid for the scope of a single invocation of the
+        callback proc.
+     */
+    void*       bufferData;
+    /** On input, specifies the maximum number of bytes that can be written
+        to "bufferData". On output, specifies the actual number of bytes that
+        the callback proc wrote into "bufferData".
+     */
+    uint32_t    size;
+};
+
+enum ANPAudioEvents {
+    /** This event is passed to the callback proc when the audio-track needs
+        more sample data written to the provided buffer parameter.
+     */
+    kMoreData_ANPAudioEvent = 0,
+    /** This event is passed to the callback proc if the audio system runs out
+        of sample data. In this event, no buffer parameter will be specified
+        (i.e. NULL will be passed to the 3rd parameter).
+     */
+    kUnderRun_ANPAudioEvent = 1
+};
+typedef int32_t ANPAudioEvent;
+
+/** Called to feed sample data to the track. This will be called in a separate
+    thread. However, you may call trackStop() from the callback (but you
+    cannot delete the track).
+
+    For example, when you have written the last chunk of sample data, you can
+    immediately call trackStop(). This will take effect after the current
+    buffer has been played.
+
+    The "user" parameter is the same value that was passed to newTrack()
+ */
+typedef void (*ANPAudioCallbackProc)(ANPAudioEvent event, void* user,
+                                     ANPAudioBuffer* buffer);
+
+struct ANPAudioTrack;   // abstract type for audio tracks
+
+struct ANPAudioTrackInterfaceV0 : ANPInterface {
+    /** Create a new audio track, or NULL on failure. The track is initially in
+        the stopped state and therefore ANPAudioCallbackProc will not be called
+        until the track is started.
+     */
+    ANPAudioTrack*  (*newTrack)(uint32_t sampleRate,    // sampling rate in Hz
+                                ANPSampleFormat,
+                                int channelCount,       // MONO=1, STEREO=2
+                                ANPAudioCallbackProc,
+                                void* user);
+    /** Deletes a track that was created using newTrack.  The track can be
+        deleted in any state and it waits for the ANPAudioCallbackProc thread
+        to exit before returning.
+     */
+    void (*deleteTrack)(ANPAudioTrack*);
+
+    void (*start)(ANPAudioTrack*);
+    void (*pause)(ANPAudioTrack*);
+    void (*stop)(ANPAudioTrack*);
+    /** Returns true if the track is not playing (e.g. pause or stop was called,
+        or start was never called.
+     */
+    bool (*isStopped)(ANPAudioTrack*);
+};
+
+///////////////////////////////////////////////////////////////////////////////
+// DEFINITION OF VALUES PASSED THROUGH NPP_HandleEvent
+
+enum ANPEventTypes {
+    kNull_ANPEventType          = 0,
+    kKey_ANPEventType           = 1,
+    /** Mouse events are triggered by either clicking with the navigational pad
+        or by tapping the touchscreen (if the kDown_ANPTouchAction is handled by
+        the plugin then no mouse event is generated).  The kKey_ANPEventFlag has
+        to be set to true in order to receive these events.
+     */
+    kMouse_ANPEventType         = 2,
+    /** Touch events are generated when the user touches on the screen. The
+        kTouch_ANPEventFlag has to be set to true in order to receive these
+        events.
+     */
+    kTouch_ANPEventType         = 3,
+    /** Only triggered by a plugin using the kBitmap_ANPDrawingModel. This event
+        signals that the plugin needs to redraw itself into the provided bitmap.
+     */
+    kDraw_ANPEventType          = 4,
+    kLifecycle_ANPEventType     = 5,
+
+    /** This event type is completely defined by the plugin.
+        When creating an event, the caller must always set the first
+        two fields, the remaining data is optional.
+            ANPEvent evt;
+            evt.inSize = sizeof(ANPEvent);
+            evt.eventType = kCustom_ANPEventType
+            // other data slots are optional
+            evt.other[] = ...;
+        To post a copy of the event, call
+            eventInterface->postEvent(myNPPInstance, &evt);
+        That call makes a copy of the event struct, and post that on the event
+        queue for the plugin.
+     */
+    kCustom_ANPEventType   = 6,
+};
+typedef int32_t ANPEventType;
+
+enum ANPKeyActions {
+    kDown_ANPKeyAction  = 0,
+    kUp_ANPKeyAction    = 1,
+};
+typedef int32_t ANPKeyAction;
+
+#include "ANPKeyCodes.h"
+typedef int32_t ANPKeyCode;
+
+enum ANPKeyModifiers {
+    kAlt_ANPKeyModifier     = 1 << 0,
+    kShift_ANPKeyModifier   = 1 << 1,
+};
+// bit-field containing some number of ANPKeyModifier bits
+typedef uint32_t ANPKeyModifier;
+
+enum ANPMouseActions {
+    kDown_ANPMouseAction  = 0,
+    kUp_ANPMouseAction    = 1,
+};
+typedef int32_t ANPMouseAction;
+
+enum ANPTouchActions {
+    /** This occurs when the user first touches on the screen. As such, this
+        action will always occur prior to any of the other touch actions. If
+        the plugin chooses to not handle this action then no other events
+        related to that particular touch gesture will be generated.
+     */
+    kDown_ANPTouchAction        = 0,
+    kUp_ANPTouchAction          = 1,
+    kMove_ANPTouchAction        = 2,
+    kCancel_ANPTouchAction      = 3,
+    // The web view will ignore the return value from the following actions
+    kLongPress_ANPTouchAction   = 4,
+    kDoubleTap_ANPTouchAction   = 5,
+};
+typedef int32_t ANPTouchAction;
+
+enum ANPLifecycleActions {
+    /** The web view containing this plugin has been paused.  See documentation
+        on the android activity lifecycle for more information.
+     */
+    kPause_ANPLifecycleAction           = 0,
+    /** The web view containing this plugin has been resumed. See documentation
+        on the android activity lifecycle for more information.
+     */
+    kResume_ANPLifecycleAction          = 1,
+    /** The plugin has focus and is now the recipient of input events (e.g. key,
+        touch, etc.)
+     */
+    kGainFocus_ANPLifecycleAction       = 2,
+    /** The plugin has lost focus and will not receive any input events until it
+        regains focus. This event is always preceded by a GainFocus action.
+     */
+    kLoseFocus_ANPLifecycleAction       = 3,
+    /** The browser is running low on available memory and is requesting that
+        the plugin free any unused/inactive resources to prevent a performance
+        degradation.
+     */
+    kFreeMemory_ANPLifecycleAction      = 4,
+    /** The page has finished loading. This happens when the page's top level
+        frame reports that it has completed loading.
+     */
+    kOnLoad_ANPLifecycleAction          = 5,
+    /** The browser is honoring the plugin's request to go full screen. Upon
+        returning from this event the browser will resize the plugin's java
+        surface to full-screen coordinates.
+     */
+    kEnterFullScreen_ANPLifecycleAction = 6,
+    /** The browser has exited from full screen mode. Immediately prior to
+        sending this event the browser has resized the plugin's java surface to
+        its original coordinates.
+     */
+    kExitFullScreen_ANPLifecycleAction  = 7,
+    /** The plugin is visible to the user on the screen. This event will always
+        occur after a kOffScreen_ANPLifecycleAction event.
+     */
+    kOnScreen_ANPLifecycleAction        = 8,
+    /** The plugin is no longer visible to the user on the screen. This event
+        will always occur prior to an kOnScreen_ANPLifecycleAction event.
+     */
+    kOffScreen_ANPLifecycleAction       = 9,
+};
+typedef uint32_t ANPLifecycleAction;
+
+/* This is what is passed to NPP_HandleEvent() */
+struct ANPEvent {
+    uint32_t        inSize;  // size of this struct in bytes
+    ANPEventType    eventType;
+    // use based on the value in eventType
+    union {
+        struct {
+            ANPKeyAction    action;
+            ANPKeyCode      nativeCode;
+            int32_t         virtualCode;    // windows virtual key code
+            ANPKeyModifier  modifiers;
+            int32_t         repeatCount;    // 0 for initial down (or up)
+            int32_t         unichar;        // 0 if there is no value
+        } key;
+        struct {
+            ANPMouseAction  action;
+            int32_t         x;  // relative to your "window" (0...width)
+            int32_t         y;  // relative to your "window" (0...height)
+        } mouse;
+        struct {
+            ANPTouchAction  action;
+            ANPKeyModifier  modifiers;
+            int32_t         x;  // relative to your "window" (0...width)
+            int32_t         y;  // relative to your "window" (0...height)
+        } touch;
+        struct {
+            ANPLifecycleAction  action;
+        } lifecycle;
+        struct {
+            ANPDrawingModel model;
+            // relative to (0,0) in top-left of your plugin
+            ANPRectI        clip;
+            // use based on the value in model
+            union {
+                ANPBitmap   bitmap;
+            } data;
+        } draw;
+        int32_t     other[8];
+    } data;
+};
+
+struct ANPEventInterfaceV0 : ANPInterface {
+    /** Post a copy of the specified event to the plugin. The event will be
+        delivered to the plugin in its main thread (the thread that receives
+        other ANPEvents). If, after posting before delivery, the NPP instance
+        is torn down, the event will be discarded.
+     */
+    void (*postEvent)(NPP inst, const ANPEvent* event);
+};
+
+struct ANPSystemInterfaceV0 : ANPInterface {
+    /** Return the path name for the current Application's plugin data directory,
+        or NULL if not supported
+     */
+    const char* (*getApplicationDataDirectory)();
+
+    /** A helper function to load java classes from the plugin's apk.  The
+        function looks for a class given the fully qualified and null terminated
+        string representing the className. For example,
+
+        const char* className = "com.android.mypackage.MyClass";
+
+        If the class cannot be found or there is a problem loading the class
+        NULL will be returned.
+     */
+    jclass (*loadJavaClass)(NPP instance, const char* className);
+};
+
+struct ANPSurfaceInterfaceV0 : ANPInterface {
+  /** Locks the surface from manipulation by other threads and provides a bitmap
+        to be written to.  The dirtyRect param specifies which portion of the
+        bitmap will be written to.  If the dirtyRect is NULL then the entire
+        surface will be considered dirty.  If the lock was successful the function
+        will return true and the bitmap will be set to point to a valid bitmap.
+        If not the function will return false and the bitmap will be set to NULL.
+  */
+  bool (*lock)(JNIEnv* env, jobject surface, ANPBitmap* bitmap, ANPRectI* dirtyRect);
+  /** Given a locked surface handle (i.e. result of a successful call to lock)
+        the surface is unlocked and the contents of the bitmap, specifically
+        those inside the dirtyRect are written to the screen.
+  */
+  void (*unlock)(JNIEnv* env, jobject surface);
+};
+
+typedef int32_t   int32;
+typedef uint32_t uint32;
+typedef int16_t   int16;
+typedef uint16_t uint16;
+
+#endif
new file mode 100644
--- a/dom/plugins/base/npfunctions.h
+++ b/dom/plugins/base/npfunctions.h
@@ -43,16 +43,20 @@
 #define NP_LOADDS _System
 #else
 #define NP_LOADDS
 #endif
 
 #include "npapi.h"
 #include "npruntime.h"
 
+#ifdef 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);
 typedef int32_t      (* NP_LOADDS NPP_WriteReadyProcPtr)(NPP instance, NPStream* stream);
 typedef int32_t      (* NP_LOADDS NPP_WriteProcPtr)(NPP instance, NPStream* stream, int32_t offset, int32_t len, void* buffer);
 typedef void         (* NP_LOADDS NPP_StreamAsFileProcPtr)(NPP instance, NPStream* stream, const char* fname);
@@ -302,18 +306,23 @@ 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
-typedef NPError        (*NP_InitializeFunc)(NPNetscapeFuncs*, NPPluginFuncs*);
-NP_EXPORT(NPError)     NP_Initialize(NPNetscapeFuncs* bFuncs, NPPluginFuncs* pFuncs);
+#ifdef 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);
 NP_EXPORT(NPError)     NP_Shutdown(void);
 typedef NPError        (*NP_GetValueFunc)(void *, NPPVariable, void *);
 NP_EXPORT(NPError)     NP_GetValue(void *future, NPPVariable aVariable, void *aValue);
 #ifdef __cplusplus
 }
 #endif
--- a/dom/plugins/base/nsJSNPRuntime.cpp
+++ b/dom/plugins/base/nsJSNPRuntime.cpp
@@ -356,17 +356,17 @@ GetJSContext(NPP npp)
 
   nsCOMPtr<nsISupports> documentContainer = doc->GetContainer();
   nsCOMPtr<nsIScriptGlobalObject> sgo(do_GetInterface(documentContainer));
   NS_ENSURE_TRUE(sgo, nsnull);
 
   nsIScriptContext *scx = sgo->GetContext();
   NS_ENSURE_TRUE(scx, nsnull);
 
-  return (JSContext *)scx->GetNativeContext();
+  return scx->GetNativeContext();
 }
 
 }
 }
 }
 
 static NPP
 LookupNPP(NPObject *npobj);
--- a/dom/plugins/base/nsNPAPIPlugin.cpp
+++ b/dom/plugins/base/nsNPAPIPlugin.cpp
@@ -122,16 +122,23 @@ using mozilla::plugins::PluginModulePare
 #ifdef MOZ_X11
 #include "mozilla/X11Util.h"
 #endif
 
 #ifdef XP_WIN
 #include <windows.h>
 #endif
 
+#ifdef 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;
 
 // We should make this const...
 static NPNetscapeFuncs sBrowserFuncs = {
   sizeof(sBrowserFuncs),
   (NP_VERSION_MAJOR << 8) + NP_VERSION_MINOR,
   _geturl,
@@ -472,17 +479,17 @@ nsNPAPIPlugin::CreatePlugin(nsPluginTag 
   if (!plugin)
     return NS_ERROR_OUT_OF_MEMORY;
 
   PluginLibrary* pluginLib = GetNewPluginLibrary(aPluginTag);
   if (!pluginLib) {
     return NS_ERROR_FAILURE;
   }
 
-#ifdef XP_MACOSX
+#if defined(XP_MACOSX) || defined(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);
@@ -713,17 +720,17 @@ static JSContext *
 GetJSContextFromDoc(nsIDocument *doc)
 {
   nsIScriptGlobalObject *sgo = doc->GetScriptGlobalObject();
   NS_ENSURE_TRUE(sgo, nsnull);
 
   nsIScriptContext *scx = sgo->GetContext();
   NS_ENSURE_TRUE(scx, nsnull);
 
-  return (JSContext *)scx->GetNativeContext();
+  return scx->GetNativeContext();
 }
 
 static JSContext *
 GetJSContextFromNPP(NPP npp)
 {
   nsIDocument *doc = GetDocumentFromNPP(npp);
   NS_ENSURE_TRUE(doc, nsnull);
 
@@ -2259,27 +2266,134 @@ NPError NP_CALLBACK
   }
 
   case NPNVsupportsUpdatedCocoaTextInputBool: {
     *(NPBool*)result = true;
     return NPERR_NO_ERROR;
   }
 #endif
 
+#ifdef ANDROID
+    case kLogInterfaceV0_ANPGetValue: {
+      LOG("get log interface");
+      ANPLogInterfaceV0 *i = (ANPLogInterfaceV0 *) result;
+      InitLogInterface(i);
+      return NPERR_NO_ERROR;
+    }
+
+    case kBitmapInterfaceV0_ANPGetValue: {
+      LOG("get bitmap interface");
+      ANPBitmapInterfaceV0 *i = (ANPBitmapInterfaceV0 *) result;
+      InitBitmapInterface(i);
+      return NPERR_NO_ERROR;
+    }
+
+    case kMatrixInterfaceV0_ANPGetValue: {
+      LOG("get matrix interface");
+      ANPMatrixInterfaceV0 *i = (ANPMatrixInterfaceV0 *) result;
+      InitMatrixInterface(i);
+      return NPERR_NO_ERROR;
+    }
+      
+    case kPathInterfaceV0_ANPGetValue: {
+      LOG("get path interface");
+      ANPPathInterfaceV0 *i = (ANPPathInterfaceV0 *) result;
+      InitPathInterface(i);
+      return NPERR_NO_ERROR;
+    }
+      
+    case kTypefaceInterfaceV0_ANPGetValue: {
+      LOG("get typeface interface");
+      ANPTypefaceInterfaceV0 *i = (ANPTypefaceInterfaceV0 *) result;
+      InitTypeFaceInterface(i);
+      return NPERR_NO_ERROR;
+    }
+
+    case kPaintInterfaceV0_ANPGetValue: {
+      LOG("get paint interface");
+      ANPPaintInterfaceV0 *i = (ANPPaintInterfaceV0 *) result;
+      InitPaintInterface(i);
+      return NPERR_NO_ERROR;
+    }
+
+    case kCanvasInterfaceV0_ANPGetValue: {
+      LOG("get canvas interface");
+      ANPCanvasInterfaceV0 *i = (ANPCanvasInterfaceV0 *) result;
+      InitCanvasInterface(i);
+      return NPERR_NO_ERROR;
+    }
+
+    case kWindowInterfaceV0_ANPGetValue: {
+      LOG("get window interface");
+      ANPWindowInterfaceV0 *i = (ANPWindowInterfaceV0 *) result;
+      InitWindowInterface(i);
+      return NPERR_NO_ERROR;
+    }
+
+    case kAudioTrackInterfaceV0_ANPGetValue: {
+      LOG("get audio interface");
+      ANPAudioTrackInterfaceV0 *i = (ANPAudioTrackInterfaceV0 *) result;
+      InitAudioTrackInterface(i);
+      return NPERR_NO_ERROR;
+    }
+
+    case kEventInterfaceV0_ANPGetValue: {
+      LOG("get event interface");
+      ANPEventInterfaceV0 *i = (ANPEventInterfaceV0 *) result;
+      InitEventInterface(i);
+      return NPERR_NO_ERROR;
+    }
+
+    case kSystemInterfaceV0_ANPGetValue: {
+      LOG("get system interface");
+      ANPSystemInterfaceV0* i = reinterpret_cast<ANPSystemInterfaceV0*>(result);
+      InitSystemInterface(i);
+      LOG("done system interface");
+      return NPERR_NO_ERROR;
+    }
+
+    case kSurfaceInterfaceV0_ANPGetValue: {
+      LOG("get surface interface");
+      ANPSurfaceInterfaceV0 *i = (ANPSurfaceInterfaceV0 *) result;
+      InitSurfaceInterface(i);
+      return NPERR_NO_ERROR;
+    }
+      
+    case kSupportedDrawingModel_ANPGetValue: {
+      LOG("get supported drawing model");
+      uint32_t* bits = reinterpret_cast<uint32_t*>(result);
+      *bits = kBitmap_ANPDrawingModel && kSurface_ANPDrawingModel;
+      return NPERR_NO_ERROR;
+    }  
+
+    case kJavaContext_ANPGetValue: {
+      LOG("get context");
+      JNIEnv* env    = GetJNIForThread();
+      jclass cls     = env->FindClass("org/mozilla/gecko/GeckoApp");
+      jfieldID field = env->GetStaticFieldID(cls, "mAppContext",
+                                             "Lorg/mozilla/gecko/GeckoApp;");
+      jobject ret = env->GetStaticObjectField(cls, field);
+      int32_t* i  = reinterpret_cast<int32_t*>(result);
+      *i = reinterpret_cast<int32_t>(ret);
+      return NPERR_NO_ERROR;
+    }
+#endif
+
   // we no longer hand out any XPCOM objects
   case NPNVDOMElement:
     // fall through
   case NPNVDOMWindow:
     // fall through
   case NPNVserviceManager:
     // old XPCOM objects, no longer supported, but null out the out
     // param to avoid crashing plugins that still try to use this.
     *(nsISupports**)result = nsnull;
     // fall through
   default:
+    NPN_PLUGIN_LOG(PLUGIN_LOG_NORMAL, ("NPN_getvalue unhandled get value: %d\n", variable));
     return NPERR_GENERIC_ERROR;
   }
 }
 
 NPError NP_CALLBACK
 _setvalue(NPP npp, NPPVariable variable, void *result)
 {
   if (!NS_IsMainThread()) {
@@ -2369,17 +2483,24 @@ NPError NP_CALLBACK
         inst->SetEventModel((NPEventModel)NS_PTR_TO_INT32(result));
         return NPERR_NO_ERROR;
       }
       else {
         return NPERR_GENERIC_ERROR;
       }
     }
 #endif
-
+#ifdef 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:
       return NPERR_GENERIC_ERROR;
   }
 }
 
 NPError NP_CALLBACK
 _requestread(NPStream *pstream, NPByteRange *rangeList)
 {
--- a/dom/plugins/base/nsNPAPIPluginInstance.cpp
+++ b/dom/plugins/base/nsNPAPIPluginInstance.cpp
@@ -56,33 +56,46 @@
 #include "nsIScriptContext.h"
 #include "nsDirectoryServiceDefs.h"
 #include "nsJSNPRuntime.h"
 #include "nsPluginStreamListenerPeer.h"
 #include "nsSize.h"
 #include "nsNetCID.h"
 #include "nsIContent.h"
 
+#ifdef ANDROID
+#include "ANPBase.h"
+#include <android/log.h>
+#include "android_npapi.h"
+#include "mozilla/Mutex.h"
+#include "mozilla/CondVar.h"
+#include "AndroidBridge.h"
+#endif
+
 using namespace mozilla;
 using namespace mozilla::plugins::parent;
 
 static NS_DEFINE_IID(kIOutputStreamIID, NS_IOUTPUTSTREAM_IID);
 static NS_DEFINE_IID(kIPluginStreamListenerIID, NS_IPLUGINSTREAMLISTENER_IID);
 
-NS_IMPL_ISUPPORTS0(nsNPAPIPluginInstance)
+NS_IMPL_THREADSAFE_ISUPPORTS0(nsNPAPIPluginInstance)
 
 nsNPAPIPluginInstance::nsNPAPIPluginInstance(nsNPAPIPlugin* plugin)
   :
 #ifdef XP_MACOSX
 #ifdef NP_NO_QUICKDRAW
     mDrawingModel(NPDrawingModelCoreGraphics),
 #else
     mDrawingModel(NPDrawingModelQuickDraw),
 #endif
 #endif
+#ifdef ANDROID
+    mSurface(nsnull),
+    mDrawingModel(0),
+#endif
     mRunning(NOT_STARTED),
     mWindowless(PR_FALSE),
     mWindowlessLocal(PR_FALSE),
     mTransparent(PR_FALSE),
     mUsesDOMForCursor(PR_FALSE),
     mInPluginInitCall(PR_FALSE),
     mPlugin(plugin),
     mMIMEType(nsnull),
@@ -679,17 +692,17 @@ NPError nsNPAPIPluginInstance::SetUsesDO
 }
 
 PRBool
 nsNPAPIPluginInstance::UsesDOMForCursor()
 {
   return mUsesDOMForCursor;
 }
 
-#ifdef XP_MACOSX
+#if defined(XP_MACOSX)
 void nsNPAPIPluginInstance::SetDrawingModel(NPDrawingModel aModel)
 {
   mDrawingModel = aModel;
 }
 
 void nsNPAPIPluginInstance::SetEventModel(NPEventModel aModel)
 {
   // the event model needs to be set for the object frame immediately
@@ -697,22 +710,79 @@ void nsNPAPIPluginInstance::SetEventMode
   GetOwner(getter_AddRefs(owner));
   if (!owner) {
     NS_WARNING("Trying to set event model without a plugin instance owner!");
     return;
   }
 
   owner->SetEventModel(aModel);
 }
+#endif
+
+#if defined(ANDROID)
+void nsNPAPIPluginInstance::SetDrawingModel(PRUint32 aModel)
+{
+  mDrawingModel = aModel;
+}
+
+class SurfaceGetter : public nsRunnable {
+public:
+  SurfaceGetter(NPPluginFuncs* aPluginFunctions, NPP_t aNPP) : 
+    mHaveSurface(PR_FALSE), mPluginFunctions(aPluginFunctions), mNPP(aNPP) {
+    mLock = new Mutex("SurfaceGetter::Lock");
+    mCondVar = new CondVar(*mLock, "SurfaceGetter::CondVar");
+    
+  }
+  ~SurfaceGetter() {
+    delete mLock;
+    delete mCondVar;
+  }
+  nsresult Run() {
+    MutexAutoLock lock(*mLock);
+    (*mPluginFunctions->getvalue)(&mNPP, kJavaSurface_ANPGetValue, &mSurface);
+    mHaveSurface = PR_TRUE;
+    mCondVar->Notify();
+    return NS_OK;
+  }
+  void* GetSurface() {
+    MutexAutoLock lock(*mLock);
+    mHaveSurface = PR_FALSE;
+    AndroidBridge::Bridge()->PostToJavaThread(this);
+    while (!mHaveSurface)
+      mCondVar->Wait();
+    return mSurface;
+  }
+private:
+  NPP_t mNPP;
+  void* mSurface;
+  Mutex* mLock;
+  CondVar* mCondVar;
+  PRBool mHaveSurface;
+  NPPluginFuncs* mPluginFunctions;
+};
+
+
+void* nsNPAPIPluginInstance::GetJavaSurface()
+{
+  if (mDrawingModel != kSurface_ANPDrawingModel)
+    return nsnull;
+  
+  if (mSurface)
+    return mSurface;
+
+  nsCOMPtr<SurfaceGetter> sg = new SurfaceGetter(mPlugin->PluginFuncs(), mNPP);
+  mSurface = sg->GetSurface();
+  return mSurface;
+}
 
 #endif
 
 nsresult nsNPAPIPluginInstance::GetDrawingModel(PRInt32* aModel)
 {
-#ifdef XP_MACOSX
+#if defined(XP_MACOSX) || defined(ANDROID)
   *aModel = (PRInt32)mDrawingModel;
   return NS_OK;
 #else
   return NS_ERROR_FAILURE;
 #endif
 }
 
 nsresult nsNPAPIPluginInstance::IsRemoteDrawingCoreAnimation(PRBool* aDrawing)
@@ -801,17 +871,22 @@ nsNPAPIPluginInstance::DefineJavaPropert
     return NS_ERROR_FAILURE;
 
   return NS_OK;
 }
 
 nsresult
 nsNPAPIPluginInstance::IsWindowless(PRBool* isWindowless)
 {
+#ifdef ANDROID
+  // On android, pre-honeycomb, all plugins are treated as windowless.
+  *isWindowless = PR_TRUE;
+#else
   *isWindowless = mWindowless;
+#endif
   return NS_OK;
 }
 
 class NS_STACK_CLASS AutoPluginLibraryCall
 {
 public:
   AutoPluginLibraryCall(nsNPAPIPluginInstance* aThis)
     : mThis(aThis), mGuard(aThis), mLibrary(nsnull)
@@ -1061,24 +1136,50 @@ nsNPAPIPluginInstance::PrivateModeStateC
       NPBool value = static_cast<NPBool>(pme);
       NS_TRY_SAFE_CALL_RETURN(error, (*pluginFunctions->setvalue)(&mNPP, NPNVprivateModeBool, &value), this);
       return (error == NPERR_NO_ERROR) ? NS_OK : NS_ERROR_FAILURE;
     }
   }
   return NS_ERROR_FAILURE;
 }
 
+class DelayUnscheduleEvent : public nsRunnable {
+public:
+  nsRefPtr<nsNPAPIPluginInstance> mInstance;
+  uint32_t mTimerID;
+  DelayUnscheduleEvent(nsNPAPIPluginInstance* aInstance, uint32_t aTimerId)
+    : mInstance(aInstance)
+    , mTimerID(aTimerId)
+  {}
+
+  ~DelayUnscheduleEvent() {}
+
+  NS_IMETHOD Run();
+};
+
+NS_IMETHODIMP
+DelayUnscheduleEvent::Run()
+{
+  mInstance->UnscheduleTimer(mTimerID);
+  return NS_OK;
+}
+
+
 static void
 PluginTimerCallback(nsITimer *aTimer, void *aClosure)
 {
   nsNPAPITimer* t = (nsNPAPITimer*)aClosure;
   NPP npp = t->npp;
   uint32_t id = t->id;
 
+  // Some plugins (Flash on Android) calls unscheduletimer
+  // from this callback.
+  t->inCallback = PR_TRUE;
   (*(t->callback))(npp, id);
+  t->inCallback = PR_FALSE;
 
   // Make sure we still have an instance and the timer is still alive
   // after the callback.
   nsNPAPIPluginInstance *inst = (nsNPAPIPluginInstance*)npp->ndata;
   if (!inst || !inst->TimerWithID(id, NULL))
     return;
 
   // use UnscheduleTimer to clean up if this is a one-shot timer
@@ -1102,16 +1203,17 @@ nsNPAPIPluginInstance::TimerWithID(uint3
   return nsnull;
 }
 
 uint32_t
 nsNPAPIPluginInstance::ScheduleTimer(uint32_t interval, NPBool repeat, void (*timerFunc)(NPP npp, uint32_t timerID))
 {
   nsNPAPITimer *newTimer = new nsNPAPITimer();
 
+  newTimer->inCallback = PR_FALSE;
   newTimer->npp = &mNPP;
 
   // generate ID that is unique to this instance
   uint32_t uniqueID = mTimers.Length();
   while ((uniqueID == 0) || TimerWithID(uniqueID, NULL))
     uniqueID++;
   newTimer->id = uniqueID;
 
@@ -1139,16 +1241,22 @@ void
 nsNPAPIPluginInstance::UnscheduleTimer(uint32_t timerID)
 {
   // find the timer struct by ID
   PRUint32 index;
   nsNPAPITimer* t = TimerWithID(timerID, &index);
   if (!t)
     return;
 
+  if (t->inCallback) {
+    nsCOMPtr<nsIRunnable> e = new DelayUnscheduleEvent(this, timerID);
+    NS_DispatchToCurrentThread(e);
+    return;
+  }
+
   // cancel the timer
   t->timer->Cancel();
 
   // remove timer struct from array
   mTimers.RemoveElementAt(index);
 
   // delete timer
   delete t;
@@ -1258,17 +1366,17 @@ nsNPAPIPluginInstance::GetJSContext(JSCo
 
   if (NS_SUCCEEDED(rv) && document) {
     nsIScriptGlobalObject *global = document->GetScriptGlobalObject();
 
     if (global) {
       nsIScriptContext *context = global->GetContext();
 
       if (context) {
-        *outContext = (JSContext*) context->GetNativeContext();
+        *outContext = context->GetNativeContext();
       }
     }
   }
 
   return rv;
 }
 
 nsresult
--- a/dom/plugins/base/nsNPAPIPluginInstance.h
+++ b/dom/plugins/base/nsNPAPIPluginInstance.h
@@ -63,16 +63,17 @@ class nsIOutputStream;
 
 class nsNPAPITimer
 {
 public:
   NPP npp;
   uint32_t id;
   nsCOMPtr<nsITimer> timer;
   void (*callback)(NPP npp, uint32_t timerID);
+  PRBool inCallback;
 };
 
 class nsNPAPIPluginInstance : public nsISupports
 {
 private:
   typedef mozilla::PluginLibrary PluginLibrary;
 
 public:
@@ -80,16 +81,19 @@ 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
+  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(PRBool* aDrawing);
   nsresult GetJSObject(JSContext *cx, JSObject** outObject);
   nsresult DefineJavaProperties();
   nsresult IsWindowless(PRBool* isWindowless);
   nsresult AsyncSetWindow(NPWindow* window);
@@ -136,16 +140,21 @@ public:
   NPError SetUsesDOMForCursor(PRBool aUsesDOMForCursor);
   PRBool UsesDOMForCursor();
 
 #ifdef XP_MACOSX
   void SetDrawingModel(NPDrawingModel aModel);
   void SetEventModel(NPEventModel aModel);
 #endif
 
+#ifdef ANDROID
+  void SetDrawingModel(PRUint32 aModel);
+  void* GetJavaSurface();
+#endif
+
   nsresult NewStreamListener(const char* aURL, void* notifyData,
                              nsIPluginStreamListener** listener);
 
   nsNPAPIPluginInstance(nsNPAPIPlugin* plugin);
   virtual ~nsNPAPIPluginInstance();
 
   // To be called when an instance becomes orphaned, when
   // it's plugin is no longer guaranteed to be around.
@@ -202,16 +211,20 @@ protected:
   // The structure used to communicate between the plugin instance and
   // the browser.
   NPP_t mNPP;
 
 #ifdef XP_MACOSX
   NPDrawingModel mDrawingModel;
 #endif
 
+#ifdef ANDROID
+  PRUint32 mDrawingModel;
+#endif
+
   enum {
     NOT_STARTED,
     RUNNING,
     DESTROYING,
     DESTROYED
   } mRunning;
 
   // these are used to store the windowless properties
@@ -245,11 +258,14 @@ private:
   nsTArray<nsNPAPITimer*> mTimers;
 
   // non-null during a HandleEvent call
   void* mCurrentPluginEvent;
 
   nsCOMPtr<nsIURI> mURI;
 
   PRPackedBool mUsePluginLayersPref;
+#ifdef ANDROID
+  void* mSurface;
+#endif
 };
 
 #endif // nsNPAPIPluginInstance_h_
--- a/dom/plugins/base/nsPluginHost.cpp
+++ b/dom/plugins/base/nsPluginHost.cpp
@@ -154,16 +154,21 @@
 
 #if defined(XP_WIN)
 #include "nsIWindowMediator.h"
 #include "nsIBaseWindow.h"
 #include "windows.h"
 #include "winbase.h"
 #endif
 
+#ifdef ANDROID
+#include <android/log.h>
+#define LOG(args...)  __android_log_print(ANDROID_LOG_INFO, "GeckoPlugins" , ## args)
+#endif
+
 using namespace mozilla;
 using mozilla::TimeStamp;
 
 // Null out a strong ref to a linked list iteratively to avoid
 // exhausting the stack (bug 486349).
 #define NS_ITERATIVE_UNREF_LIST(type_, list_, mNext_)                \
   {                                                                  \
     while (list_) {                                                  \
@@ -2224,17 +2229,17 @@ nsresult nsPluginHost::ScanPluginsDirect
     while (NS_SUCCEEDED(dirEnum->HasMoreElements(&hasMore)) && hasMore) {
       nsCOMPtr<nsISupports> supports;
       nsresult rv = dirEnum->GetNext(getter_AddRefs(supports));
       if (NS_FAILED(rv))
         continue;
       nsCOMPtr<nsIFile> nextDir(do_QueryInterface(supports, &rv));
       if (NS_FAILED(rv))
         continue;
-
+      
       // don't pass aPluginsChanged directly to prevent it from been reset
       PRBool pluginschanged = PR_FALSE;
       ScanPluginsDirectory(nextDir, aCreatePluginList, &pluginschanged);
 
       if (pluginschanged)
         *aPluginsChanged = PR_TRUE;
 
       // if changes are detected and we are not creating the list, do not proceed
@@ -2319,16 +2324,20 @@ nsresult nsPluginHost::FindPlugins(PRBoo
 
     // if we are just looking for possible changes,
     // no need to proceed if changes are detected
     if (!aCreatePluginList && *aPluginsChanged) {
       NS_ITERATIVE_UNREF_LIST(nsRefPtr<nsPluginTag>, mCachedPlugins, mNext);
       NS_ITERATIVE_UNREF_LIST(nsRefPtr<nsInvalidPluginTag>, mInvalidPlugins, mNext);
       return NS_OK;
     }
+  } else {
+#ifdef ANDROID
+    LOG("getting plugins dir failed");
+#endif
   }
 
   mPluginsLoaded = PR_TRUE; // at this point 'some' plugins have been loaded,
                             // the rest is optional
 
 #ifdef XP_WIN
   PRBool bScanPLIDs = PR_FALSE;
 
--- a/dom/plugins/base/nsPluginInstanceOwner.cpp
+++ b/dom/plugins/base/nsPluginInstanceOwner.cpp
@@ -113,16 +113,26 @@ 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
+#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
+
 using namespace mozilla;
 
 // special class for handeling DOM context menu events because for
 // some reason it starves other mouse events if implemented on the
 // same class
 class nsPluginDOMContextMenuListener : public nsIDOMEventListener
 {
 public:
@@ -1250,17 +1260,22 @@ 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
+  // Flash expects an empty string on android
+  mCachedAttrParamValues[nextAttrParamIndex] = ToNewUTF8String(NS_LITERAL_STRING(""));
+#else
   mCachedAttrParamValues[nextAttrParamIndex] = nsnull;
+#endif
   nextAttrParamIndex++;
 
   // Add PARAM name/value pairs.
   for (PRUint16 i = 0; i < mNumCachedParams; i++) {
     nsIDOMElement* param = ourParams.ObjectAt(i);
     if (!param) {
       continue;
     }
@@ -1635,18 +1650,58 @@ void nsPluginInstanceOwner::ScrollPositi
         mInstance->HandleEvent(&scrollEvent, nsnull);
       }
       pluginWidget->EndDrawPlugin();
     }
   }
 #endif
 }
 
+#ifdef ANDROID
+void nsPluginInstanceOwner::RemovePluginView()
+{
+  if (mInstance && mObjectFrame) {
+    void* surface = mInstance->GetJavaSurface();
+    if (surface) {
+      JNIEnv* env = GetJNIForThread();
+      if (env) {
+        jclass cls = env->FindClass("org/mozilla/gecko/GeckoAppShell");
+        jmethodID method = env->GetStaticMethodID(cls,
+                                                  "removePluginView",
+                                                  "(Landroid/view/View;)V");
+        env->CallStaticVoidMethod(cls, method, surface);
+      }
+    }
+  }
+}
+#endif
+
 nsresult nsPluginInstanceOwner::DispatchFocusToPlugin(nsIDOMEvent* aFocusEvent)
 {
+#ifdef ANDROID
+  {
+    ANPEvent event;
+    event.inSize = sizeof(ANPEvent);
+    event.eventType = kLifecycle_ANPEventType;
+
+    nsAutoString eventType;
+    aFocusEvent->GetType(eventType);
+    if (eventType.EqualsLiteral("focus")) {
+      event.data.lifecycle.action = kGainFocus_ANPLifecycleAction;
+    }
+    else if (eventType.EqualsLiteral("blur")) {
+      event.data.lifecycle.action = kLoseFocus_ANPLifecycleAction;
+    }
+    else {
+      NS_ASSERTION(PR_FALSE, "nsPluginInstanceOwner::DispatchFocusToPlugin, wierd eventType");   
+    }
+    mInstance->HandleEvent(&event, nsnull);
+  }
+#endif
+
 #ifndef XP_MACOSX
   if (!mPluginWindow || (mPluginWindow->type == NPWindowTypeWindow)) {
     // continue only for cases without child window
     return aFocusEvent->PreventDefault(); // consume event
   }
 #endif
 
   nsCOMPtr<nsIPrivateDOMEvent> privateEvent(do_QueryInterface(aFocusEvent));
@@ -1907,18 +1962,16 @@ static unsigned int XInputEventState(con
   if (anEvent.isAlt) state |= Mod1Mask;
   if (anEvent.isMeta) state |= Mod4Mask;
   return state;
 }
 #endif
 
 nsEventStatus nsPluginInstanceOwner::ProcessEvent(const nsGUIEvent& anEvent)
 {
-  // printf("nsGUIEvent.message: %d\n", anEvent.message);
-
   nsEventStatus rv = nsEventStatus_eIgnore;
 
   if (!mInstance || !mObjectFrame)   // if mInstance is null, we shouldn't be here
     return nsEventStatus_eIgnore;
 
 #ifdef XP_MACOSX
   if (!mWidget)
     return nsEventStatus_eIgnore;
@@ -2431,16 +2484,117 @@ nsEventStatus nsPluginInstanceOwner::Pro
   event.send_event = False;
 
   PRInt16 response = kNPEventNotHandled;
   mInstance->HandleEvent(&pluginEvent, &response);
   if (response == kNPEventHandled)
     rv = nsEventStatus_eConsumeNoDefault;
 #endif
 
+#ifdef 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);
+    }
+  }
+  switch(anEvent.eventStructType)
+    {
+    case NS_MOUSE_EVENT:
+      {
+        switch (anEvent.message)
+          {
+          case NS_MOUSE_CLICK:
+          case NS_MOUSE_DOUBLECLICK:
+            // Button up/down events sent instead.
+            return rv;
+          }
+
+        // Get reference point relative to plugin origin.
+        const nsPresContext* presContext = mObjectFrame->PresContext();
+        nsPoint appPoint =
+          nsLayoutUtils::GetEventCoordinatesRelativeTo(&anEvent, mObjectFrame) -
+          mObjectFrame->GetContentRectRelativeToSelf().TopLeft();
+        nsIntPoint pluginPoint(presContext->AppUnitsToDevPixels(appPoint.x),
+                               presContext->AppUnitsToDevPixels(appPoint.y));
+
+        switch (anEvent.message)
+          {
+          case NS_MOUSE_MOVE:
+            {
+              // are these going to be touch events?
+              // pluginPoint.x;
+              // pluginPoint.y;
+            }
+            break;
+          case NS_MOUSE_BUTTON_DOWN:
+            {
+              ANPEvent event;
+              event.inSize = sizeof(ANPEvent);
+              event.eventType = kMouse_ANPEventType;
+              event.data.mouse.action = kDown_ANPMouseAction;
+              event.data.mouse.x = pluginPoint.x;
+              event.data.mouse.y = pluginPoint.y;
+              mInstance->HandleEvent(&event, nsnull);
+            }
+            break;
+          case NS_MOUSE_BUTTON_UP:
+            {
+              ANPEvent event;
+              event.inSize = sizeof(ANPEvent);
+              event.eventType = kMouse_ANPEventType;
+              event.data.mouse.action = kUp_ANPMouseAction;
+              event.data.mouse.x = pluginPoint.x;
+              event.data.mouse.y = pluginPoint.y;
+              mInstance->HandleEvent(&event, nsnull);
+            }
+            break;
+          }
+      }
+      break;
+
+    case NS_KEY_EVENT:
+     {
+       const nsKeyEvent& keyEvent = static_cast<const nsKeyEvent&>(anEvent);
+       LOG("Firing NS_KEY_EVENT %d %d\n", keyEvent.keyCode, keyEvent.charCode);
+       
+       int modifiers = 0;
+       if (keyEvent.isShift)
+         modifiers |= kShift_ANPKeyModifier;
+       if (keyEvent.isAlt)
+         modifiers |= kAlt_ANPKeyModifier;
+
+       ANPEvent event;
+       event.inSize = sizeof(ANPEvent);
+       event.eventType = kKey_ANPEventType;
+       event.data.key.nativeCode = keyEvent.keyCode;
+       event.data.key.virtualCode = keyEvent.charCode;
+       event.data.key.modifiers = modifiers;
+       event.data.key.repeatCount = 0;
+       event.data.key.unichar = 0;
+       switch (anEvent.message)
+         {
+         case NS_KEY_DOWN:
+           event.data.key.action = kDown_ANPKeyAction;
+           mInstance->HandleEvent(&event, nsnull);
+           break;
+           
+         case NS_KEY_UP:
+           event.data.key.action = kUp_ANPKeyAction;
+           mInstance->HandleEvent(&event, nsnull);
+           break;
+         }
+     }
+    }
+    rv = nsEventStatus_eConsumeNoDefault;
+#endif
+ 
   return rv;
 }
 
 nsresult
 nsPluginInstanceOwner::Destroy()
 {
 #ifdef MAC_CARBON_PLUGINS
   // stop the timer explicitly to reduce reference count.
@@ -2536,16 +2690,20 @@ nsPluginInstanceOwner::PrepareToStop(PRB
     // and plugin et al not holding any other references to its
     // parent.
     mWidget->SetParent(nsnull);
 
     mDestroyWidget = PR_TRUE;
   }
 #endif
 
+#ifdef 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);
     }
   }
 }
@@ -2632,16 +2790,148 @@ 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
+
+class AndroidPaintEventRunnable : public nsRunnable
+{
+public:
+  AndroidPaintEventRunnable(void* aSurface, nsNPAPIPluginInstance* inst, const gfxRect& aFrameRect)
+    : mSurface(aSurface), mInstance(inst), mFrameRect(aFrameRect) {
+  }
+
+  ~AndroidPaintEventRunnable() {
+  }
+
+  NS_IMETHOD Run()
+  {
+    LOG("%p - AndroidPaintEventRunnable::Run\n", this);
+
+    if (!mInstance || !mSurface)
+      return NS_OK;
+
+    // This needs to happen on the gecko main thread.
+    JNIEnv* env = GetJNIForThread();
+    jclass cls = env->FindClass("org/mozilla/gecko/GeckoAppShell");
+    jmethodID method = env->GetStaticMethodID(cls,
+                                              "addPluginView",
+                                              "(Landroid/view/View;DDDD)V");
+    env->CallStaticVoidMethod(cls,
+                              method,
+                              mSurface,
+                              mFrameRect.x,
+                              mFrameRect.y,
+                              mFrameRect.width,
+                              mFrameRect.height);
+    return NS_OK;
+  }
+private:
+  void* mSurface;
+  nsCOMPtr<nsNPAPIPluginInstance> mInstance;
+  gfxRect mFrameRect;
+};
+
+
+void nsPluginInstanceOwner::Paint(gfxContext* aContext,
+                                  const gfxRect& aFrameRect,
+                                  const gfxRect& aDirtyRect)
+{
+  if (!mInstance || !mObjectFrame)
+    return;
+
+  PRInt32 model;
+  mInstance->GetDrawingModel(&model);
+
+  if (model == kSurface_ANPDrawingModel) {
+
+    {
+      ANPEvent event;
+      event.inSize = sizeof(ANPEvent);
+      event.eventType = kLifecycle_ANPEventType;
+      event.data.lifecycle.action = kOnScreen_ANPLifecycleAction;
+      mInstance->HandleEvent(&event, nsnull);
+    }
+
+    /*
+    gfxMatrix currentMatrix = aContext->CurrentMatrix();
+    gfxSize scale = currentMatrix.ScaleFactors(PR_TRUE);
+    printf_stderr("!!!!!!!! scale!!:  %f x %f\n", scale.width, scale.height);
+    */
+
+    JNIEnv* env = GetJNIForThread();
+    jclass cls = env->FindClass("org/mozilla/gecko/GeckoAppShell");
+    jmethodID method = env->GetStaticMethodID(cls,
+                                              "addPluginView",
+                                              "(Landroid/view/View;DDDD)V");
+    env->CallStaticVoidMethod(cls,
+                              method,
+                              mInstance->GetJavaSurface(),
+                              aFrameRect.x,
+                              aFrameRect.y,
+                              aFrameRect.width,
+                              aFrameRect.height);
+    return;
+  }
+
+  if (model != kBitmap_ANPDrawingModel)
+    return;
+
+#ifdef ANP_BITMAP_DRAWING_MODEL
+  static nsRefPtr<gfxImageSurface> pluginSurface;
+
+  if (pluginSurface == nsnull ||
+      aFrameRect.width  != pluginSurface->Width() ||
+      aFrameRect.height != pluginSurface->Height()) {
+
+    pluginSurface = new gfxImageSurface(gfxIntSize(aFrameRect.width, aFrameRect.height), 
+                                        gfxImageSurface::ImageFormatARGB32);
+    if (!pluginSurface)
+      return;
+  }
+
+  // Clears buffer.  I think this is needed.
+  nsRefPtr<gfxContext> ctx = new gfxContext(pluginSurface);
+  ctx->SetOperator(gfxContext::OPERATOR_CLEAR);
+  ctx->Paint();
+  
+  ANPEvent event;
+  event.inSize = sizeof(ANPEvent);
+  event.eventType = 4;
+  event.data.draw.model = 1;
+  
+  event.data.draw.clip.top     = 0;
+  event.data.draw.clip.left    = 0;
+  event.data.draw.clip.bottom  = aFrameRect.width;
+  event.data.draw.clip.right   = aFrameRect.height;
+  
+  event.data.draw.data.bitmap.format   = kRGBA_8888_ANPBitmapFormat;
+  event.data.draw.data.bitmap.width    = aFrameRect.width;
+  event.data.draw.data.bitmap.height   = aFrameRect.height;
+  event.data.draw.data.bitmap.baseAddr = pluginSurface->Data();
+  event.data.draw.data.bitmap.rowBytes = aFrameRect.width * 4;
+  
+  if (!mInstance)
+    return;
+    
+  mInstance->HandleEvent(&event, nsnull);
+
+  aContext->SetOperator(gfxContext::OPERATOR_SOURCE);
+  aContext->SetSource(pluginSurface, gfxPoint(aFrameRect.x, aFrameRect.y));
+  aContext->Clip(aFrameRect);
+  aContext->Paint();
+#endif
+}
+#endif
+
 #if defined(MOZ_X11)
 void nsPluginInstanceOwner::Paint(gfxContext* aContext,
                                   const gfxRect& aFrameRect,
                                   const gfxRect& aDirtyRect)
 {
   if (!mInstance || !mObjectFrame)
     return;
 
@@ -3269,19 +3559,38 @@ 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
+    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
+    if (mInstance) {
+      ANPEvent event;
+      event.inSize = sizeof(ANPEvent);
+      event.eventType = kLifecycle_ANPEventType;
+      event.data.lifecycle.action = kOffScreen_ANPLifecycleAction;
+      mInstance->HandleEvent(&event, nsnull);
+    }
+    RemovePluginView();
+#endif
   }
 
   if (!aSetWindow)
     return;
 
   if (mPluginWindow->x               != oldWindow.x               ||
       mPluginWindow->y               != oldWindow.y               ||
       mPluginWindow->clipRect.left   != oldWindow.clipRect.left   ||
--- a/dom/plugins/base/nsPluginInstanceOwner.h
+++ b/dom/plugins/base/nsPluginInstanceOwner.h
@@ -139,17 +139,17 @@ public:
   void PrepareToStop(PRBool aDelayedStop);
   
 #ifdef XP_WIN
   void Paint(const RECT& aDirty, HDC aDC);
 #elif defined(XP_MACOSX)
   void Paint(const gfxRect& aDirtyRect, CGContextRef cgContext);  
   void RenderCoreAnimation(CGContextRef aCGContext, int aWidth, int aHeight);
   void DoCocoaEventDrawRect(const gfxRect& aDrawRect, CGContextRef cgContext);
-#elif defined(MOZ_X11)
+#elif defined(MOZ_X11) || defined(ANDROID)
   void Paint(gfxContext* aContext,
              const gfxRect& aFrameRect,
              const gfxRect& aDirtyRect);
 #elif defined(XP_OS2)
   void Paint(const nsRect& aDirtyRect, HPS aHPS);
 #endif
   
 #ifdef MAC_CARBON_PLUGINS
@@ -303,17 +303,20 @@ private:
   PRBool IsUpToDate()
   {
     nsIntSize size;
     return NS_SUCCEEDED(mInstance->GetImageSize(&size)) &&
     size == nsIntSize(mPluginWindow->width, mPluginWindow->height);
   }
   
   void FixUpURLS(const nsString &name, nsAString &value);
-  
+#ifdef ANDROID
+  void RemovePluginView();
+#endif 
+ 
   nsPluginNativeWindow       *mPluginWindow;
   nsRefPtr<nsNPAPIPluginInstance> mInstance;
   nsObjectFrame              *mObjectFrame; // owns nsPluginInstanceOwner
   nsCOMPtr<nsIContent>        mContent;
   nsCString                   mDocumentBase;
   char                       *mTagText;
   nsCOMPtr<nsIWidget>         mWidget;
   nsRefPtr<nsPluginHost>      mPluginHost;
--- a/dom/plugins/base/nsPluginNativeWindowWin.cpp
+++ b/dom/plugins/base/nsPluginNativeWindowWin.cpp
@@ -179,18 +179,17 @@ static PRBool ProcessFlashMessageDelayed
                                          HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
 {
   NS_ENSURE_TRUE(aWin, NS_ERROR_NULL_POINTER);
   NS_ENSURE_TRUE(aInst, NS_ERROR_NULL_POINTER);
 
   if (msg == sWM_FLASHBOUNCEMSG) {
     // See PluginWindowEvent::Run() below.
     NS_ASSERTION((sWM_FLASHBOUNCEMSG != 0), "RegisterWindowMessage failed in flash plugin WM_USER message handling!");
-    NS_TRY_SAFE_CALL_VOID(::CallWindowProc((WNDPROC)aWin->GetWindowProc(), hWnd, WM_USER_FLASH, wParam, lParam),
-                                           aInst);
+    ::CallWindowProc((WNDPROC)aWin->GetWindowProc(), hWnd, WM_USER_FLASH, wParam, lParam);
     return TRUE;
   }
 
   if (msg != WM_USER_FLASH)
     return PR_FALSE; // no need to delay
 
   // do stuff
   nsCOMPtr<nsIRunnable> pwe = aWin->GetPluginWindowEvent(hWnd, msg, wParam, lParam);
@@ -572,22 +571,21 @@ NS_IMETHODIMP PluginWindowEvent::Run()
   if (GetMsg() == WM_USER_FLASH) {
     // XXX Unwind issues related to runnable event callback depth for this
     // event and destruction of the plugin. (Bug 493601)
     ::PostMessage(hWnd, sWM_FLASHBOUNCEMSG, GetWParam(), GetLParam());
   }
   else {
     // Currently not used, but added so that processing events here
     // is more generic.
-    NS_TRY_SAFE_CALL_VOID(::CallWindowProc(win->GetWindowProc(), 
-                          hWnd, 
-                          GetMsg(), 
-                          GetWParam(), 
-                          GetLParam()),
-                          inst);
+    ::CallWindowProc(win->GetWindowProc(), 
+                     hWnd, 
+                     GetMsg(), 
+                     GetWParam(), 
+                     GetLParam());
   }
 
   Clear();
   return NS_OK;
 }
 
 PluginWindowEvent * 
 nsPluginNativeWindowWin::GetPluginWindowEvent(HWND aWnd, UINT aMsg, WPARAM aWParam, LPARAM aLParam)
--- a/dom/plugins/base/nsPluginsDirUnix.cpp
+++ b/dom/plugins/base/nsPluginsDirUnix.cpp
@@ -242,16 +242,26 @@ static void LoadExtraSharedLibs()
 /* nsPluginsDir implementation */
 
 PRBool nsPluginsDir::IsPluginFile(nsIFile* file)
 {
     nsCAutoString filename;
     if (NS_FAILED(file->GetNativeLeafName(filename)))
         return PR_FALSE;
 
+#ifdef ANDROID
+    // It appears that if you load
+    // 'libstagefright_honeycomb.so' on froyo, or
+    // 'libstagefright_froyo.so' on honeycomb, we will abort.
+    // Since these are just helper libs, we can ignore.
+    const char *cFile = filename.get();
+    if (strstr(cFile, "libstagefright") != NULL)
+        return PR_FALSE;
+#endif
+
     NS_NAMED_LITERAL_CSTRING(dllSuffix, LOCAL_PLUGIN_DLL_SUFFIX);
     if (filename.Length() > dllSuffix.Length() &&
         StringEndsWith(filename, dllSuffix))
         return PR_TRUE;
     
 #ifdef LOCAL_PLUGIN_DLL_ALT_SUFFIX
     NS_NAMED_LITERAL_CSTRING(dllAltSuffix, LOCAL_PLUGIN_DLL_ALT_SUFFIX);
     if (filename.Length() > dllAltSuffix.Length() &&
--- a/dom/plugins/ipc/PluginInstanceChild.cpp
+++ b/dom/plugins/ipc/PluginInstanceChild.cpp
@@ -207,17 +207,17 @@ PluginInstanceChild::GetQuirks()
 {
     return PluginModuleChild::current()->GetQuirks();
 }
 
 NPError
 PluginInstanceChild::InternalGetNPObjectForValue(NPNVariable aValue,
                                                  NPObject** aObject)
 {
-    PluginScriptableObjectChild* actor;
+    PluginScriptableObjectChild* actor = NULL;
     NPError result = NPERR_NO_ERROR;
 
     switch (aValue) {
         case NPNVWindowNPObject:
             if (!(actor = mCachedWindowActor)) {
                 PPluginScriptableObjectChild* actorProtocol;
                 CallNPN_GetValue_NPNVWindowNPObject(&actorProtocol, &result);
                 if (result == NPERR_NO_ERROR) {
--- a/dom/plugins/ipc/PluginModuleChild.cpp
+++ b/dom/plugins/ipc/PluginModuleChild.cpp
@@ -194,34 +194,32 @@ PluginModuleChild::Init(const std::strin
                     getter_AddRefs(localFile));
 
     PRBool exists;
     localFile->Exists(&exists);
     NS_ASSERTION(exists, "plugin file ain't there");
 
     nsPluginFile pluginFile(localFile);
 
-    nsresult rv;
     // Maemo flash can render with any provided rectangle and so does not
     // require this quirk.
 #if defined(MOZ_X11) && !defined(MOZ_PLATFORM_MAEMO)
     nsPluginInfo info = nsPluginInfo();
-    rv = pluginFile.GetPluginInfo(info, &mLibrary);
-    if (NS_FAILED(rv))
+    if (NS_FAILED(pluginFile.GetPluginInfo(info, &mLibrary)))
         return false;
 
     NS_NAMED_LITERAL_CSTRING(flash10Head, "Shockwave Flash 10.");
     if (StringBeginsWith(nsDependentCString(info.fDescription), flash10Head)) {
         AddQuirk(QUIRK_FLASH_EXPOSE_COORD_TRANSLATION);
     }
 
     if (!mLibrary)
 #endif
     {
-        rv = pluginFile.LoadPlugin(&mLibrary);
+        DebugOnly<nsresult> rv = pluginFile.LoadPlugin(&mLibrary);
         NS_ASSERTION(NS_OK == rv, "trouble with mPluginFile");
     }
     NS_ASSERTION(mLibrary, "couldn't open shared object");
 
     if (!Open(aChannel, aParentProcessHandle, aIOLoop))
         return false;
 
     memset((void*) &mFunctions, 0, sizeof(mFunctions));
@@ -254,18 +252,17 @@ PluginModuleChild::Init(const std::strin
 #else
 
 #  error Please copy the initialization code from nsNPAPIPlugin.cpp
 
 #endif
 
 #ifdef XP_MACOSX
     nsPluginInfo info = nsPluginInfo();
-    rv = pluginFile.GetPluginInfo(info, &mLibrary);
-    if (rv == NS_OK) {
+    if (pluginFile.GetPluginInfo(info, &mLibrary) == NS_OK) {
         mozilla::plugins::PluginUtilsOSX::SetProcessName(info.fName);
     }
 #endif
 
     return true;
 }
 
 #if defined(MOZ_WIDGET_GTK2)
@@ -683,22 +680,21 @@ PluginModuleChild::AnswerNPP_GetSitesWit
     return true;
 }
 
 bool
 PluginModuleChild::RecvSetAudioSessionData(const nsID& aId,
                                            const nsString& aDisplayName,
                                            const nsString& aIconPath)
 {
-    nsresult rv;
 #if !defined XP_WIN || MOZ_WINSDK_TARGETVER < MOZ_NTDDI_LONGHORN
     NS_RUNTIMEABORT("Not Reached!");
     return false;
 #else
-    rv = mozilla::widget::RecvAudioSessionData(aId, aDisplayName, aIconPath);
+    nsresult rv = mozilla::widget::RecvAudioSessionData(aId, aDisplayName, aIconPath);
     NS_ENSURE_SUCCESS(rv, true); // Bail early if this fails
 
     // Ignore failures here; we can't really do anything about them
     mozilla::widget::StartAudioSession();
     return true;
 #endif
 }
 
@@ -2075,17 +2071,20 @@ PluginModuleChild::NPN_CreateObject(NPP 
     return newObject;
 }
 
 NPObject* NP_CALLBACK
 PluginModuleChild::NPN_RetainObject(NPObject* aNPObj)
 {
     AssertPluginThread();
 
-    int32_t refCnt = PR_ATOMIC_INCREMENT((int32_t*)&aNPObj->referenceCount);
+#ifdef NS_BUILD_REFCNT_LOGGING
+    int32_t refCnt =
+#endif
+    PR_ATOMIC_INCREMENT((int32_t*)&aNPObj->referenceCount);
     NS_LOG_ADDREF(aNPObj, refCnt, "NPObject", sizeof(NPObject));
 
     return aNPObj;
 }
 
 void NP_CALLBACK
 PluginModuleChild::NPN_ReleaseObject(NPObject* aNPObj)
 {
--- a/dom/plugins/ipc/PluginModuleParent.cpp
+++ b/dom/plugins/ipc/PluginModuleParent.cpp
@@ -769,18 +769,16 @@ PluginModuleParent::EndUpdateBackground(
 }
 
 #if defined(XP_UNIX) && !defined(XP_MACOSX)
 nsresult
 PluginModuleParent::NP_Initialize(NPNetscapeFuncs* bFuncs, NPPluginFuncs* pFuncs, NPError* error)
 {
     PLUGIN_LOG_DEBUG_METHOD;
 
-    nsresult rv;
-
     mNPNIface = bFuncs;
 
     if (mShutdown) {
         *error = NPERR_GENERIC_ERROR;
         return NS_ERROR_FAILURE;
     }
 
     if (!CallNP_Initialize(&mPluginThread, error)) {
--- a/dom/plugins/ipc/PluginScriptableObjectParent.cpp
+++ b/dom/plugins/ipc/PluginScriptableObjectParent.cpp
@@ -36,16 +36,17 @@
  *
  * ***** END LICENSE BLOCK ***** */
 
 #include "PluginScriptableObjectParent.h"
 #include "PluginScriptableObjectUtils.h"
 
 #include "nsNPAPIPlugin.h"
 #include "mozilla/unused.h"
+#include "mozilla/Util.h"
 
 using namespace mozilla::plugins;
 using namespace mozilla::plugins::parent;
 
 namespace {
 
 typedef PluginIdentifierParent::StackIdentifier StackIdentifier;
 
@@ -1078,17 +1079,17 @@ PluginScriptableObjectParent::AnswerEnum
   JSAutoRequest ar(cx);
 
   for (uint32_t index = 0; index < idCount; index++) {
     // Because of GC hazards, all identifiers returned from enumerate
     // must be made permanent.
     if (_identifierisstring(ids[index])) {
       JSString* str = NPIdentifierToString(ids[index]);
       if (!JS_StringHasBeenInterned(cx, str)) {
-        JSString* str2 = JS_InternJSString(cx, str);
+        DebugOnly<JSString*> str2 = JS_InternJSString(cx, str);
         NS_ASSERTION(str2 == str, "Interning a JS string which is currently an ID should return itself.");
       }
     }
     PluginIdentifierParent* id =
       instance->Module()->GetIdentifierForNPIdentifier(instance->GetNPP(), ids[index]);
     aProperties->AppendElement(id);
     NS_ASSERTION(!id->IsTemporary(), "Should only have permanent identifiers!");
   }
--- a/dom/src/jsurl/nsJSProtocolHandler.cpp
+++ b/dom/src/jsurl/nsJSProtocolHandler.cpp
@@ -262,17 +262,17 @@ nsresult nsJSThunk::EvaluateScript(nsICh
     PRBool useSandbox =
         (aExecutionPolicy == nsIScriptChannel::EXECUTE_IN_SANDBOX);
 
     if (!useSandbox) {
         //-- Don't outside a sandbox unless the script principal subsumes the
         //   principal of the context.
         nsCOMPtr<nsIPrincipal> objectPrincipal;
         rv = securityManager->
-            GetObjectPrincipal((JSContext*)scriptContext->GetNativeContext(),
+            GetObjectPrincipal(scriptContext->GetNativeContext(),
                                globalJSObject,
                                getter_AddRefs(objectPrincipal));
         if (NS_FAILED(rv))
             return rv;
 
         PRBool subsumes;
         rv = principal->Subsumes(objectPrincipal, &subsumes);
         if (NS_FAILED(rv))
@@ -289,17 +289,17 @@ nsresult nsJSThunk::EvaluateScript(nsICh
     if (useSandbox) {
         // We were asked to use a sandbox, or the channel owner isn't allowed
         // to execute in this context.  Evaluate the javascript URL in a
         // sandbox to prevent it from accessing data it doesn't have
         // permissions to access.
 
         // First check to make sure it's OK to evaluate this script to
         // start with.  For example, script could be disabled.
-        JSContext *cx = (JSContext*)scriptContext->GetNativeContext();
+        JSContext *cx = scriptContext->GetNativeContext();
         JSAutoRequest ar(cx);
 
         PRBool ok;
         rv = securityManager->CanExecuteScripts(cx, principal, &ok);
         if (NS_FAILED(rv)) {
             return rv;
         }
 
@@ -368,17 +368,17 @@ nsresult nsJSThunk::EvaluateScript(nsICh
 
         // If there's an error on cx as a result of that call, report
         // it now -- either we're just running under the event loop,
         // so we shouldn't propagate JS exceptions out of here, or we
         // can't be sure that our caller is JS (and if it's not we'll
         // lose the error), or it might be JS that then proceeds to
         // cause an error of its own (which will also make us lose
         // this error).
-        JSContext *cx = (JSContext*)scriptContext->GetNativeContext();
+        JSContext *cx = scriptContext->GetNativeContext();
         JSAutoRequest ar(cx);
         ::JS_ReportPendingException(cx);
     }
     
     if (NS_FAILED(rv)) {
         rv = NS_ERROR_MALFORMED_URI;
     }
     else if (isUndefined) {
--- a/dom/tests/mochitest/dom-level2-core/test_createDocument03.html
+++ b/dom/tests/mochitest/dom-level2-core/test_createDocument03.html
@@ -72,16 +72,18 @@ var docName = 'createDocument03';
 
 
 /**
 * 
     The "createDocument(namespaceURI,qualifiedName,doctype)" method for a 
    DOMImplementation should raise WRONG_DOCUMENT_ERR DOMException
    if parameter doctype has been used with a different document.
    
+   The specification has changed! No exception should be thrown.
+   
    Invoke method createDocument(namespaceURI,qualifiedName,doctype) on
    this domimplementation where doctype is the type of this document.
    Method should raise WRONG_DOCUMENT_ERR DOMException.
 
 * @author NIST
 * @author Mary Brady
 * @see http://www.w3.org/TR/DOM-Level-2-Core/core#xpointer(id('ID-258A00AF')/constant[@name='WRONG_DOCUMENT_ERR'])
 * @see http://www.w3.org/TR/DOM-Level-2-Core/core#Level-2-Core-DOM-createDocument
@@ -105,21 +107,22 @@ function createDocument03() {
       docType = doc.doctype;
 
       domImpl = doc.implementation;
 
 	{
 		success = false;
 		try {
             aNewDoc = domImpl.createDocument(namespaceURI,qualifiedName,docType);
+            success = true;
         }
 		catch(ex) {
-      success = (typeof(ex.code) != 'undefined' && ex.code == 4);
+      success = false;
 		}
-		assertTrue("throw_WRONG_DOCUMENT_ERR",success);
+		//assertTrue("no_throw_WRONG_DOCUMENT_ERR",success);
 	}
 
 }
 
 </script>
 </head>
 <body>
 <h2>Test http://www.w3.org/2001/DOM-Test-Suite/level2/core/createDocument03</h2>
--- a/dom/tests/mochitest/dom-level2-core/test_createDocument04.html
+++ b/dom/tests/mochitest/dom-level2-core/test_createDocument04.html
@@ -78,16 +78,18 @@ var docName = 'createDocument04';
 
 
 /**
 * 
     The "createDocument(namespaceURI,qualifiedName,doctype)" method for a 
    DOMImplementation should raise WRONG_DOCUMENT_ERR DOMException
    if parameter doctype was created from a different implementation.
    
+   The specification has changed! No exception should be thrown.
+   
    Invoke method createDocument(namespaceURI,qualifiedName,doctype) on
    a domimplementation that is different from this domimplementation.
    Doctype is the type of this document.
    Method should raise WRONG_DOCUMENT_ERR DOMException.
 
 * @author NIST
 * @author Mary Brady
 * @see http://www.w3.org/TR/DOM-Level-2-Core/core#xpointer(id('ID-258A00AF')/constant[@name='WRONG_DOCUMENT_ERR'])
@@ -118,21 +120,22 @@ function createDocument04() {
       docType = doc.doctype;
 
       domImpl = aNewDoc.implementation;
 
 	{
 		success = false;
 		try {
             aNewDoc = domImpl.createDocument(namespaceURI,qualifiedName,docType);
+            success = true;
         }
 		catch(ex) {
-      success = (typeof(ex.code) != 'undefined' && ex.code == 4);
+      success = false;
 		}
-		assertTrue("throw_WRONG_DOCUMENT_ERR",success);
+		assertTrue("no_throw_WRONG_DOCUMENT_ERR",success);
 	}
 
 }
 
 </script>
 </head>
 <body>
 <h2>Test http://www.w3.org/2001/DOM-Test-Suite/level2/core/createDocument04</h2>
--- a/dom/tests/mochitest/dom-level2-core/test_documentimportnode07.html
+++ b/dom/tests/mochitest/dom-level2-core/test_documentimportnode07.html
@@ -77,16 +77,18 @@ var docName = 'documentimportnode07';
 	The importNode method imports a node from another document to this document. 
 	A NOT_SUPPORTED_ERR is raised if the type of node being imported is
 	not supported
 	
 	Using the method importNode with deep=true, try to import this Document's 
 	DocumentType object. Since DocumentType nodes cannot be imported, a 
 	NOT_SUPPORTED_ERR should be raised.
 
+	The specification has changed! No exception should be thrown.
+
 * @author IBM
 * @author Neil Delima
 * @see http://www.w3.org/TR/DOM-Level-2-Core/core
 * @see http://www.w3.org/TR/DOM-Level-2-Core/core#Core-Document-importNode
 */
 function documentimportnode07() {
    var success;
     if(checkInitialization(builder, "documentimportnode07") != null) return;
@@ -101,21 +103,22 @@ function documentimportnode07() {
       doc = load(docRef, "doc", "staffNS");
       docType = doc.doctype;
 
       
 	{
 		success = false;
 		try {
             imported = doc.importNode(docType,true);
+            success = true;
         }
 		catch(ex) {
-      success = (typeof(ex.code) != 'undefined' && ex.code == 9);
+      success = false;
 		}
-		assertTrue("throw_NOT_SUPPORTED_ERR",success);
+		assertTrue("no_throw_NOT_SUPPORTED_ERR",success);
 	}
 
 }
 
 </script>
 </head>
 <body>
 <h2>Test http://www.w3.org/2001/DOM-Test-Suite/level2/core/documentimportnode07</h2>
--- a/dom/tests/mochitest/dom-level2-core/test_documentimportnode08.html
+++ b/dom/tests/mochitest/dom-level2-core/test_documentimportnode08.html
@@ -76,16 +76,18 @@ var docName = 'documentimportnode08';
 * 
 	The importNode method imports a node from another document to this document. 
 	A NOT_SUPPORTED_ERR is raised if the type of node being imported is
 	not supported
 	
 	Using the method importNode with deep=true, try to import a newly created DOcumentType
 	node. Since DocumentType nodes cannot be imported, a NOT_SUPPORTED_ERR should be raised.
 
+	The specification has changed! No exception should be thrown.
+
 * @author IBM
 * @author Neil Delima
 * @see http://www.w3.org/TR/DOM-Level-2-Core/core
 * @see http://www.w3.org/TR/DOM-Level-2-Core/core#Core-Document-importNode
 * @see http://www.w3.org/Bugs/Public/show_bug.cgi?id=259
 */
 function documentimportnode08() {
    var success;
@@ -104,21 +106,22 @@ function documentimportnode08() {
       doc = load(docRef, "doc", "staffNS");
       domImpl = doc.implementation;
 docType = domImpl.createDocumentType("test:root",nullNS,nullNS);
       
 	{
 		success = false;
 		try {
             imported = doc.importNode(docType,true);
+            success = true;
         }
 		catch(ex) {
-      success = (typeof(ex.code) != 'undefined' && ex.code == 9);
+      success = false;
 		}
-		assertTrue("throw_NOT_SUPPORTED_ERR",success);
+		assertTrue("no_throw_NOT_SUPPORTED_ERR",success);
 	}
 
 }
 
 </script>
 </head>
 <body>
 <h2>Test http://www.w3.org/2001/DOM-Test-Suite/level2/core/documentimportnode08</h2>
--- a/dom/tests/mochitest/dom-level2-core/test_domimplementationcreatedocumenttype01.html
+++ b/dom/tests/mochitest/dom-level2-core/test_domimplementationcreatedocumenttype01.html
@@ -75,16 +75,18 @@ var docName = 'domimplementationcreatedo
 * 
 	The method createDocumentType with valid values for qualifiedName, publicId and
 	systemId should create an empty DocumentType node.
 	
 	Invoke createDocument on this DOMImplementation with a valid qualifiedName and different
 	publicIds and systemIds.  Check if the the DocumentType node was created with its 
 	ownerDocument attribute set to null.
 
+	The specification has changed! ownerDocument should not be null.
+
 * @author IBM
 * @author Neil Delima
 * @see http://www.w3.org/TR/DOM-Level-2-Core/core#Level-2-Core-DOM-createDocument
 */
 function domimplementationcreatedocumenttype01() {
    var success;
     if(checkInitialization(builder, "domimplementationcreatedocumenttype01") != null) return;
     var doc;
@@ -112,17 +114,17 @@ function domimplementationcreatedocument
 for(var indexN65629 = 0;indexN65629 < publicIds.length; indexN65629++) {
       publicId = publicIds[indexN65629];
       for(var indexN65633 = 0;indexN65633 < systemIds.length; indexN65633++) {
       systemId = systemIds[indexN65633];
       newDocType = domImpl.createDocumentType(qualifiedName,publicId,systemId);
       assertNotNull("domimplementationcreatedocumenttype01_newDocType",newDocType);
 ownerDocument = newDocType.ownerDocument;
 
-      assertNull("domimplementationcreatedocumenttype01_ownerDocument",ownerDocument);
+      assertNotNull("domimplementationcreatedocumenttype01_ownerDocument",ownerDocument);
     
 	}
    
 	}
    
 }
 
 </script>
--- a/dom/tests/mochitest/dom-level2-core/test_domimplementationcreatedocumenttype02.html
+++ b/dom/tests/mochitest/dom-level2-core/test_domimplementationcreatedocumenttype02.html
@@ -75,16 +75,18 @@ var docName = 'domimplementationcreatedo
 * 
 	The method createDocumentType with valid values for qualifiedName, publicId and
 	systemId should create an empty DocumentType node.
 	
 	Invoke createDocument on this DOMImplementation with a different valid qualifiedNames 
 	and a valid publicId and systemId.  Check if the the DocumentType node was created 
 	with its ownerDocument attribute set to null.
 
+	The specification has changed! ownerDocument should not be null.
+
 * @author IBM
 * @author Neil Delima
 * @see http://www.w3.org/TR/DOM-Level-2-Core/core#Level-2-Core-DOM-createDocType
 */
 function domimplementationcreatedocumenttype02() {
    var success;
     if(checkInitialization(builder, "domimplementationcreatedocumenttype02") != null) return;
     var doc;
@@ -118,17 +120,17 @@ function domimplementationcreatedocument
       doc = load(docRef, "doc", "staffNS");
       domImpl = doc.implementation;
 for(var indexN65655 = 0;indexN65655 < qualifiedNames.length; indexN65655++) {
       qualifiedName = qualifiedNames[indexN65655];
       newDocType = domImpl.createDocumentType(qualifiedName,publicId,systemId);
       assertNotNull("domimplementationcreatedocumenttype02_newDocType",newDocType);
 ownerDocument = newDocType.ownerDocument;
 
-      assertNull("domimplementationcreatedocumenttype02_ownerDocument",ownerDocument);
+      assertNotNull("domimplementationcreatedocumenttype02_ownerDocument",ownerDocument);
     
 	}
    
 }
 
 </script>
 </head>
 <body>
--- a/dom/tests/mochitest/dom-level2-core/test_importNode16.html
+++ b/dom/tests/mochitest/dom-level2-core/test_importNode16.html
@@ -77,16 +77,18 @@ function loadComplete() {
 var docName = 'importNode16';
 
 
 /**
 * 
     The "importNode(importedNode,deep)" method for a 
    Document should raise NOT_SUPPORTED_ERR DOMException if
    the type of node being imported is DocumentType.
+
+   The specification has changed! No exception should be thrown.
    
    Retrieve document staff.xml and get its type.
    Invoke method importNode(importedNode,deep) where importedNode
    contains the document type of the staff.xml.  
    Method should raise NOT_SUPPORT_ERR DOMException.
 
 * @author NIST
 * @author Mary Brady
@@ -115,21 +117,22 @@ function importNode16() {
       anotherDoc = load(anotherDocRef, "anotherDoc", "staffNS");
       docType = anotherDoc.doctype;
 
       
 	{
 		success = false;
 		try {
             node = doc.importNode(docType,false);
+            success = true;
         }
 		catch(ex) {
-      success = (typeof(ex.code) != 'undefined' && ex.code == 9);
+      success = false;
 		}
-		assertTrue("throw_NOT_SUPPORTED_ERR",success);
+		assertTrue("no_throw_NOT_SUPPORTED_ERR",success);
 	}
 
 }
 
 </script>
 </head>
 <body>
 <h2>Test http://www.w3.org/2001/DOM-Test-Suite/level2/core/importNode16</h2>
--- a/dom/tests/mochitest/dom-level2-core/test_nodegetownerdocument01.html
+++ b/dom/tests/mochitest/dom-level2-core/test_nodegetownerdocument01.html
@@ -74,16 +74,18 @@ var docName = 'nodegetownerdocument01';
 
 /**
 * 
 	The method getOwnerDocument returns the Document object associated with this node
   
 	Create a new DocumentType node.  Since this node is not used with any Document yet
 	verify if the ownerDocument is null.
 
+	The specification has changed! ownerDocument should not be null.
+
 * @author IBM
 * @author Neil Delima
 * @see http://www.w3.org/TR/DOM-Level-2-Core/core#node-ownerDoc
 * @see http://www.w3.org/Bugs/Public/show_bug.cgi?id=259
 */
 function nodegetownerdocument01() {
    var success;
     if(checkInitialization(builder, "nodegetownerdocument01") != null) return;
@@ -98,17 +100,17 @@ function nodegetownerdocument01() {
       if (typeof(this.doc) != 'undefined') {
         docRef = this.doc;
       }
       doc = load(docRef, "doc", "staff");
       domImpl = doc.implementation;
 docType = domImpl.createDocumentType("mydoc",nullID,nullID);
       ownerDoc = docType.ownerDocument;
 
-      assertNull("nodegetownerdocument01",ownerDoc);
+      assertNotNull("nodegetownerdocument01",ownerDoc);
     
 }
 
 </script>
 </head>
 <body>
 <h2>Test http://www.w3.org/2001/DOM-Test-Suite/level2/core/nodegetownerdocument01</h2>
 <p></p>
--- a/dom/workers/WorkerPrivate.cpp
+++ b/dom/workers/WorkerPrivate.cpp
@@ -2171,18 +2171,17 @@ WorkerPrivateParent<Derived>::ParentJSCo
   if (!mParent) {
     AssertIsOnMainThread();
 
     if (!mScriptContext) {
       NS_ASSERTION(!mParentJSContext, "Shouldn't have a parent context!");
       return RuntimeService::AutoSafeJSContext::GetSafeContext();
     }
 
-    NS_ASSERTION(mParentJSContext ==
-                 static_cast<JSContext*>(mScriptContext->GetNativeContext()),
+    NS_ASSERTION(mParentJSContext == mScriptContext->GetNativeContext(),
                  "Native context has changed!");
   }
 
   return mParentJSContext;
 }
 
 WorkerPrivate::WorkerPrivate(JSContext* aCx, JSObject* aObject,
                              WorkerPrivate* aParent,
@@ -2284,18 +2283,17 @@ WorkerPrivate::Create(JSContext* aCx, JS
       }
 
       scriptContext = scriptGlobal->GetContext();
       if (!scriptContext) {
         JS_ReportError(aCx, "Couldn't get script context for this worker!");
         return nsnull;
       }
 
-      parentContext =
-        static_cast<JSContext*>(scriptContext->GetNativeContext());
+      parentContext = scriptContext->GetNativeContext();
 
       // If we're called from a window then we can dig out the principal and URI
       // from the document.
       document = do_QueryInterface(window->GetExtantDocument());
       if (!document) {
         JS_ReportError(aCx, "No document in this window!");
         return nsnull;
       }
--- a/embedding/android/AndroidManifest.xml.in
+++ b/embedding/android/AndroidManifest.xml.in
@@ -14,16 +14,23 @@
 
     <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
     <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
     <uses-permission android:name="android.permission.INTERNET"/>
     <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
     <uses-permission android:name="android.permission.READ_PHONE_STATE"/>
     <uses-permission android:name="com.android.launcher.permission.INSTALL_SHORTCUT"/>
 
+    <uses-permission android:name="android.permission.READ_LOGS"/>
+    <uses-permission android:name="android.permission.WAKE_LOCK"/>
+    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
+    <uses-permission android:name="android.permission.CHANGE_NETWORK_STATE"/> 
+    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
+    <uses-permission android:name="android.permission.CHANGE_NETWORK_STATE"/>
+
     <uses-feature android:name="android.hardware.location" android:required="false"/>
     <uses-feature android:name="android.hardware.location.gps" android:required="false"/>
     <uses-feature android:name="android.hardware.touchscreen"/>
 
     <application android:label="@MOZ_APP_DISPLAYNAME@"
 		 android:icon="@drawable/icon"
 #if MOZILLA_OFFICIAL
 		 android:debuggable="false">
--- a/embedding/android/GeckoApp.java
+++ b/embedding/android/GeckoApp.java
@@ -40,16 +40,17 @@
 package org.mozilla.gecko;
 
 import java.io.*;
 import java.util.*;
 import java.util.zip.*;
 import java.nio.*;
 import java.nio.channels.FileChannel;
 import java.util.concurrent.*;
+import java.lang.reflect.*;
 
 import android.os.*;
 import android.app.*;
 import android.text.*;
 import android.view.*;
 import android.view.inputmethod.*;
 import android.content.*;
 import android.content.res.*;
@@ -57,29 +58,32 @@ import android.graphics.*;
 import android.widget.*;
 import android.hardware.*;
 
 import android.util.*;
 import android.net.*;
 import android.database.*;
 import android.provider.*;
 import android.telephony.*;
+import android.content.pm.*;
+import android.content.pm.PackageManager.*;
+import dalvik.system.*;
 
 abstract public class GeckoApp
     extends Activity
 {
     private static final String LOG_FILE_NAME     = "GeckoApp";
 
     public static final String ACTION_ALERT_CLICK = "org.mozilla.gecko.ACTION_ALERT_CLICK";
     public static final String ACTION_ALERT_CLEAR = "org.mozilla.gecko.ACTION_ALERT_CLEAR";
     public static final String ACTION_WEBAPP      = "org.mozilla.gecko.WEBAPP";
     public static final String ACTION_DEBUG       = "org.mozilla.gecko.DEBUG";
     public static final String ACTION_BOOKMARK    = "org.mozilla.gecko.BOOKMARK";
 
-    public static FrameLayout mainLayout;
+    public static AbsoluteLayout mainLayout;
     public static GeckoSurfaceView surfaceView;
     public static GeckoApp mAppContext;
     public static boolean mFullscreen = false;
     public static File sGREDir = null;
     static Thread mLibLoadThread = null;
     public Handler mMainHandler;
     private IntentFilter mConnectivityFilter;
     private BroadcastReceiver mConnectivityReceiver;
@@ -125,16 +129,161 @@ abstract public class GeckoApp
                                                        int id)
                                    {
                                        GeckoApp.this.finish();
                                        System.exit(0);
                                    }
                                }).show();
     }
 
+    public static final String PLUGIN_ACTION = "android.webkit.PLUGIN";
+
+    /**
+     * A plugin that wish to be loaded in the WebView must provide this permission
+     * in their AndroidManifest.xml.
+     */
+    public static final String PLUGIN_PERMISSION = "android.webkit.permission.PLUGIN";
+
+    private static final String LOGTAG = "PluginManager";
+
+    private static final String PLUGIN_SYSTEM_LIB = "/system/lib/plugins/";
+
+    private static final String PLUGIN_TYPE = "type";
+    private static final String TYPE_NATIVE = "native";
+    public ArrayList<PackageInfo> mPackageInfoCache = new ArrayList<PackageInfo>();
+
+    String[] getPluginDirectories() {
+
+        ArrayList<String> directories = new ArrayList<String>();
+        PackageManager pm = this.mAppContext.getPackageManager();
+        List<ResolveInfo> plugins = pm.queryIntentServices(new Intent(PLUGIN_ACTION),
+                PackageManager.GET_SERVICES | PackageManager.GET_META_DATA);
+
+        synchronized(mPackageInfoCache) {
+
+            // clear the list of existing packageInfo objects
+            mPackageInfoCache.clear();
+
+
+            for (ResolveInfo info : plugins) {
+
+                // retrieve the plugin's service information
+                ServiceInfo serviceInfo = info.serviceInfo;
+                if (serviceInfo == null) {
+                    Log.w(LOGTAG, "Ignore bad plugin");
+                    continue;
+                }
+
+                Log.w(LOGTAG, "Loading plugin: " + serviceInfo.packageName);
+
+
+                // retrieve information from the plugin's manifest
+                PackageInfo pkgInfo;
+                try {
+                    pkgInfo = pm.getPackageInfo(serviceInfo.packageName,
+                                    PackageManager.GET_PERMISSIONS
+                                    | PackageManager.GET_SIGNATURES);
+                } catch (Exception e) {
+                    Log.w(LOGTAG, "Can't find plugin: " + serviceInfo.packageName);
+                    continue;
+                }
+                if (pkgInfo == null) {
+                    Log.w(LOGTAG, "Loading plugin: " + serviceInfo.packageName + ". Could not load package information.");
+                    continue;
+                }
+
+                /*
+                 * find the location of the plugin's shared library. The default
+                 * is to assume the app is either a user installed app or an
+                 * updated system app. In both of these cases the library is
+                 * stored in the app's data directory.
+                 */
+                String directory = pkgInfo.applicationInfo.dataDir + "/lib";
+                final int appFlags = pkgInfo.applicationInfo.flags;
+                final int updatedSystemFlags = ApplicationInfo.FLAG_SYSTEM |
+                                               ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
+                // preloaded system app with no user updates
+                if ((appFlags & updatedSystemFlags) == ApplicationInfo.FLAG_SYSTEM) {
+                    directory = PLUGIN_SYSTEM_LIB + pkgInfo.packageName;
+                }
+
+                // check if the plugin has the required permissions
+                String permissions[] = pkgInfo.requestedPermissions;
+                if (permissions == null) {
+                    Log.w(LOGTAG, "Loading plugin: " + serviceInfo.packageName + ". Does not have required permission.");
+                    continue;
+                }
+                boolean permissionOk = false;
+                for (String permit : permissions) {
+                    if (PLUGIN_PERMISSION.equals(permit)) {
+                        permissionOk = true;
+                        break;
+                    }
+                }
+                if (!permissionOk) {
+                    Log.w(LOGTAG, "Loading plugin: " + serviceInfo.packageName + ". Does not have required permission (2).");
+                    continue;
+                }
+
+                // check to ensure the plugin is properly signed
+                Signature signatures[] = pkgInfo.signatures;
+                if (signatures == null) {
+                    Log.w(LOGTAG, "Loading plugin: " + serviceInfo.packageName + ". Not signed.");
+                    continue;
+                }
+
+                // determine the type of plugin from the manifest
+                if (serviceInfo.metaData == null) {
+                    Log.e(LOGTAG, "The plugin '" + serviceInfo.name + "' has no type defined");
+                    continue;
+                }
+
+                String pluginType = serviceInfo.metaData.getString(PLUGIN_TYPE);
+                if (!TYPE_NATIVE.equals(pluginType)) {
+                    Log.e(LOGTAG, "Unrecognized plugin type: " + pluginType);
+                    continue;
+                }
+
+                try {
+                    Class<?> cls = getPluginClass(serviceInfo.packageName, serviceInfo.name);
+
+                    //TODO implement any requirements of the plugin class here!
+                    boolean classFound = true;
+
+                    if (!classFound) {
+                        Log.e(LOGTAG, "The plugin's class' " + serviceInfo.name + "' does not extend the appropriate class.");
+                        continue;
+                    }
+
+                } catch (NameNotFoundException e) {
+                    Log.e(LOGTAG, "Can't find plugin: " + serviceInfo.packageName);
+                    continue;
+                } catch (ClassNotFoundException e) {
+                    Log.e(LOGTAG, "Can't find plugin's class: " + serviceInfo.name);
+                    continue;
+                }
+
+                // if all checks have passed then make the plugin available
+                mPackageInfoCache.add(pkgInfo);
+                directories.add(directory);
+            }
+        }
+
+        return directories.toArray(new String[directories.size()]);
+    }
+
+    Class<?> getPluginClass(String packageName, String className)
+            throws NameNotFoundException, ClassNotFoundException {
+        Context pluginContext = this.mAppContext.createPackageContext(packageName,
+                Context.CONTEXT_INCLUDE_CODE |
+                Context.CONTEXT_IGNORE_SECURITY);
+        ClassLoader pluginCL = pluginContext.getClassLoader();
+        return pluginCL.loadClass(className);
+    }
+
     // Returns true when the intent is going to be handled by gecko launch
     boolean launch(Intent intent)
     {
         if (!checkAndSetLaunchState(LaunchState.Launching, LaunchState.Launched))
             return false;
 
         if (intent == null)
             intent = getIntent();
@@ -224,23 +373,24 @@ abstract public class GeckoApp
 
         getWindow().setFlags(mFullscreen ?
                              WindowManager.LayoutParams.FLAG_FULLSCREEN : 0,
                              WindowManager.LayoutParams.FLAG_FULLSCREEN);
 
         if (surfaceView == null)
             surfaceView = new GeckoSurfaceView(this);
         else
-            mainLayout.removeView(surfaceView);
+            mainLayout.removeAllViews();
 
-        mainLayout = new FrameLayout(this);
+        mainLayout = new AbsoluteLayout(this);
         mainLayout.addView(surfaceView,
-                           new FrameLayout.LayoutParams(FrameLayout.LayoutParams.FILL_PARENT,
-                                                        FrameLayout.LayoutParams.FILL_PARENT));
-
+                           new AbsoluteLayout.LayoutParams(AbsoluteLayout.LayoutParams.MATCH_PARENT, // level 8
+                                                           AbsoluteLayout.LayoutParams.MATCH_PARENT,
+                                                           0,
+                                                           0));
         setContentView(mainLayout,
                        new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
                                                   ViewGroup.LayoutParams.FILL_PARENT));
 
         mConnectivityFilter = new IntentFilter();
         mConnectivityFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
         mConnectivityReceiver = new GeckoConnectivityReceiver();
 
--- a/embedding/android/GeckoAppShell.java
+++ b/embedding/android/GeckoAppShell.java
@@ -303,16 +303,29 @@ public class GeckoAppShell
             if (oldHome.exists())
                 moveDir(oldHome, profileDir);
 
             File intHome =  geckoApp.getFilesDir();
             File intProf = new File(intHome, "mozilla");
             if (intHome != null && intProf != null && intProf.exists())
                 moveDir(intProf, profileDir);
         }
+        try {
+            String[] dirs = GeckoApp.mAppContext.getPluginDirectories();
+            StringBuffer pluginSearchPath = new StringBuffer();
+            for (int i = 0; i < dirs.length; i++) {
+                Log.i("GeckoPlugins", "dir: " + dirs[i]);
+                pluginSearchPath.append(dirs[i]);
+                pluginSearchPath.append(":");
+            }
+            GeckoAppShell.putenv("MOZ_PLUGIN_PATH="+pluginSearchPath);
+        } catch (Exception ex) {
+            Log.i("GeckoPlugins", "exception getting plugin dirs", ex);
+        }
+
         GeckoAppShell.putenv("HOME=" + homeDir);
         GeckoAppShell.putenv("GRE_HOME=" + GeckoApp.sGREDir.getPath());
         Intent i = geckoApp.getIntent();
         String env = i.getStringExtra("env0");
         Log.i(LOG_FILE_NAME, "env0: "+ env);
         for (int c = 1; env != null; c++) {
             GeckoAppShell.putenv(env);
             env = i.getStringExtra("env" + c);
@@ -390,16 +403,17 @@ public class GeckoAppShell
         GeckoAppShell.setSurfaceView(GeckoApp.surfaceView);
 
         // First argument is the .apk path
         String combinedArgs = apkPath + " -greomni " + apkPath;
         if (args != null)
             combinedArgs += " " + args;
         if (url != null)
             combinedArgs += " " + url;
+
         // and go
         GeckoAppShell.nativeRun(combinedArgs);
     }
 
     private static GeckoEvent mLastDrawEvent;
 
     private static void sendPendingEventsToGecko() {
         try {
@@ -1380,9 +1394,192 @@ public class GeckoAppShell
                 Settings.System.getInt(GeckoApp.mAppContext.getContentResolver(),
                                        Settings.System.TEXT_SHOW_PASSWORD);
             return (showPassword > 0);
         }
         catch (Exception e) {
             return false;
         }
     }
+    public static void addPluginView(final View view,
+                                     final double x, final double y,
+                                     final double w, final double h) {
+
+        Log.i("GeckoAppShell", "addPluginView:" + view + " @ x:" + x + " y:" + y + " w:" + w + " h:" + h ) ;
+
+        getMainHandler().post(new Runnable() { 
+                public void run() {
+                    AbsoluteLayout.LayoutParams lp = new AbsoluteLayout.LayoutParams((int)w,
+                                                                                     (int)h,
+                                                                                     (int)x,
+                                                                                     (int)y);
+
+                    if (GeckoApp.mainLayout.indexOfChild(view) == -1) {
+                        view.setWillNotDraw(false);
+                        if(view instanceof SurfaceView)
+                            ((SurfaceView)view).setZOrderOnTop(true);
+
+                        GeckoApp.mainLayout.addView(view, lp);
+                    }
+                    else
+                    {
+                        try {
+                            GeckoApp.mainLayout.updateViewLayout(view, lp);
+                        } catch (IllegalArgumentException e) {
+                            Log.i("updateViewLayout - IllegalArgumentException", "e:" + e);
+                            // it can be the case where we
+                            // get an update before the view
+                            // is actually attached.
+                        }
+                    }
+                }
+            });
+    }
+
+    public static void removePluginView(final View view) {
+        Log.i("GeckoAppShell", "remove view:" + view);
+        getMainHandler().post(new Runnable() { 
+                public void run() {
+                    try {
+                        GeckoApp.mainLayout.removeView(view);
+                    } catch (Exception e) {}
+                }
+            });
+    }
+
+    public static Class<?> loadPluginClass(String className, String libName) {
+        Log.i("GeckoAppShell", "in loadPluginClass... attempting to access className, then libName.....");
+        Log.i("GeckoAppShell", "className: " + className);
+        Log.i("GeckoAppShell", "libName: " + libName);
+
+        try {
+            String[] split = libName.split("/");
+            String packageName = split[split.length - 3];
+            Log.i("GeckoAppShell", "load \"" + className + "\" from \"" + packageName + 
+                  "\" for \"" + libName + "\"");
+            Context pluginContext = 
+                GeckoApp.mAppContext.createPackageContext(packageName,
+                                                          Context.CONTEXT_INCLUDE_CODE |
+                                                      Context.CONTEXT_IGNORE_SECURITY);
+            ClassLoader pluginCL = pluginContext.getClassLoader();
+            return pluginCL.loadClass(className);
+        } catch (java.lang.ClassNotFoundException cnfe) {
+            Log.i("GeckoAppShell", "class not found", cnfe);
+        } catch (android.content.pm.PackageManager.NameNotFoundException nnfe) {
+            Log.i("GeckoAppShell", "package not found", nnfe);
+        }
+        Log.e("GeckoAppShell", "couldn't find class");
+        return null;
+    }
+
+    static HashMap<SurfaceView, SurfaceLockInfo> sSufaceMap = new HashMap<SurfaceView, SurfaceLockInfo>();
+
+    public static void lockSurfaceANP()
+    {
+         Log.i("GeckoAppShell", "other lockSurfaceANP");
+    }
+
+    public static org.mozilla.gecko.SurfaceLockInfo lockSurfaceANP(android.view.SurfaceView sview, int top, int left, int bottom, int right)
+    {
+        Log.i("GeckoAppShell", "real lockSurfaceANP " + sview + ", " + top + ",  " + left + ", " + bottom + ", " + right);
+        if (sview == null)
+            return null;
+
+        int format = -1;
+        try {
+            Field privateFormatField = SurfaceView.class.getDeclaredField("mFormat");
+            privateFormatField.setAccessible(true);
+            format = privateFormatField.getInt(sview);
+        } catch (Exception e) {
+            Log.i("GeckoAppShell", "mFormat is not a field of sview: ", e);
+        }
+
+        int n = 0;
+        if (format == PixelFormat.RGB_565)
+            n = 2;
+        else if (format == PixelFormat.RGBA_8888)
+            n = 4;
+
+        if (n == 0)
+            return null;
+
+        SurfaceLockInfo info = sSufaceMap.get(sview);
+        if (info == null) {
+            info = new SurfaceLockInfo();
+            sSufaceMap.put(sview, info);
+        }
+
+        Rect r = new Rect(left, top, right, bottom);
+
+        info.canvas = sview.getHolder().lockCanvas(r);
+        int bufSizeRequired = info.canvas.getWidth() * info.canvas.getHeight() * n;
+        Log.i("GeckoAppShell", "lockSurfaceANP - bufSizeRequired: " + n + " " + info.canvas.getHeight() + " " + info.canvas.getWidth());
+
+        if (info.width != info.canvas.getWidth() || info.height != info.canvas.getHeight() || info.buffer == null || info.buffer.capacity() < bufSizeRequired) {
+            info.width = info.canvas.getWidth();
+            info.height = info.canvas.getHeight();
+
+            // XXX Bitmaps instead of ByteBuffer
+            info.buffer = ByteBuffer.allocateDirect(bufSizeRequired);  //leak
+            Log.i("GeckoAppShell", "!!!!!!!!!!!  lockSurfaceANP - Allocating buffer! " + bufSizeRequired);
+
+        }
+
+        info.canvas.drawColor(Color.WHITE, PorterDuff.Mode.CLEAR);
+
+        info.format = format;
+        info.dirtyTop = top;
+        info.dirtyBottom = bottom;
+        info.dirtyLeft = left;
+        info.dirtyRight = right;
+
+        return info;
+    }
+
+    public static void unlockSurfaceANP(SurfaceView sview) {
+        SurfaceLockInfo info = sSufaceMap.get(sview);
+
+        int n = 0;
+        Bitmap.Config config;
+        if (info.format == PixelFormat.RGB_565) {
+            n = 2;
+            config = Bitmap.Config.RGB_565;
+        } else {
+            n = 4;
+            config = Bitmap.Config.ARGB_8888;
+        }
+
+        Log.i("GeckoAppShell", "unlockSurfaceANP: " + (info.width * info.height * n));
+
+        Bitmap bm = Bitmap.createBitmap(info.width, info.height, config);
+        bm.copyPixelsFromBuffer(info.buffer);
+        info.canvas.drawBitmap(bm, 0, 0, null);
+        sview.getHolder().unlockCanvasAndPost(info.canvas);
+    }
+
+    public static Class getSurfaceLockInfoClass() {
+        Log.i("GeckoAppShell", "class name: " + SurfaceLockInfo.class.getName());
+        return SurfaceLockInfo.class;
+    }
+
+    public static Method getSurfaceLockMethod() {
+        Method[] m = GeckoAppShell.class.getMethods();
+        for (int i = 0; i < m.length; i++) {
+            if (m[i].getName().equals("lockSurfaceANP"))
+                return m[i];
+        }
+        return null;
+    }
+
+    static native void executeNextRunnable();
+
+    static class GeckoRunnableCallback implements Runnable {
+        public void run() {
+            Log.i("GeckoShell", "run GeckoRunnableCallback");
+            GeckoAppShell.executeNextRunnable();
+        }
+    }
+
+    public static void postToJavaThread(boolean mainThread) {
+        Log.i("GeckoShell", "post to " + (mainThread ? "main " : "") + "java thread");
+        getMainHandler().post(new GeckoRunnableCallback());
+    }
 }
--- a/embedding/android/Makefile.in
+++ b/embedding/android/Makefile.in
@@ -49,16 +49,17 @@ JAVAFILES = \
   GeckoApp.java \
   GeckoAppShell.java \
   GeckoConnectivityReceiver.java \
   GeckoEvent.java \
   GeckoSurfaceView.java \
   GeckoInputConnection.java \
   GeckoPhoneStateListener.java \
   AlertNotification.java \
+  SurfaceLockInfo.java \
   $(NULL)
 
 PROCESSEDJAVAFILES = \
   App.java \
   Restarter.java \
   NotificationHandler.java \
   LauncherShortcuts.java \
   $(NULL)
new file mode 100644
--- /dev/null
+++ b/embedding/android/SurfaceLockInfo.java
@@ -0,0 +1,18 @@
+package org.mozilla.gecko;
+
+import android.graphics.Canvas;
+import java.nio.Buffer;
+
+public class SurfaceLockInfo {
+    public int dirtyTop;
+    public int dirtyLeft;
+    public int dirtyRight;
+    public int dirtyBottom;
+
+    public int bpr;
+    public int format;
+    public int width;
+    public int height;
+    public Buffer buffer;
+    public Canvas canvas;
+}
--- a/embedding/components/printingui/src/os2/nsPrintingPromptService.cpp
+++ b/embedding/components/printingui/src/os2/nsPrintingPromptService.cpp
@@ -136,44 +136,38 @@ nsPrintingPromptService::ShowProgress(ns
 {
     NS_ENSURE_ARG(webProgressListener);
     NS_ENSURE_ARG(printProgressParams);
     NS_ENSURE_ARG(notifyOnOpen);
 
     *notifyOnOpen = PR_FALSE;
 
     nsPrintProgress* prtProgress = new nsPrintProgress();
-    nsresult rv = prtProgress->QueryInterface(NS_GET_IID(nsIPrintProgress), (void**)getter_AddRefs(mPrintProgress));
-    NS_ENSURE_SUCCESS(rv, rv);
-
-    rv = prtProgress->QueryInterface(NS_GET_IID(nsIWebProgressListener), (void**)getter_AddRefs(mWebProgressListener));
-    NS_ENSURE_SUCCESS(rv, rv);
-
-    nsPrintProgressParams* prtProgressParams = new nsPrintProgressParams();
-    rv = prtProgressParams->QueryInterface(NS_GET_IID(nsIPrintProgressParams), (void**)printProgressParams);
-    NS_ENSURE_SUCCESS(rv, rv);
+    mPrintProgress = prtProgress;
+    mWebProgressListener = prtProgress;
 
-    if (printProgressParams) {
-        nsCOMPtr<nsIDOMWindow> parentDOMIntl = parent;
+    nsCOMPtr<nsIPrintProgressParams> prtProgressParams = new nsPrintProgressParams();
+      
+    nsCOMPtr<nsIDOMWindow> parentWindow = parent;
 
-        if (mWatcher && !parentDOMIntl) {
-            mWatcher->GetActiveWindow(getter_AddRefs(parentDOMIntl));
-        }
-
-        if (parentDOMIntl) {
-            mPrintProgress->OpenProgressDialog(parentDOMIntl,
-                                               isForPrinting?kPrintProgressDialogURL:kPrtPrvProgressDialogURL,
-                                               *printProgressParams, openDialogObserver, notifyOnOpen);
-        }
+    if (mWatcher && !parentWindow) {
+        mWatcher->GetActiveWindow(getter_AddRefs(parentWindow));
     }
 
-    *webProgressListener = static_cast<nsIWebProgressListener*>(this);
-    NS_ADDREF(*webProgressListener);
+    if (parentWindow) {
+        mPrintProgress->OpenProgressDialog(parentWindow,
+                                           isForPrinting ? kPrintProgressDialogURL : kPrtPrvProgressDialogURL,
+                                           prtProgressParams, openDialogObserver, notifyOnOpen);
+    }
 
-    return rv;
+    prtProgressParams.forget(printProgressParams);
+    nsCOMPtr<nsIWebProgressListener> myWebProgressListener = this;
+    myWebProgressListener.forget(webProgressListener);
+
+    return NS_OK;
 }
 
 /* void showPageSetup (in nsIDOMWindow parent, in nsIPrintSettings printSettings); */
 NS_IMETHODIMP 
 nsPrintingPromptService::ShowPageSetup(nsIDOMWindow *parent, nsIPrintSettings *printSettings, nsIObserver *aObs)
 {
     NS_ENSURE_ARG(printSettings);
 
--- a/embedding/components/printingui/src/unixshared/nsPrintingPromptService.cpp
+++ b/embedding/components/printingui/src/unixshared/nsPrintingPromptService.cpp
@@ -139,44 +139,37 @@ nsPrintingPromptService::ShowProgress(ns
 {
     NS_ENSURE_ARG(webProgressListener);
     NS_ENSURE_ARG(printProgressParams);
     NS_ENSURE_ARG(notifyOnOpen);
 
     *notifyOnOpen = PR_FALSE;
 
     nsPrintProgress* prtProgress = new nsPrintProgress(printSettings);
-    nsresult rv = prtProgress->QueryInterface(NS_GET_IID(nsIPrintProgress), (void**)getter_AddRefs(mPrintProgress));
-    NS_ENSURE_SUCCESS(rv, rv);
+    mPrintProgress = prtProgress;
+    mWebProgressListener = prtProgress;
 
-    rv = prtProgress->QueryInterface(NS_GET_IID(nsIWebProgressListener), (void**)getter_AddRefs(mWebProgressListener));
-    NS_ENSURE_SUCCESS(rv, rv);
-
-    nsPrintProgressParams* prtProgressParams = new nsPrintProgressParams();
-    rv = prtProgressParams->QueryInterface(NS_GET_IID(nsIPrintProgressParams), (void**)printProgressParams);
-    NS_ENSURE_SUCCESS(rv, rv);
+    nsCOMPtr<nsIPrintProgressParams> prtProgressParams = new nsPrintProgressParams();
 
-    if (printProgressParams) {
-        nsCOMPtr<nsIDOMWindow> parentDOMIntl = parent;
+    nsCOMPtr<nsIDOMWindow> parentWindow = parent;
 
-        if (mWatcher && !parentDOMIntl) {
-            mWatcher->GetActiveWindow(getter_AddRefs(parentDOMIntl));
-        }
-
-        if (parentDOMIntl) {
-            mPrintProgress->OpenProgressDialog(parentDOMIntl,
-                                               isForPrinting?kPrintProgressDialogURL:kPrtPrvProgressDialogURL,
-                                               *printProgressParams, openDialogObserver, notifyOnOpen);
-        }
+    if (mWatcher && !parentWindow) {
+        mWatcher->GetActiveWindow(getter_AddRefs(parentWindow));
     }
 
-    *webProgressListener = static_cast<nsIWebProgressListener*>(this);
-    NS_ADDREF(*webProgressListener);
+    if (parentWindow) {
+        mPrintProgress->OpenProgressDialog(parentWindow,
+                                           isForPrinting ? kPrintProgressDialogURL : kPrtPrvProgressDialogURL,
+                                           prtProgressParams, openDialogObserver, notifyOnOpen);
+    }
 
-    return rv;
+    prtProgressParams.forget(printProgressParams);
+    NS_ADDREF(*webProgressListener = this);
+
+    return NS_OK;
 }
 
 /* void showPageSetup (in nsIDOMWindow parent, in nsIPrintSettings printSettings); */
 NS_IMETHODIMP 
 nsPrintingPromptService::ShowPageSetup(nsIDOMWindow *parent, nsIPrintSettings *printSettings, nsIObserver *aObs)
 {
     NS_ENSURE_ARG(printSettings);
 
--- a/embedding/components/printingui/src/win/nsPrintingPromptService.cpp
+++ b/embedding/components/printingui/src/win/nsPrintingPromptService.cpp
@@ -204,52 +204,44 @@ nsPrintingPromptService::ShowProgress(ns
                                       nsIPrintProgressParams** printProgressParams,
                                       PRBool*                  notifyOnOpen)
 {
     NS_ENSURE_ARG(webProgressListener);
     NS_ENSURE_ARG(printProgressParams);
     NS_ENSURE_ARG(notifyOnOpen);
 
     *notifyOnOpen = PR_FALSE;
-    if (mPrintProgress) 
-    {
+    if (mPrintProgress) {
         *webProgressListener = nsnull;
         *printProgressParams = nsnull;
         return NS_ERROR_FAILURE;
     }
 
     nsPrintProgress* prtProgress = new nsPrintProgress();
-    nsresult rv = prtProgress->QueryInterface(NS_GET_IID(nsIPrintProgress), (void**)getter_AddRefs(mPrintProgress));
-    NS_ENSURE_SUCCESS(rv, rv);
+    mPrintProgress = prtProgress;
+    mWebProgressListener = prtProgress;
 
-    rv = prtProgress->QueryInterface(NS_GET_IID(nsIWebProgressListener), (void**)getter_AddRefs(mWebProgressListener));
-    NS_ENSURE_SUCCESS(rv, rv);
-
-    nsPrintProgressParams* prtProgressParams = new nsPrintProgressParams();
-    rv = prtProgressParams->QueryInterface(NS_GET_IID(nsIPrintProgressParams), (void**)printProgressParams);
-    NS_ENSURE_SUCCESS(rv, rv);
+    nsCOMPtr<nsIPrintProgressParams> prtProgressParams = new nsPrintProgressParams();
 
-    if (printProgressParams) {
-        nsCOMPtr<nsIDOMWindow> parentDOMIntl = parent;
+    nsCOMPtr<nsIDOMWindow> parentWindow = parent;
 
-        if (mWatcher && !parentDOMIntl) {
-            mWatcher->GetActiveWindow(getter_AddRefs(parentDOMIntl));
-        }
-
-        if (parentDOMIntl) {
-            mPrintProgress->OpenProgressDialog(parentDOMIntl,
-                                               isForPrinting?kPrintProgressDialogURL:kPrtPrvProgressDialogURL,
-                                               *printProgressParams, openDialogObserver, notifyOnOpen);
-        }
+    if (mWatcher && !parentWindow) {
+        mWatcher->GetActiveWindow(getter_AddRefs(parentWindow));
     }
 
-    *webProgressListener = static_cast<nsIWebProgressListener*>(this);
-    NS_ADDREF(*webProgressListener);
+    if (parentWindow) {
+        mPrintProgress->OpenProgressDialog(parentWindow,
+                                           isForPrinting ? kPrintProgressDialogURL : kPrtPrvProgressDialogURL,
+                                           prtProgressParams, openDialogObserver, notifyOnOpen);
+    }
 
-    return rv;
+    prtProgressParams.forget(printProgressParams);
+    NS_ADDREF(*webProgressListener = this);
+
+    return NS_OK;
 }
 
 /* void showPageSetup (in nsIDOMWindow parent, in nsIPrintSettings printSettings); */
 NS_IMETHODIMP 
 nsPrintingPromptService::ShowPageSetup(nsIDOMWindow *parent, nsIPrintSettings *printSettings, nsIObserver *aObs)
 {
     NS_ENSURE_ARG(printSettings);
 
--- a/embedding/components/windowwatcher/src/nsWindowWatcher.cpp
+++ b/embedding/components/windowwatcher/src/nsWindowWatcher.cpp
@@ -2111,17 +2111,17 @@ nsWindowWatcher::GetJSContextFromWindow(
 {
   JSContext *cx = 0;
 
   if (aWindow) {
     nsCOMPtr<nsIScriptGlobalObject> sgo(do_QueryInterface(aWindow));
     if (sgo) {
       nsIScriptContext *scx = sgo->GetContext();
       if (scx)
-        cx = (JSContext *) scx->GetNativeContext();
+        cx = scx->GetNativeContext();
     }
     /* (off-topic note:) the nsIScriptContext can be retrieved by
     nsCOMPtr<nsIScriptContext> scx;
     nsJSUtils::GetDynamicScriptContext(cx, getter_AddRefs(scx));
     */
   }
 
   return cx;
--- a/gfx/thebes/gfxBlur.cpp
+++ b/gfx/thebes/gfxBlur.cpp
@@ -141,29 +141,34 @@ BoxBlurHorizontal(unsigned char* aInput,
                   PRInt32 aRows,
                   const nsIntRect& aSkipRect)
 {
     NS_ASSERTION(aWidth > 0, "Can't handle zero width here");
 
     PRInt32 boxSize = aLeftLobe + aRightLobe + 1;
     PRBool skipRectCoversWholeRow = 0 >= aSkipRect.x &&
                                     aWidth <= aSkipRect.XMost();
+    if (boxSize == 1) {
+        memcpy(aOutput, aInput, aWidth*aRows);
+        return;
+    }
+    PRUint32 reciprocal = (PRUint64(1) << 32)/boxSize;
 
     for (PRInt32 y = 0; y < aRows; y++) {
         // Check whether the skip rect intersects this row. If the skip
         // rect covers the whole surface in this row, we can avoid
         // this row entirely (and any others along the skip rect).
         PRBool inSkipRectY = y >= aSkipRect.y &&
                              y < aSkipRect.YMost();
         if (inSkipRectY && skipRectCoversWholeRow) {
             y = aSkipRect.YMost() - 1;
             continue;
         }
 
-        PRInt32 alphaSum = 0;
+        PRUint32 alphaSum = 0;
         for (PRInt32 i = 0; i < boxSize; i++) {
             PRInt32 pos = i - aLeftLobe;
             // See assertion above; if aWidth is zero, then we would have no
             // valid position to clamp to.
             pos = NS_MAX(pos, 0);
             pos = NS_MIN(pos, aWidth - 1);
             alphaSum += aInput[aWidth * y + pos];
         }
@@ -187,17 +192,17 @@ BoxBlurHorizontal(unsigned char* aInput,
                     pos = NS_MIN(pos, aWidth - 1);
                     alphaSum += aInput[aWidth * y + pos];
                 }
             }
             PRInt32 tmp = x - aLeftLobe;
             PRInt32 last = NS_MAX(tmp, 0);
             PRInt32 next = NS_MIN(tmp + boxSize, aWidth - 1);
 
-            aOutput[aWidth * y + x] = alphaSum/boxSize;
+            aOutput[aWidth * y + x] = (PRUint64(alphaSum)*reciprocal) >> 32;
 
             alphaSum += aInput[aWidth * y + next] -
                         aInput[aWidth * y + last];
         }
     }
 }
 
 /**
@@ -214,26 +219,31 @@ BoxBlurVertical(unsigned char* aInput,
                 PRInt32 aRows,
                 const nsIntRect& aSkipRect)
 {
     NS_ASSERTION(aRows > 0, "Can't handle zero rows here");
 
     PRInt32 boxSize = aTopLobe + aBottomLobe + 1;
     PRBool skipRectCoversWholeColumn = 0 >= aSkipRect.y &&
                                        aRows <= aSkipRect.YMost();
+    if (boxSize == 1) {
+        memcpy(aOutput, aInput, aWidth*aRows);
+        return;
+    }
+    PRUint32 reciprocal = (PRUint64(1) << 32)/boxSize;
 
     for (PRInt32 x = 0; x < aWidth; x++) {
         PRBool inSkipRectX = x >= aSkipRect.x &&
                              x < aSkipRect.XMost();
         if (inSkipRectX && skipRectCoversWholeColumn) {
             x = aSkipRect.XMost() - 1;
             continue;
         }
 
-        PRInt32 alphaSum = 0;
+        PRUint32 alphaSum = 0;
         for (PRInt32 i = 0; i < boxSize; i++) {
             PRInt32 pos = i - aTopLobe;
             // See assertion above; if aRows is zero, then we would have no
             // valid position to clamp to.
             pos = NS_MAX(pos, 0);
             pos = NS_MIN(pos, aRows - 1);
             alphaSum += aInput[aWidth * pos + x];
         }
@@ -253,17 +263,17 @@ BoxBlurVertical(unsigned char* aInput,
                     pos = NS_MIN(pos, aRows - 1);
                     alphaSum += aInput[aWidth * pos + x];
                 }
             }
             PRInt32 tmp = y - aTopLobe;
             PRInt32 last = NS_MAX(tmp, 0);
             PRInt32 next = NS_MIN(tmp + boxSize, aRows - 1);
 
-            aOutput[aWidth * y + x] = alphaSum/boxSize;
+            aOutput[aWidth * y + x] = (PRUint64(alphaSum)*reciprocal) >> 32;
 
             alphaSum += aInput[aWidth * next + x] -
                         aInput[aWidth * last + x];
         }
     }
 }
 
 static void ComputeLobes(PRInt32 aRadius, PRInt32 aLobes[3][2])
--- a/js/src/Makefile.in
+++ b/js/src/Makefile.in
@@ -301,24 +301,27 @@ CPPSRCS += \
 		jstracer.cpp \
 		Assembler.cpp  \
 		Allocator.cpp  \
 		CodeAlloc.cpp  \
 		Containers.cpp \
 		Fragmento.cpp  \
 		LIR.cpp        \
 		njconfig.cpp   \
-		RegAlloc.cpp   \
 		avmplus.cpp    \
 		Native$(NANOJIT_ARCH).cpp \
 		jsbuiltins.cpp \
 		VMPI.cpp       \
 		Writer.cpp     \
 		$(NULL)
 
+ifdef MOZ_DEBUG
+CPPSRCS += RegAlloc.cpp
+endif
+
 endif # ENABLE_TRACEJIT
 ifdef ENABLE_METHODJIT
 
 ###############################################
 # BEGIN include sources for the method JIT
 #
 VPATH += 	$(srcdir)/methodjit
 
@@ -418,34 +421,47 @@ VPATH += 	$(srcdir)/assembler \
 		$(srcdir)/assembler/wtf \
 		$(srcdir)/assembler/jit \
 		$(srcdir)/assembler/assembler \
 		$(srcdir)/methodjit \
 		$(srcdir)/yarr \
 		$(NONE)
 
 CPPSRCS += 	Assertions.cpp \
-		ExecutableAllocatorPosix.cpp \
-		ExecutableAllocatorWin.cpp \
-		ExecutableAllocatorOS2.cpp \
 		ExecutableAllocator.cpp \
 		ARMAssembler.cpp \
-        Logging.cpp \
 		MacroAssemblerARM.cpp \
 		MacroAssemblerX86Common.cpp \
-		OSAllocatorOS2.cpp \
-		OSAllocatorPosix.cpp \
-		OSAllocatorWin.cpp \
 		PageBlock.cpp \
 		YarrInterpreter.cpp \
 		YarrJIT.cpp \
 		YarrPattern.cpp \
 		YarrSyntaxChecker.cpp \
 		$(NONE)
 
+ifdef MOZ_DEBUG
+CPPSRCS += Logging.cpp
+endif
+
+ifneq (,$(filter-out OS2 WINNT,$(OS_ARCH)))
+CPPSRCS += ExecutableAllocatorPosix.cpp \
+           OSAllocatorPosix.cpp \
+           $(NONE)
+endif
+ifeq ($(OS_ARCH),WINNT)
+CPPSRCS += ExecutableAllocatorWin.cpp \
+           OSAllocatorWin.cpp \
+           $(NONE)
+endif
+ifeq ($(OS_ARCH),OS2)
+CPPSRCS += ExecutableAllocatorOS2.cpp \
+           OSAllocatorOS2.cpp \
+           $(NONE)
+endif
+
 ifeq (86, $(findstring 86,$(TARGET_CPU)))
 ifeq (x86_64, $(TARGET_CPU))
 #CPPSRCS		+= only_on_x86_64.cpp
 else
 #CPPSRCS		+= only_on_x86.cpp
 endif
 endif
 ifeq (arm, $(TARGET_CPU))
@@ -1042,24 +1058,29 @@ endif
 
 INCLUDES +=	-I$(srcdir)/assembler -I$(srcdir)/yarr
 
 ifdef ENABLE_METHODJIT
 # Build a standalone test program that exercises the assembler
 # sources a bit.
 TESTMAIN_OBJS = \
 		Assertions.$(OBJ_SUFFIX) \
-		ExecutableAllocatorPosix.$(OBJ_SUFFIX) \
-		ExecutableAllocatorWin.$(OBJ_SUFFIX) \
 		ExecutableAllocator.$(OBJ_SUFFIX) \
 		ARMAssembler.$(OBJ_SUFFIX) \
 		MacroAssemblerARM.$(OBJ_SUFFIX) \
 		TestMain.$(OBJ_SUFFIX) \
 		jsutil.$(OBJ_SUFFIX) \
 		jslog2.$(OBJ_SUFFIX)
+
+ifeq ($(OS_ARCH),WINNT)
+TESTMAIN_OBJS += ExecutableAllocatorWin.$(OBJ_SUFFIX)
+else
+TESTMAIN_OBJS += ExecutableAllocatorPosix.$(OBJ_SUFFIX)
+endif
+
 TestMain$(HOST_BIN_SUFFIX): $(TESTMAIN_OBJS)
 	$(CXX) -o TestMain$(HOST_BIN_SUFFIX) $(TESTMAIN_OBJS)
 endif
 
 #
 # END kludges for the Nitro assembler
 ###############################################
 
--- a/js/src/config/autoconf.mk.in
+++ b/js/src/config/autoconf.mk.in
@@ -327,16 +327,17 @@ MOZ_UTILS_PROGRAM_LDFLAGS = @MOZ_UTILS_P
 MOZ_MAPINFO	= @MOZ_MAPINFO@
 
 QEMU_CANT_RUN_JS_SHELL = @QEMU_CANT_RUN_JS_SHELL@
 
 MACOS_SDK_DIR	= @MACOS_SDK_DIR@
 NEXT_ROOT	= @NEXT_ROOT@
 GCC_VERSION	= @GCC_VERSION@
 UNIVERSAL_BINARY= @UNIVERSAL_BINARY@
+MOZ_CAN_RUN_PROGRAMS = MOZ_CAN_RUN_PROGRAMS@
 HAVE_DTRACE= @HAVE_DTRACE@
 
 VISIBILITY_FLAGS = @VISIBILITY_FLAGS@
 WRAP_SYSTEM_INCLUDES = @WRAP_SYSTEM_INCLUDES@
 
 ENABLE_TRACEJIT = @ENABLE_TRACEJIT@
 ENABLE_METHODJIT = @ENABLE_METHODJIT@
 NANOJIT_ARCH = @NANOJIT_ARCH@
--- a/js/src/configure.in
+++ b/js/src/configure.in
@@ -1078,18 +1078,20 @@ from building Mozilla. Upgrade to Xcode 
     dnl it has moved into /usr/bin.
     MOZ_PATH_PROG(SDP, sdp, :, [$PATH:/usr/bin:/Developer/Tools])
     ;;
 esac
 
 AC_SUBST(GCC_VERSION)
 
 dnl The universal machinery sets UNIVERSAL_BINARY to inform packager.mk
-dnl that a universal binary is being produced.
+dnl that a universal binary is being produced and MOZ_CAN_RUN_PROGRAMS
+dnl when we can run target binaries.
 AC_SUBST(UNIVERSAL_BINARY)
+AC_SUBST(MOZ_CAN_RUN_PROGRAMS)
 
 dnl ========================================================
 dnl Check for MacOS deployment target version
 dnl ========================================================
 
 MOZ_ARG_ENABLE_STRING(macos-target,
                       [  --enable-macos-target=VER (default=10.5)
                           Set the minimum MacOS version needed at runtime],
--- a/layout/build/Makefile.in
+++ b/layout/build/Makefile.in
@@ -130,16 +130,17 @@ SHARED_LIBRARY_LIBS += \
 	$(DEPTH)/dom/system/cocoa/$(LIB_PREFIX)domsystemcocoa_s.$(LIB_SUFFIX) \
 	$(NULL)
 LOCAL_INCLUDES	+= \
 	-I$(topsrcdir)/dom/system/cocoa \
 	$(NULL)
 else ifneq (,$(filter android,$(MOZ_WIDGET_TOOLKIT)))
 SHARED_LIBRARY_LIBS += \
 	$(DEPTH)/dom/system/android/$(LIB_PREFIX)domsystemandroid_s.$(LIB_SUFFIX) \
+	$(DEPTH)/dom/plugins/base/android/$(LIB_PREFIX)gkpluginandroid_s.$(LIB_SUFFIX) \
 	$(NULL)
 LOCAL_INCLUDES	+= \
 	-I$(topsrcdir)/dom/system/android \
 	$(NULL)
 endif
 
 ifdef MOZ_VORBIS
 SHARED_LIBRARY_LIBS 	+= \
--- a/layout/build/nsLayoutModule.cpp
+++ b/layout/build/nsLayoutModule.cpp
@@ -264,19 +264,16 @@ static NS_DEFINE_CID(kWindowCommandTable
 
 nsresult
 NS_NewXULContentBuilder(nsISupports* aOuter, REFNSIID aIID, void** aResult);
 
 nsresult
 NS_NewXULTreeBuilder(nsISupports* aOuter, REFNSIID aIID, void** aResult);
 #endif
 
-nsresult
-NS_NewDOMImplementation(nsIDOMDOMImplementation**);
-
 static void Shutdown();
 
 #ifdef MOZ_XTF
 #include "nsIXTFService.h"
 #include "nsIXMLContentBuilder.h"
 #endif
 
 #include "nsGeolocation.h"
@@ -505,17 +502,16 @@ NS_GENERIC_FACTORY_CONSTRUCTOR(inDOMView
 NS_GENERIC_FACTORY_CONSTRUCTOR(inDeepTreeWalker)
 NS_GENERIC_FACTORY_CONSTRUCTOR(inFlasher)
 NS_GENERIC_FACTORY_CONSTRUCTOR(inCSSValueSearch)
 NS_GENERIC_FACTORY_CONSTRUCTOR(inDOMUtils)
 
 MAKE_CTOR(CreateNameSpaceManager,         nsINameSpaceManager,         NS_GetNameSpaceManager)
 MAKE_CTOR(CreateDocumentViewer,           nsIDocumentViewer,           NS_NewDocumentViewer)
 MAKE_CTOR(CreateHTMLDocument,             nsIDocument,                 NS_NewHTMLDocument)
-MAKE_CTOR(CreateDOMImplementation,        nsIDOMDOMImplementation,     NS_NewDOMImplementation)
 MAKE_CTOR(CreateXMLDocument,              nsIDocument,                 NS_NewXMLDocument)
 MAKE_CTOR(CreateSVGDocument,              nsIDocument,                 NS_NewSVGDocument)
 MAKE_CTOR(CreateImageDocument,            nsIDocument,                 NS_NewImageDocument)
 MAKE_CTOR(CreateDOMSelection,             nsISelection,                NS_NewDomSelection)
 MAKE_CTOR(CreateRange,                    nsIDOMRange,                 NS_NewRange)
 MAKE_CTOR(CreateRangeUtils,               nsIRangeUtils,               NS_NewRangeUtils)
 MAKE_CTOR(CreateContentIterator,          nsIContentIterator,          NS_NewContentIterator)
 MAKE_CTOR(CreatePreContentIterator,       nsIContentIterator,          NS_NewPreContentIterator)
@@ -741,17 +737,16 @@ NS_DEFINE_NAMED_CID(IN_DOMVIEW_CID);
 #endif
 NS_DEFINE_NAMED_CID(IN_DEEPTREEWALKER_CID);
 NS_DEFINE_NAMED_CID(IN_FLASHER_CID);
 NS_DEFINE_NAMED_CID(IN_CSSVALUESEARCH_CID);
 NS_DEFINE_NAMED_CID(IN_DOMUTILS_CID);
 NS_DEFINE_NAMED_CID(NS_NAMESPACEMANAGER_CID);
 NS_DEFINE_NAMED_CID(NS_DOCUMENT_VIEWER_CID);
 NS_DEFINE_NAMED_CID(NS_HTMLDOCUMENT_CID);
-NS_DEFINE_NAMED_CID(NS_DOM_IMPLEMENTATION_CID);
 NS_DEFINE_NAMED_CID(NS_XMLDOCUMENT_CID);
 NS_DEFINE_NAMED_CID(NS_SVGDOCUMENT_CID);
 NS_DEFINE_NAMED_CID(NS_IMAGEDOCUMENT_CID);
 NS_DEFINE_NAMED_CID(NS_DOMSELECTION_CID);
 NS_DEFINE_NAMED_CID(NS_RANGE_CID);
 NS_DEFINE_NAMED_CID(NS_RANGEUTILS_CID);
 NS_DEFINE_NAMED_CID(NS_CONTENTITERATOR_CID);
 NS_DEFINE_NAMED_CID(NS_PRECONTENTITERATOR_CID);
@@ -876,17 +871,16 @@ static const mozilla::Module::CIDEntry k
 #endif
   { &kIN_DEEPTREEWALKER_CID, false, NULL, inDeepTreeWalkerConstructor },
   { &kIN_FLASHER_CID, false, NULL, inFlasherConstructor },
   { &kIN_CSSVALUESEARCH_CID, false, NULL, inCSSValueSearchConstructor },
   { &kIN_DOMUTILS_CID, false, NULL, inDOMUtilsConstructor },
   { &kNS_NAMESPACEMANAGER_CID, false, NULL, CreateNameSpaceManager },
   { &kNS_DOCUMENT_VIEWER_CID, false, NULL, CreateDocumentViewer },
   { &kNS_HTMLDOCUMENT_CID, false, NULL, CreateHTMLDocument },
-  { &kNS_DOM_IMPLEMENTATION_CID, false, NULL, CreateDOMImplementation },
   { &kNS_XMLDOCUMENT_CID, false, NULL, CreateXMLDocument },
   { &kNS_SVGDOCUMENT_CID, false, NULL, CreateSVGDocument },
   { &kNS_IMAGEDOCUMENT_CID, false, NULL, CreateImageDocument },
   { &kNS_DOMSELECTION_CID, false, NULL, CreateDOMSelection },
   { &kNS_RANGE_CID, false, NULL, CreateRange },
   { &kNS_RANGEUTILS_CID, false, NULL, CreateRangeUtils },
   { &kNS_CONTENTITERATOR_CID, false, NULL, CreateContentIterator },
   { &kNS_PRECONTENTITERATOR_CID, false, NULL, CreatePreContentIterator },
--- a/layout/forms/nsComboboxControlFrame.cpp
+++ b/layout/forms/nsComboboxControlFrame.cpp
@@ -539,54 +539,96 @@ nsComboboxControlFrame::ReflowDropdown(n
                             ignoredStatus);
  
    // Set the child's width and height to it's desired size
   FinishReflowChild(mDropdownFrame, aPresContext, &kidReflowState,
                     desiredSize, rect.x, rect.y, flags);
   return rv;
 }
 
+nsPoint
+nsComboboxControlFrame::GetCSSTransformTranslation()
+{
+  nsIFrame* frame = this;
+  PRBool is3DTransform = PR_FALSE;
+  gfxMatrix transform;
+  while (frame) {
+    nsIFrame* parent = nsnull;
+    gfx3DMatrix ctm = frame->GetTransformMatrix(&parent);
+    gfxMatrix matrix;
+    if (ctm.Is2D(&matrix)) {
+      transform = transform * matrix;
+    } else {
+      is3DTransform = PR_TRUE;
+      break;
+    }
+    frame = parent;
+  }
+  nsPoint translation;
+  if (!is3DTransform && !transform.HasNonTranslation()) {
+    nsPresContext* pc = PresContext();
+    gfxPoint pixelTranslation = transform.GetTranslation();
+    PRInt32 apd = pc->AppUnitsPerDevPixel();
+    translation.x = NSFloatPixelsToAppUnits(float(pixelTranslation.x), apd);
+    translation.y = NSFloatPixelsToAppUnits(float(pixelTranslation.y), apd);
+    // To get the translation introduced only by transforms we subtract the
+    // regular non-transform translation.
+    nsRootPresContext* rootPC = pc->GetRootPresContext();
+    if (rootPC) {
+      translation -= GetOffsetToCrossDoc(rootPC->PresShell()->GetRootFrame());
+    } else {
+      translation.x = translation.y = 0;
+    }
+  }
+  return translation;
+}
+
 void
 nsComboboxControlFrame::AbsolutelyPositionDropDown()
 {
    // Position the dropdown list. It is positioned below the display frame if there is enough
    // room on the screen to display the entire list. Otherwise it is placed above the display
    // frame.
 
    // Note: As first glance, it appears that you could simply get the absolute bounding box for the
    // dropdown list by first getting its view, then getting the view's nsIWidget, then asking the nsIWidget
    // for it's AbsoluteBounds. The problem with this approach, is that the dropdown lists y location can
    // change based on whether the dropdown is placed below or above the display frame.
    // The approach, taken here is to get use the absolute position of the display frame and use it's location
    // to determine if the dropdown will go offscreen.
 
+  // Normal frame geometry (eg GetOffsetTo, mRect) doesn't include transforms.
+  // In the special case that our transform is only a 2D translation we
+  // introduce this hack so that the dropdown will show up in the right place.
+  nsPoint translation = GetCSSTransformTranslation();
+
    // Use the height calculated for the area frame so it includes both
    // the display and button heights.
   nscoord dropdownYOffset = GetRect().height;
   nsSize dropdownSize = mDropdownFrame->GetSize();
 
   nsRect screen = nsFormControlFrame::GetUsableScreenRect(PresContext());
 
   // Check to see if the drop-down list will go offscreen
-  if (GetScreenRectInAppUnits().YMost() + dropdownSize.height > screen.YMost()) {
+  if ((GetScreenRectInAppUnits() + translation).YMost() + dropdownSize.height > screen.YMost()) {
     // move the dropdown list up
     dropdownYOffset = - (dropdownSize.height);
   }
 
   nsPoint dropdownPosition;
   const nsStyleVisibility* vis = GetStyleVisibility();
   if (vis->mDirection == NS_STYLE_DIRECTION_RTL) {
     // Align the right edge of the drop-down with the right edge of the control.
     dropdownPosition.x = GetRect().width - dropdownSize.width;
   } else {
     dropdownPosition.x = 0;
   }
   dropdownPosition.y = dropdownYOffset; 
 
-  mDropdownFrame->SetPosition(dropdownPosition);
+  mDropdownFrame->SetPosition(dropdownPosition + translation);
 }
 
 //----------------------------------------------------------
 // 
 //----------------------------------------------------------
 #ifdef DO_REFLOW_DEBUG
 static int myCounter = 0;
 
--- a/layout/forms/nsComboboxControlFrame.h
+++ b/layout/forms/nsComboboxControlFrame.h
@@ -249,16 +249,22 @@ protected:
    */
   PRBool ShowList(PRBool aShowList);
   void CheckFireOnChange();
   void FireValueChangeEvent();
   nsresult RedisplayText(PRInt32 aIndex);
   void HandleRedisplayTextEvent();
   void ActuallyDisplayText(PRBool aNotify);
 
+private:
+  // If our total transform to the root frame of the root document is only a 2d
+  // translation then return that translation, otherwise returns (0,0).
+  nsPoint GetCSSTransformTranslation();
+
+protected:
   nsFrameList              mPopupFrames;             // additional named child list
   nsCOMPtr<nsIContent>     mDisplayContent;          // Anonymous content used to display the current selection
   nsCOMPtr<nsIContent>     mButtonContent;           // Anonymous content for the button
   nsIFrame*                mDisplayFrame;            // frame to display selection
   nsIFrame*                mButtonFrame;             // button frame
   nsIFrame*                mDropdownFrame;           // dropdown list frame
   nsIListControlFrame *    mListControlFrame;        // ListControl Interface for the dropdown frame
 
--- a/layout/generic/nsFrame.cpp
+++ b/layout/generic/nsFrame.cpp
@@ -1054,17 +1054,16 @@ public:
 private:
   PRInt16 mSelectionValue;
 };
 
 void nsDisplaySelectionOverlay::Paint(nsDisplayListBuilder* aBuilder,
                                       nsRenderingContext* aCtx)
 {
   LookAndFeel::ColorID colorID;
-  nsresult result;
   if (mSelectionValue == nsISelectionController::SELECTION_ON) {
     colorID = LookAndFeel::eColorID_TextSelectBackground;
   } else if (mSelectionValue == nsISelectionController::SELECTION_ATTENTION) {
     colorID = LookAndFeel::eColorID_TextSelectBackgroundAttention;
   } else {
     colorID = LookAndFeel::eColorID_TextSelectBackgroundDisabled;
   }
 
--- a/layout/generic/nsObjectFrame.cpp
+++ b/layout/generic/nsObjectFrame.cpp
@@ -1626,17 +1626,25 @@ nsObjectFrame::BuildLayer(nsDisplayListB
     }
 
     NS_ASSERTION(layer->GetType() == Layer::TYPE_IMAGE, "Bad layer type");
 
     ImageLayer* imglayer = static_cast<ImageLayer*>(layer.get());
     UpdateImageLayer(container, r);
 
     imglayer->SetContainer(container);
-    imglayer->SetFilter(nsLayoutUtils::GetGraphicsFilterForFrame(this));
+    gfxPattern::GraphicsFilter filter =
+      nsLayoutUtils::GetGraphicsFilterForFrame(this);
+#ifdef MOZ_GFX_OPTIMIZE_MOBILE
+    if (!aManager->IsCompositingCheap()) {
+      // Pixman just horrible with bilinear filter scaling
+      filter = gfxPattern::FILTER_NEAREST;
+    }
+#endif
+    imglayer->SetFilter(filter);
 
     layer->SetContentFlags(IsOpaque() ? Layer::CONTENT_OPAQUE : 0);
   } else {
     NS_ASSERTION(aItem->GetType() == nsDisplayItem::TYPE_PLUGIN_READBACK,
                  "Unknown item type");
     NS_ABORT_IF_FALSE(!IsOpaque(), "Opaque plugins don't use backgrounds");
 
     if (!layer) {
@@ -1678,16 +1686,32 @@ nsObjectFrame::BuildLayer(nsDisplayListB
   return layer.forget();
 }
 
 void
 nsObjectFrame::PaintPlugin(nsDisplayListBuilder* aBuilder,
                            nsRenderingContext& aRenderingContext,
                            const nsRect& aDirtyRect, const nsRect& aPluginRect)
 {
+#if defined(ANDROID)
+  if (mInstanceOwner) {
+    NPWindow *window;
+    mInstanceOwner->GetWindow(window);
+
+    gfxRect frameGfxRect =
+      PresContext()->AppUnitsToGfxUnits(aPluginRect);
+    gfxRect dirtyGfxRect =
+      PresContext()->AppUnitsToGfxUnits(aDirtyRect);
+    gfxContext* ctx = aRenderingContext.ThebesContext();
+
+    mInstanceOwner->Paint(ctx, frameGfxRect, dirtyGfxRect);
+    return;
+  }
+#endif
+
   // Screen painting code
 #if defined(XP_MACOSX)
   // delegate all painting to the plugin instance.
   if (mInstanceOwner) {
     if (mInstanceOwner->GetDrawingModel() == NPDrawingModelCoreGraphics ||
         mInstanceOwner->GetDrawingModel() == NPDrawingModelCoreAnimation ||
         mInstanceOwner->GetDrawingModel() == 
                                   NPDrawingModelInvalidatingCoreAnimation) {
@@ -2514,17 +2538,17 @@ nsObjectFrame::NotifyContentObjectWrappe
   nsIScriptGlobalObject *sgo = doc->GetScriptGlobalObject();
   if (!sgo)
     return;
 
   nsIScriptContext *scx = sgo->GetContext();
   if (!scx)
     return;
 
-  JSContext *cx = (JSContext *)scx->GetNativeContext();
+  JSContext *cx = scx->GetNativeContext();
 
   nsCOMPtr<nsIXPConnectWrappedNative> wrapper;
   nsContentUtils::XPConnect()->
     GetWrappedNativeOfNativeObject(cx, sgo->GetGlobalJSObject(), mContent,
                                    NS_GET_IID(nsISupports),
                                    getter_AddRefs(wrapper));
 
   if (!wrapper) {
--- a/layout/reftests/box-shadow/reftest.list
+++ b/layout/reftests/box-shadow/reftest.list
@@ -1,13 +1,13 @@
 == boxshadow-basic.html boxshadow-basic-ref.html
 != boxshadow-blur.html boxshadow-blur-notref.html
 != boxshadow-blur.html boxshadow-blur-notref2.html
-== boxshadow-blur-2.html boxshadow-blur-2-ref.html
-fails-if(Android) != boxshadow-blur-2.html boxshadow-blur-2-notref.html
+random == boxshadow-blur-2.html boxshadow-blur-2-ref.html # fixedpoint division in blur code makes this fail
+random fails-if(Android) != boxshadow-blur-2.html boxshadow-blur-2-notref.html # fixedpoint division in blur code makes this fail
 == boxshadow-multiple.html boxshadow-multiple-ref.html
 == boxshadow-spread.html boxshadow-spread-ref.html
 == tableboxshadow-basic.html tableboxshadow-basic-ref.html
 == tableboxshadow-trshadow.html tableboxshadow-trshadow-ref.html
 == tableboxshadow-tdshadow.html tableboxshadow-tdshadow-ref.html
 == boxshadow-rounding.html boxshadow-rounding-ref.html
 fails-if(Android) == boxshadow-button.html boxshadow-button-ref.html
 fails-if(Android) == boxshadow-fileupload.html boxshadow-fileupload-ref.html
--- a/layout/reftests/bugs/reftest.list
+++ b/layout/reftests/bugs/reftest.list
@@ -1443,17 +1443,17 @@ asserts(5) == 528038-2.html 528038-2-ref
 == 531098-1.html 531098-1-ref.html
 == 531371-1.html 531371-1-ref.html
 == 534526-1a.html 534526-1-ref.html
 == 534526-1b.html 534526-1-ref.html
 == 534804-1.html 534804-1-ref.html
 == 534808-1.html 534808-1-ref.html
 == 534808-2.html 534808-2-ref.html
 == 534919-1.html 534919-1-ref.html
-== 536061.html 536061-ref.html
+random == 536061.html 536061-ref.html # fixedpoint division in blur code makes this fail
 == 537507-1.xul 537507-1-ref.xul
 == 537507-2.html 537507-2-ref.html
 == 537471-1.html 537471-1-ref.html
 == 538909-1.html 538909-1-ref.html
 == 538935-1.html 538935-1-ref.html
 == 539226-1.html about:blank
 == 539323-1.html 539323-1-ref.html
 == 539323-2.html 539323-2-ref.html
new file mode 100644
--- /dev/null
+++ b/layout/reftests/svg/dynamic-clipPath-02.svg
@@ -0,0 +1,37 @@
+<!--
+     Any copyright is dedicated to the Public Domain.
+     http://creativecommons.org/publicdomain/zero/1.0/
+-->
+<svg xmlns="http://www.w3.org/2000/svg" version="1.1"
+     class="reftest-wait"
+     onload="startTest()"
+     xmlns:xlink="http://www.w3.org/1999/xlink">
+  <title>Testing that dynamic changes to the clipPathUnits are reflected in the clipPath</title>
+
+  <defs>
+    <clipPath id="clip1" clipPathUnits="objectBoundingBox">
+      <rect width=".1" height=".1"/>
+    </clipPath>
+  </defs>
+
+  <rect width="100%" height="100%" fill="lime"/>
+
+  <g transform="scale(1000)">
+    <rect x=".2" y=".2" width=".6" height=".6" fill="red" clip-path="url(#clip1)"/>
+  </g>
+
+  <script>
+    function startTest() {
+      document.addEventListener("MozReftestInvalidate", doTest, false);
+      // in case we're not gecko
+      setTimeout(doTest, 5000);
+    }
+
+    function doTest() {
+      var clip1 = document.getElementById("clip1");
+      clip1.setAttribute("clipPathUnits", "userSpaceOnUse");
+
+      document.documentElement.removeAttribute("class");
+    }
+  </script>
+</svg>
--- a/layout/reftests/svg/dynamic-marker-01.svg
+++ b/layout/reftests/svg/dynamic-marker-01.svg
@@ -1,19 +1,19 @@
 <!--
      Any copyright is dedicated to the Public Domain.
      http://creativecommons.org/publicdomain/zero/1.0/
 -->
 <svg xmlns="http://www.w3.org/2000/svg" version="1.1" class="reftest-wait" onload="startTest()" xmlns:xlink="http://www.w3.org/1999/xlink">
   <title>Testing that dynamic changes to the element for a given ID are reflected in marker</title>
   <!-- From https://bugzilla.mozilla.org/show_bug.cgi?id=309220 -->
   <defs>
-	  <marker id="x" style="overflow: visible;" orient="auto" markerUnits="strokeWidth">
-		  <rect width="100%" height="100%" fill="lime"/>
-	  </marker>
+    <marker id="x" style="overflow: visible;" orient="auto" markerUnits="strokeWidth">
+      <rect width="100%" height="100%" fill="lime"/>
+    </marker>
   </defs>
 	
   <rect width="100%" height="100%" fill="red"/>
 	
   <line id="l1" x1="0" x2="0" y1="0" y2="0" fill="none" stroke="black" stroke-width="1" marker-end="url(#m1)"/>
 
   <script>
   function startTest() {
new file mode 100644
--- /dev/null
+++ b/layout/reftests/svg/dynamic-marker-03.svg
@@ -0,0 +1,41 @@
+<?xml version="1.0" encoding="Windows-1252"?>
+<!--
+     Any copyright is dedicated to the Public Domain.
+     http://creativecommons.org/publicdomain/zero/1.0/
+-->
+<svg xmlns="http://www.w3.org/2000/svg" class="reftest-wait"
+  onload="startTest()">
+
+  <title>Testing that dynamic changes to preserveAspectRatio are reflected in the marker</title>
+  <script>
+<![CDATA[
+