Merge cvs-trunk-mirror -> mozilla-central
authorbenjamin@smedbergs.us
Sat, 13 Oct 2007 21:05:56 -0400
changeset 6925 93c6f56cecb805b71fd1ba9dcd91dd8c06463143
parent 6748 ebd6bf4a0991885cf9b52e8943ef7b71f725e26b (current diff)
parent 6924 5cf5c546440de5ce1d4e602190ae9bf6254ffea5 (diff)
child 6955 ca7f4423d54561612575d1859b5a7af7358af64e
push idunknown
push userunknown
push dateunknown
milestone1.9a9pre
Merge cvs-trunk-mirror -> mozilla-central
client.mk
client.py
config/autoconf.mk.in
config/rules.mk
configure.in
content/svg/content/src/nsSVGAnimatedAngle.cpp
content/svg/content/src/nsSVGAnimatedAngle.h
embedding/browser/cocoa/Makefile.in
embedding/browser/cocoa/NSBrowserView.pbproj/project.pbxproj
embedding/browser/cocoa/res/English.lproj/InfoPlist.strings
embedding/browser/cocoa/res/English.lproj/alert.nib/classes.nib
embedding/browser/cocoa/res/English.lproj/alert.nib/info.nib
embedding/browser/cocoa/res/English.lproj/alert.nib/objects.nib
embedding/browser/cocoa/src/CHBrowserListener.h
embedding/browser/cocoa/src/CHBrowserListener.mm
embedding/browser/cocoa/src/CHBrowserService.h
embedding/browser/cocoa/src/CHBrowserService.mm
embedding/browser/cocoa/src/CHBrowserView.h
embedding/browser/cocoa/src/CHBrowserView.mm
embedding/browser/cocoa/src/CHClickListener.h
embedding/browser/cocoa/src/CHClickListener.mm
embedding/browser/cocoa/src/CHDownloadProgressDisplay.h
embedding/browser/cocoa/src/CHDownloadProgressDisplay.mm
embedding/browser/cocoa/src/NSBrowserView.h
embedding/browser/cocoa/src/NSBrowserView.mm
embedding/browser/cocoa/src/NSString+Utils.h
embedding/browser/cocoa/src/NSString+Utils.mm
embedding/browser/cocoa/src/ProgressDlgController.h
embedding/browser/cocoa/src/ProgressDlgController.mm
embedding/browser/cocoa/src/SaveHeaderSniffer.h
embedding/browser/cocoa/src/SaveHeaderSniffer.mm
embedding/browser/cocoa/src/nsAlertController.h
embedding/browser/cocoa/src/nsAlertController.mm
embedding/browser/cocoa/src/nsCocoaBrowserService.h
embedding/browser/cocoa/src/nsCocoaBrowserService.mm
embedding/browser/cocoa/src/nsDownloadListener.h
embedding/browser/cocoa/src/nsDownloadListener.mm
extensions/inspector/resources/locale/de/search/findFiles.dtd
extensions/inspector/resources/locale/de/search/junkImgs.dtd
js/src/js.cpp
js/src/jsarray.cpp
js/src/jsbool.cpp
js/src/jsdate.cpp
js/src/jsexn.cpp
js/src/jsfun.cpp
js/src/jsinterp.cpp
js/src/jsiter.cpp
js/src/jsmath.cpp
js/src/jsnum.cpp
js/src/jsobj.cpp
js/src/jsparse.cpp
js/src/jsregexp.cpp
js/src/jsscript.cpp
js/src/jsstr.cpp
js/src/jsxml.cpp
js/src/prmjtime.cpp
js/tests/ecma_3/RegExp/regress-103087.js
js/tests/ecma_3/RegExp/regress-220367-002.js
js/tests/ecma_3/RegExp/regress-228087.js
js/tests/ecma_3/RegExp/regress-327170.js
js/tests/ecma_3/extensions/regress-327170.js
js/tests/js1_5/Date/toLocaleFormat.js
js/tests/js1_5/extensions/toLocaleFormat-01.js
js/tests/js1_5/extensions/toLocaleFormat-02.js
layout/reftests/line-breaking/chemical-1-ref.html
layout/reftests/line-breaking/chemical-1.html
layout/reftests/line-breaking/currency-1-ref.html
layout/reftests/line-breaking/currency-1.html
layout/reftests/line-breaking/currency-2-ref.html
layout/reftests/line-breaking/currency-2.html
layout/reftests/line-breaking/datetime-1-ref.html
layout/reftests/line-breaking/datetime-1.html
layout/reftests/line-breaking/hyphens-1-ref.html
layout/reftests/line-breaking/hyphens-1.html
layout/reftests/line-breaking/ja-1-ref.html
layout/reftests/line-breaking/ja-1.html
layout/reftests/line-breaking/ja-2-ref.html
layout/reftests/line-breaking/ja-2.html
layout/reftests/line-breaking/ja-3-ref.html
layout/reftests/line-breaking/ja-3.html
layout/reftests/line-breaking/leaders-1-ref.html
layout/reftests/line-breaking/leaders-1.html
layout/reftests/line-breaking/markup-src-1-ref.html
layout/reftests/line-breaking/markup-src-1.html
layout/reftests/line-breaking/non-breakable-1-ref.html
layout/reftests/line-breaking/non-breakable-1.html
layout/reftests/line-breaking/numerics-1-ref.html
layout/reftests/line-breaking/numerics-1.html
layout/reftests/line-breaking/parentheses-1-ref.html
layout/reftests/line-breaking/parentheses-1.html
layout/reftests/line-breaking/quotationmarks-1-ref.html
layout/reftests/line-breaking/quotationmarks-1.html
layout/reftests/line-breaking/reftest.list
layout/reftests/line-breaking/smileys-1-ref.html
layout/reftests/line-breaking/smileys-1.html
layout/reftests/line-breaking/smileys-2-ref.html
layout/reftests/line-breaking/smileys-2.html
layout/reftests/line-breaking/url-1-ref.html
layout/reftests/line-breaking/url-1.html
layout/reftests/line-breaking/url-2-ref.html
layout/reftests/line-breaking/url-2.html
layout/reftests/line-breaking/url-3-ref.html
layout/reftests/line-breaking/url-3.html
layout/reftests/line-breaking/winpath-1-ref.html
layout/reftests/line-breaking/winpath-1.html
toolkit/crashreporter/client/crashreporter.ini
toolkit/mozapps/handling/content/handling.dtd
toolkit/mozapps/handling/content/handling.properties
widget/public/nsIEventSink.idl
xpfe/components/sidebar/Makefile.in
xpfe/components/sidebar/resources/locale/en-US/customize-panel.dtd
xpfe/components/sidebar/resources/make-panels.pl
xpfe/components/sidebar/src/Makefile.in
xpfe/components/sidebar/src/nsSidebar.js
--- a/Makefile.in
+++ b/Makefile.in
@@ -53,16 +53,17 @@ default alldep all::
 TIERS += base
 
 #
 # tier "base" - basic setup
 #
 tier_base_dirs = \
 	config \
 	build \
+	probes \
 	$(NULL)
 
 include $(topsrcdir)/$(MOZ_BUILD_APP)/build.mk
 
 TIERS += testharness
 
 # test harnesses
 ifdef ENABLE_TESTS
--- a/accessible/build/Makefile.in
+++ b/accessible/build/Makefile.in
@@ -78,17 +78,16 @@ SHARED_LIBRARY_LIBS += ../src/xforms/$(L
 endif
 
 EXTRA_DSO_LIBS = \
 	gkgfx \
 	thebes \
 	$(NULL)
 
 EXTRA_DSO_LDOPTS =           \
-	$(MOZ_FIX_LINK_PATHS)    \
 	$(LIBS_DIR)              \
 	$(EXTRA_DSO_LIBS)        \
 	$(MOZ_UNICHARUTIL_LIBS)  \
 	$(MOZ_COMPONENT_LIBS)    \
 	$(NULL)
 
 ifeq ($(MOZ_WIDGET_TOOLKIT),gtk2)
 EXTRA_DSO_LDOPTS += $(MOZ_GTK2_LIBS)
--- a/accessible/public/nsIAccessibleRetrieval.idl
+++ b/accessible/public/nsIAccessibleRetrieval.idl
@@ -51,17 +51,17 @@ interface nsIDOMDOMStringList;
  * An interface for in-process accessibility clients
  * wishing to get an nsIAccessible or nsIAccessNode for
  * a given DOM node.
  * More documentation at:
  *   http://www.mozilla.org/projects/ui/accessibility
  *
  * @status UNDER_REVIEW
  */
-[scriptable, uuid(56c34b1a-d390-44f4-89c3-6935c0e4e3fa)]
+[scriptable, uuid(244e4c67-a1d3-44f2-9cab-cdaa31b68046)]
 interface nsIAccessibleRetrieval : nsISupports
 {
   /**
    * Return an nsIAccessible for a DOM node in pres shell 0.
    * Create a new accessible of the appropriate type if necessary,
    * or use one from the accessibility cache if it already exists.
    * @param aNode The DOM node to get an accessible for.
    * @return The nsIAccessible for the given DOM node.
@@ -160,16 +160,24 @@ interface nsIAccessibleRetrieval : nsISu
 
   /**
    * Get the type of accessible event as a string.
    *
    * @param aEventType - the accessible event type constant
    * @return - accessible event type presented as human readable string
    */
   AString getStringEventType(in unsigned long aEventType);
+
+  /**
+   * Get the type of accessible relation as a string.
+   *
+   * @param aRelationType - the accessible relation type constant
+   * @return - accessible relation type presented as human readable string
+   */
+  AString getStringRelationType(in unsigned long aRelationType);
 };
 
 
 %{ C++
 
 // for component registration
 // {663CA4A8-D219-4000-925D-D8F66406B626}
 #define NS_ACCESSIBLE_RETRIEVAL_CID \
--- a/accessible/src/atk/nsAppRootAccessible.cpp
+++ b/accessible/src/atk/nsAppRootAccessible.cpp
@@ -63,16 +63,17 @@ static const char sSysPrefService [] =
     "@mozilla.org/system-preference-service;1";
 static const char sAccessibilityKey [] =
     "config.use_system_prefs.accessibility";
 
 /* gail function pointer */
 static guint (* gail_add_global_event_listener) (GSignalEmissionHook listener,
                                                  const gchar *event_type);
 static void (* gail_remove_global_event_listener) (guint remove_listener);
+static void (* gail_remove_key_event_listener) (guint remove_listener);
 static AtkObject * (*gail_get_root) (void);
 
 /* maiutil */
 
 static guint mai_util_add_global_event_listener(GSignalEmissionHook listener,
                                                 const gchar *event_type);
 static void mai_util_remove_global_event_listener(guint remove_listener);
 static guint mai_util_add_key_event_listener(AtkKeySnoopFunc listener,
@@ -225,16 +226,17 @@ mai_util_class_init(MaiUtilClass *klass)
     gpointer data;
 
     data = g_type_class_peek(ATK_TYPE_UTIL);
     atk_class = ATK_UTIL_CLASS(data);
 
     // save gail function pointer
     gail_add_global_event_listener = atk_class->add_global_event_listener;
     gail_remove_global_event_listener = atk_class->remove_global_event_listener;
+    gail_remove_key_event_listener = atk_class->remove_key_event_listener;
     gail_get_root = atk_class->get_root;
 
     atk_class->add_global_event_listener =
         mai_util_add_global_event_listener;
     atk_class->remove_global_event_listener =
         mai_util_remove_global_event_listener;
     atk_class->add_key_event_listener = mai_util_add_key_event_listener;
     atk_class->remove_key_event_listener = mai_util_remove_key_event_listener;
@@ -302,16 +304,22 @@ mai_util_remove_global_event_listener(gu
                 g_hash_table_remove(listener_list, &tmp_idx);
             }
             else {
                 g_warning("Invalid listener hook_id %ld or signal_id %d\n",
                           listener_info->hook_id, listener_info->signal_id);
             }
         }
         else {
+            // atk-bridge is initialized with gail (e.g. yelp)
+            // try gail_remove_global_event_listener
+            if (gail_remove_global_event_listener) {
+                return gail_remove_global_event_listener(remove_listener);
+            }
+
             g_warning("No listener with the specified listener id %d",
                       remove_listener);
         }
     }
     else {
         g_warning("Invalid listener_id %d", remove_listener);
     }
 }
@@ -407,16 +415,22 @@ mai_util_add_key_event_listener (AtkKeyS
     g_hash_table_insert(key_listener_list, GUINT_TO_POINTER (key++),
                         atkKeySnoop.data);
     return key;
 }
 
 static void
 mai_util_remove_key_event_listener (guint remove_listener)
 {
+    if (!key_listener_list) {
+        // atk-bridge is initialized with gail (e.g. yelp)
+        // try gail_remove_key_event_listener
+        return gail_remove_key_event_listener(remove_listener);
+    }
+
     g_hash_table_remove(key_listener_list, GUINT_TO_POINTER (remove_listener));
     if (g_hash_table_size(key_listener_list) == 0) {
         gtk_key_snooper_remove(key_snooper_id);
     }
 }
 
 AtkObject *
 mai_util_get_root(void)
--- a/accessible/src/base/nsAccessNode.cpp
+++ b/accessible/src/base/nsAccessNode.cpp
@@ -220,26 +220,28 @@ nsAccessNode::GetApplicationAccessible()
 
   if (!gApplicationAccessible) {
     nsApplicationAccessibleWrap::PreCreate();
 
     gApplicationAccessible = new nsApplicationAccessibleWrap();
     if (!gApplicationAccessible)
       return nsnull;
 
+    // Addref on create. Will Release in ShutdownXPAccessibility()
     NS_ADDREF(gApplicationAccessible);
 
     nsresult rv = gApplicationAccessible->Init();
     if (NS_FAILED(rv)) {
       NS_RELEASE(gApplicationAccessible);
+      gApplicationAccessible = nsnull;
       return nsnull;
     }
   }
 
-  NS_ADDREF(gApplicationAccessible);
+  NS_ADDREF(gApplicationAccessible);   // Addref because we're a getter
   return gApplicationAccessible;
 }
 
 void nsAccessNode::InitXPAccessibility()
 {
   if (gIsAccessibilityActive) {
     return;
   }
@@ -292,19 +294,22 @@ void nsAccessNode::ShutdownXPAccessibili
   }
   NS_IF_RELEASE(gStringBundle);
   NS_IF_RELEASE(gKeyStringBundle);
   NS_IF_RELEASE(gDoCommandTimer);
   NS_IF_RELEASE(gLastFocusedNode);
   NS_IF_RELEASE(sAccService);
 
   nsApplicationAccessibleWrap::Unload();
-  NS_IF_RELEASE(gApplicationAccessible);
+  ClearCache(gGlobalDocAccessibleCache);
 
-  ClearCache(gGlobalDocAccessibleCache);
+  // Release gApplicationAccessible after everything else is shutdown
+  // so we don't accidently create it again while tearing down root accessibles
+  NS_IF_RELEASE(gApplicationAccessible);
+  gApplicationAccessible = nsnull;  
 
   gIsAccessibilityActive = PR_FALSE;
   NotifyA11yInitOrShutdown();
 }
 
 already_AddRefed<nsIPresShell> nsAccessNode::GetPresShell()
 {
   nsIPresShell *presShell = nsnull;
--- a/accessible/src/base/nsAccessibilityService.cpp
+++ b/accessible/src/base/nsAccessibilityService.cpp
@@ -1051,16 +1051,31 @@ nsAccessibilityService::GetStringEventTy
     aString.AssignLiteral("unknown");
     return NS_OK;
   }
 
   CopyUTF8toUTF16(kEventTypeNames[aEventType], aString);
   return NS_OK;
 }
 
+// nsIAccessibleRetrieval::getStringRelationType()
+NS_IMETHODIMP
+nsAccessibilityService::GetStringRelationType(PRUint32 aRelationType,
+                                              nsAString& aString)
+{
+  if (aRelationType >= NS_ARRAY_LENGTH(kRelationTypeNames)) {
+    aString.AssignLiteral("unknown");
+    return NS_OK;
+  }
+
+  CopyUTF8toUTF16(kRelationTypeNames[aRelationType], aString);
+  return NS_OK;
+}
+
+
 /**
   * GetAccessibleFor - get an nsIAccessible from a DOM node
   */
 
 NS_IMETHODIMP
 nsAccessibilityService::GetAccessibleFor(nsIDOMNode *aNode,
                                          nsIAccessible **aAccessible)
 {
--- a/accessible/src/base/nsAccessibilityService.h
+++ b/accessible/src/base/nsAccessibilityService.h
@@ -350,9 +350,34 @@ static const char kEventTypeNames[][40] 
   "hypertext changed",                       // EVENT_HYPERTEXT_CHANGED
   "hypertext links count changed",           // EVENT_HYPERTEXT_NLINKS_CHANGED
   "object attribute changed",                // EVENT_OBJECT_ATTRIBUTE_CHANGED
   "page changed",                            // EVENT_PAGE_CHANGED
   "internal load",                           // EVENT_INTERNAL_LOAD
   "reorder"                                  // EVENT_REORDER
 };
 
+/**
+ * Map nsIAccessibleRelation constants to strings. Used by
+ * nsIAccessibleRetrieval::getStringRelationType() method.
+ */
+static const char kRelationTypeNames[][20] = {
+  "unknown",             // RELATION_NUL
+  "controlled by",       // RELATION_CONTROLLED_BY
+  "controller for",      // RELATION_CONTROLLER_FOR
+  "label for",           // RELATION_LABEL_FOR
+  "labelled by",         // RELATION_LABELLED_BY
+  "member of",           // RELATION_MEMBER_OF
+  "node child of",       // RELATION_NODE_CHILD_OF
+  "flows to",            // RELATION_FLOWS_TO
+  "flows from",          // RELATION_FLOWS_FROM
+  "subwindow of",        // RELATION_SUBWINDOW_OF
+  "embeds",              // RELATION_EMBEDS
+  "embedded by",         // RELATION_EMBEDDED_BY
+  "popup for",           // RELATION_POPUP_FOR
+  "parent window of",    // RELATION_PARENT_WINDOW_OF
+  "described by",        // RELATION_DESCRIBED_BY
+  "description for",     // RELATION_DESCRIPTION_FOR
+  "default button"       // RELATION_DEFAULT_BUTTON
+};
+
 #endif /* __nsIAccessibilityService_h__ */
+
--- a/accessible/src/base/nsAccessible.cpp
+++ b/accessible/src/base/nsAccessible.cpp
@@ -1720,27 +1720,26 @@ nsIContent* nsAccessible::GetHTMLLabelCo
 
   return nsnull;
 }
 
 nsresult nsAccessible::GetTextFromRelationID(EAriaProperty aIDProperty, nsString &aName)
 {
   // Get DHTML name from content subtree pointed to by ID attribute
   aName.Truncate();
-  nsCOMPtr<nsIContent> content(do_QueryInterface(mDOMNode));
+  nsCOMPtr<nsIContent> content = GetRoleContent(mDOMNode);
   NS_ASSERTION(content, "Called from shutdown accessible");
 
   nsAutoString ids;
   if (!nsAccUtils::GetAriaProperty(content, mWeakShell, aIDProperty, ids)) {
     return NS_ERROR_FAILURE;
   }
   ids.CompressWhitespace(PR_TRUE, PR_TRUE);
 
-  nsCOMPtr<nsIDOMDocument> domDoc;
-  mDOMNode->GetOwnerDocument(getter_AddRefs(domDoc));
+  nsCOMPtr<nsIDOMDocument> domDoc = do_QueryInterface(content->GetOwnerDoc());
   NS_ENSURE_TRUE(domDoc, NS_ERROR_FAILURE);
   
   nsresult rv = NS_ERROR_FAILURE;
 
   // Support idlist as in aaa::labelledby="id1 id2 id3"
   while (!ids.IsEmpty()) {
     nsAutoString id;
     PRInt32 idLength = ids.FindChar(' ');
@@ -2016,64 +2015,65 @@ nsAccessible::GetAttributes(nsIPersisten
 
   nsAccEvent::GetLastEventAttributes(mDOMNode, attributes);
  
   nsresult rv = GetAttributesInternal(attributes);
   NS_ENSURE_SUCCESS(rv, rv);
 
   nsCOMPtr<nsIContent> content = GetRoleContent(mDOMNode);
   nsAutoString id;
+  nsAutoString oldValueUnused;
   if (content && nsAccUtils::GetID(content, id)) {
-    nsAutoString oldValueUnused;
     attributes->SetStringProperty(NS_LITERAL_CSTRING("id"), id, oldValueUnused);
-    // XXX In the future we may need to expose the dynamic content role inheritance chain
-    // through this attribute
-    nsAutoString xmlRole;
-    if (GetARIARole(content, xmlRole)) {
-      attributes->SetStringProperty(NS_LITERAL_CSTRING("xml-roles"), xmlRole, oldValueUnused);          
+  }
+
+  // XXX In the future we may need to expose the dynamic content role inheritance chain
+  // through this attribute
+  nsAutoString xmlRole;
+  if (GetARIARole(content, xmlRole)) {
+    attributes->SetStringProperty(NS_LITERAL_CSTRING("xml-roles"), xmlRole, oldValueUnused);          
+  }
+
+  // Make sure to keep these two arrays in sync
+  PRUint32 ariaPropTypes = nsAccUtils::GetAriaPropTypes(content, mWeakShell);
+  char *ariaPropertyString[] = { "live", "channel", "atomic", "relevant", "datatype", "level",
+                             "posinset", "setsize", "sort", "grab", "dropeffect"};
+  EAriaProperty ariaPropertyEnum[] = { eAria_live, eAria_channel, eAria_atomic, eAria_relevant,
+                                     eAria_datatype, eAria_level, eAria_posinset, eAria_setsize,
+                                     eAria_sort, eAria_grab, eAria_dropeffect};
+  NS_ASSERTION(NS_ARRAY_LENGTH(ariaPropertyString) == NS_ARRAY_LENGTH(ariaPropertyEnum),
+               "ARIA attributes and object property name arrays out of sync");
+  for (PRUint32 index = 0; index < NS_ARRAY_LENGTH(ariaPropertyString); index ++) {
+    nsAutoString value;
+    if (nsAccUtils::GetAriaProperty(content, mWeakShell, ariaPropertyEnum[index], value, ariaPropTypes)) {
+      ToLowerCase(value);
+      attributes->SetStringProperty(nsDependentCString(ariaPropertyString[index]), value, oldValueUnused);    
     }
-
-    // Make sure to keep these two arrays in sync
-    PRUint32 ariaPropTypes = nsAccUtils::GetAriaPropTypes(content, mWeakShell);
-    char *ariaPropertyString[] = { "live", "channel", "atomic", "relevant", "datatype", "level",
-                               "posinset", "setsize", "sort", "grab", "dropeffect"};
-    EAriaProperty ariaPropertyEnum[] = { eAria_live, eAria_channel, eAria_atomic, eAria_relevant,
-                                       eAria_datatype, eAria_level, eAria_posinset, eAria_setsize,
-                                       eAria_sort, eAria_grab, eAria_dropeffect};
-    NS_ASSERTION(NS_ARRAY_LENGTH(ariaPropertyString) == NS_ARRAY_LENGTH(ariaPropertyEnum),
-                 "ARIA attributes and object property name arrays out of sync");
-    for (PRUint32 index = 0; index < NS_ARRAY_LENGTH(ariaPropertyString); index ++) {
-      nsAutoString value;
-      if (nsAccUtils::GetAriaProperty(content, mWeakShell, ariaPropertyEnum[index], value, ariaPropTypes)) {
-        ToLowerCase(value);
-        attributes->SetStringProperty(nsDependentCString(ariaPropertyString[index]), value, oldValueUnused);    
-      }
-    }
-
-    // Get container-foo computed live region properties based on the closest container with
-    // the live region attribute
-    nsAutoString atomic, live, relevant, channel, busy;
-    while (content) {
-      if (relevant.IsEmpty() &&
-          nsAccUtils::GetAriaProperty(content, mWeakShell, eAria_relevant, relevant, ariaPropTypes))
-        attributes->SetStringProperty(NS_LITERAL_CSTRING("container-relevant"), relevant, oldValueUnused);
-      if (live.IsEmpty() &&
-          nsAccUtils::GetAriaProperty(content, mWeakShell, eAria_live, live, ariaPropTypes))
-        attributes->SetStringProperty(NS_LITERAL_CSTRING("container-live"), live, oldValueUnused);
-      if (channel.IsEmpty() &&
-          nsAccUtils::GetAriaProperty(content, mWeakShell, eAria_channel, channel, ariaPropTypes))
-        attributes->SetStringProperty(NS_LITERAL_CSTRING("container-channel"), channel, oldValueUnused);
-      if (atomic.IsEmpty() &&
-          nsAccUtils::GetAriaProperty(content, mWeakShell, eAria_atomic, atomic, ariaPropTypes))
-        attributes->SetStringProperty(NS_LITERAL_CSTRING("container-atomic"), atomic, oldValueUnused);
-      if (busy.IsEmpty() &&
-          nsAccUtils::GetAriaProperty(content, mWeakShell, eAria_busy, busy, ariaPropTypes))
-        attributes->SetStringProperty(NS_LITERAL_CSTRING("container-busy"), busy, oldValueUnused);
-      content = content->GetParent();
-    }
+  }
+
+  // Get container-foo computed live region properties based on the closest container with
+  // the live region attribute
+  nsAutoString atomic, live, relevant, channel, busy;
+  while (content) {
+    if (relevant.IsEmpty() &&
+        nsAccUtils::GetAriaProperty(content, mWeakShell, eAria_relevant, relevant, ariaPropTypes))
+      attributes->SetStringProperty(NS_LITERAL_CSTRING("container-relevant"), relevant, oldValueUnused);
+    if (live.IsEmpty() &&
+        nsAccUtils::GetAriaProperty(content, mWeakShell, eAria_live, live, ariaPropTypes))
+      attributes->SetStringProperty(NS_LITERAL_CSTRING("container-live"), live, oldValueUnused);
+    if (channel.IsEmpty() &&
+        nsAccUtils::GetAriaProperty(content, mWeakShell, eAria_channel, channel, ariaPropTypes))
+      attributes->SetStringProperty(NS_LITERAL_CSTRING("container-channel"), channel, oldValueUnused);
+    if (atomic.IsEmpty() &&
+        nsAccUtils::GetAriaProperty(content, mWeakShell, eAria_atomic, atomic, ariaPropTypes))
+      attributes->SetStringProperty(NS_LITERAL_CSTRING("container-atomic"), atomic, oldValueUnused);
+    if (busy.IsEmpty() &&
+        nsAccUtils::GetAriaProperty(content, mWeakShell, eAria_busy, busy, ariaPropTypes))
+      attributes->SetStringProperty(NS_LITERAL_CSTRING("container-busy"), busy, oldValueUnused);
+    content = content->GetParent();
   }
 
   if (!nsAccUtils::HasAccGroupAttrs(attributes)) {
     // The role of an accessible can be pointed by ARIA attribute but ARIA
     // posinset, level, setsize may be skipped. Therefore we calculate here
     // these properties to map them into description.
 
     // If accessible is invisible we don't want to calculate group ARIA
--- a/accessible/src/base/nsCaretAccessible.cpp
+++ b/accessible/src/base/nsCaretAccessible.cpp
@@ -240,18 +240,18 @@ nsCaretAccessible::GetCaretRect(nsIWidge
 
   nsCOMPtr<nsIDOMNode> lastNodeWithCaret;
   lastAccessNode->GetDOMNode(getter_AddRefs(lastNodeWithCaret));
   NS_ENSURE_TRUE(lastNodeWithCaret, caretRect);
 
   nsCOMPtr<nsIPresShell> presShell = mRootAccessible->GetPresShellFor(lastNodeWithCaret);
   NS_ENSURE_TRUE(presShell, caretRect);
 
-  nsICaret *caret;
-  presShell->GetCaret(&caret);
+  nsCOMPtr<nsICaret> caret;
+  presShell->GetCaret(getter_AddRefs(caret));
   NS_ENSURE_TRUE(caret, caretRect);
 
   PRBool isCollapsed;
   nsIView *view;
   nsCOMPtr<nsISelection> caretSelection(do_QueryReferent(mLastUsedSelection));
   NS_ENSURE_TRUE(caretSelection, caretRect);
   
   caret->GetCaretCoordinates(nsICaret::eRenderingViewCoordinates, caretSelection,
--- a/accessible/src/base/nsDocAccessible.cpp
+++ b/accessible/src/base/nsDocAccessible.cpp
@@ -219,17 +219,19 @@ NS_IMETHODIMP nsDocAccessible::GetRole(P
 NS_IMETHODIMP nsDocAccessible::GetValue(nsAString& aValue)
 {
   return GetURL(aValue);
 }
 
 NS_IMETHODIMP 
 nsDocAccessible::GetDescription(nsAString& aDescription)
 {
-  aDescription.Truncate();
+  nsAutoString description;
+  GetTextFromRelationID(eAria_describedby, description);
+  aDescription = description;
   return NS_OK;
 }
 
 NS_IMETHODIMP
 nsDocAccessible::GetState(PRUint32 *aState, PRUint32 *aExtraState)
 {
   // nsAccessible::GetState() always fail for document accessible.
   nsAccessible::GetState(aState, aExtraState);
@@ -679,18 +681,19 @@ nsresult nsDocAccessible::AddEventListen
     if (commandManager) {
       commandManager->AddCommandObserver(this, "obs_documentCreated");
     }
   }
 
   nsCOMPtr<nsIDocShellTreeItem> rootTreeItem;
   docShellTreeItem->GetRootTreeItem(getter_AddRefs(rootTreeItem));
   if (rootTreeItem) {
-    GetDocAccessibleFor(rootTreeItem, PR_TRUE); // Ensure root accessible is created;
-    nsRefPtr<nsRootAccessible> rootAccessible = GetRootAccessible();
+    nsCOMPtr<nsIAccessibleDocument> rootAccDoc =
+      GetDocAccessibleFor(rootTreeItem, PR_TRUE); // Ensure root accessible is created;
+    nsRefPtr<nsRootAccessible> rootAccessible = GetRootAccessible(); // Then get it as ref ptr
     NS_ENSURE_TRUE(rootAccessible, NS_ERROR_FAILURE);
     nsRefPtr<nsCaretAccessible> caretAccessible = rootAccessible->GetCaretAccessible();
     if (caretAccessible) {
       nsCOMPtr<nsIDOMDocument> domDoc = do_QueryInterface(mDocument);
       caretAccessible->AddDocSelectionListener(domDoc);
     }
   }
 
--- a/accessible/src/base/nsRootAccessible.cpp
+++ b/accessible/src/base/nsRootAccessible.cpp
@@ -912,25 +912,26 @@ nsRootAccessible::Init()
   NS_ENSURE_STATE(root);
 
   root->AddRootAccessible(this);
   return NS_OK;
 }
 
 NS_IMETHODIMP nsRootAccessible::Shutdown()
 {
+  // Called manually or by nsAccessNode::LastRelease()
+  if (!mWeakShell) {
+    return NS_OK;  // Already shutdown
+  }
+
   nsRefPtr<nsApplicationAccessibleWrap> root = GetApplicationAccessible();
   NS_ENSURE_STATE(root);
 
   root->RemoveRootAccessible(this);
 
-  // Called manually or by nsAccessNode::LastRelease()
-  if (!mWeakShell) {
-    return NS_OK;  // Already shutdown
-  }
   mCurrentARIAMenubar = nsnull;
 
   if (mFireFocusTimer) {
     mFireFocusTimer->Cancel();
     mFireFocusTimer = nsnull;
   }
 
   return nsDocAccessibleWrap::Shutdown();
--- a/accessible/src/html/nsHyperTextAccessible.cpp
+++ b/accessible/src/html/nsHyperTextAccessible.cpp
@@ -1062,16 +1062,25 @@ nsHyperTextAccessible::GetAttributesInte
     headLevel = 6;
 
   if (headLevel) {
     nsAutoString strHeadLevel;
     strHeadLevel.AppendInt(headLevel);
     nsAccUtils::SetAccAttr(aAttributes, nsAccessibilityAtoms::level,
                            strHeadLevel);
   }
+  
+  // Indicate when the current object uses block-level formatting
+  // via formatting: block
+  nsIFrame *frame = GetFrame();
+  if (frame && frame->GetType() == nsAccessibilityAtoms::blockFrame) {
+    nsAutoString oldValueUnused;
+    aAttributes->SetStringProperty(NS_LITERAL_CSTRING("formatting"), NS_LITERAL_STRING("block"),
+                                   oldValueUnused);
+  }
 
   return  NS_OK;
 }
 
 /*
  * Given an offset, the x, y, width, and height values are filled appropriately.
  */
 NS_IMETHODIMP nsHyperTextAccessible::GetCharacterExtents(PRInt32 aOffset, PRInt32 *aX, PRInt32 *aY,
--- a/allmakefiles.sh
+++ b/allmakefiles.sh
@@ -58,16 +58,17 @@ fi
 add_makefiles "
 Makefile
 build/Makefile
 build/unix/Makefile
 config/Makefile
 config/autoconf.mk
 config/mkdepend/Makefile
 config/doxygen.cfg
+probes/Makefile
 extensions/Makefile
 "
 
 #
 # Application-specific makefiles
 #
 if test -f "${srcdir}/${MOZ_BUILD_APP}/makefiles.sh"; then
   . "${srcdir}/${MOZ_BUILD_APP}/makefiles.sh"
--- a/browser/app/profile/firefox.js
+++ b/browser/app/profile/firefox.js
@@ -571,8 +571,11 @@ pref("browser.sessionstore.max_tabs_undo
 // allow META refresh by default
 pref("accessibility.blockautorefresh", false);
 
 // import bookmarks.html into Places bookmarks
 pref("browser.places.importBookmarksHTML", true);
 
 // Show infobar on chromeless windows
 pref("browser.warn_chromeless_window.infobar", false);
+
+// if false, will add the "Places" folder to the personal toolbar
+pref("browser.places.createdDefaultQueries", false);
--- a/browser/base/content/browser-contentPrefSink.js
+++ b/browser/base/content/browser-contentPrefSink.js
@@ -70,67 +70,46 @@ var ContentPrefSink = {
     return this;
   },
 
 
   //**************************************************************************//
   // Initialization & Destruction
 
   init: function ContentPrefSink_init() {
-    gBrowser.addProgressListener(this, Ci.nsIWebProgress.NOTIFY_STATE_DOCUMENT);
     gBrowser.addEventListener("DOMContentLoaded", this, false);
     // XXX Should we also listen for pageshow and/or load?
   },
 
   destroy: function ContentPrefSink_destroy() {
     gBrowser.removeEventListener("DOMContentLoaded", this, false);
-    gBrowser.removeProgressListener(this);
 
     // Delete references to XPCOM components to make sure we don't leak them
     // (although we haven't observed leakage in tests).  Also delete references
     // in _observers and _genericObservers to avoid cycles with those that
     // refer to us and don't remove themselves from those observer pools.
     for (var i in this) {
       try { this[i] = null }
       // Ignore "setting a property that has only a getter" exceptions.
       catch(ex) {}
     }
   },
 
 
   //**************************************************************************//
   // Event Handlers
 
-  // nsIWebProgressListener
-
-  onLocationChange: function ContentPrefSink_onLocationChange(progress, request, uri) {
-    // Catch exceptions until bug 376222 gets fixed so that we don't hork
-    // other progress listeners if our code throws an exception.
-    try {
-      this._handleLocationChanged(uri);
-    }
-    catch(ex) {
-      Components.utils.reportError(ex);
-    }
-  },
-  onStateChange: function ContentPrefSink_onStateChange(progress, request, flags, status) {},
-  onProgressChange: function ContentPrefSink_onProgressChange(progress, request, curSelfProgress,
-                                                              maxSelfProgress, curTotalProgress,
-                                                              maxTotalProgress) {},
-  onStatusChange: function ContentPrefSink_onStatusChange(progress, request, status, message) {},
-  onSecurityChange: function ContentPrefSink_onSecurityChange(progress, request, state) {},
-
   // nsIDOMEventListener
 
   handleEvent: function ContentPrefSink_handleEvent(event) {
     // The only events we handle are DOMContentLoaded events.
     this._handleDOMContentLoaded(event);
   },
 
-  _handleLocationChanged: function ContentPrefSink__handleLocationChanged(uri) {
+  handleLocationChanged: function ContentPrefSink_handleLocationChanged(uri) {
     if (!uri)
       return;
 
     var prefs = this._cps.getPrefs(uri);
 
     for (var name in this._observers) {
       var value = prefs.hasKey(name) ? prefs.get(name) : undefined;
       for each (var observer in this._observers[name])
--- a/browser/base/content/browser-menubar.inc
+++ b/browser/base/content/browser-menubar.inc
@@ -370,17 +370,17 @@
   <menu id="bookmarksMenu" 
         label="&bookmarksMenu.label;" accesskey="&bookmarksMenu.accesskey;"
         ondragenter="PlacesMenuDNDController.onBookmarksMenuDragEnter(event);"
         ondragdrop="nsDragAndDrop.drop(event, BookmarksMenuDropHandler);"
         ondragover="nsDragAndDrop.dragOver(event, BookmarksMenuDropHandler);"
         ondragexit="PlacesMenuDNDController.onDragExit(event);">
     <menupopup id="bookmarksMenuPopup"
                type="places" asyncinit="true"
-               place="place:folder=2&amp;group=3&amp;expandQueries=1"
+               place="place:folder=2&amp;expandQueries=1"
                context="placesContext"
                openInTabs="children"
                oncommand="BookmarksEventHandler.onCommand(event);"
                onclick="BookmarksEventHandler.onClick(event);"
                onpopupshowing="BookmarksEventHandler.onPopupShowing(event);">
       <menuitem label="&addCurPageAsCmd.label;" 
                 command="Browser:AddBookmarkAs" key="addBookmarkAsKb"/>
       <menuitem id="subscribeToPageMenuitem"
--- a/browser/base/content/browser.js
+++ b/browser/base/content/browser.js
@@ -309,16 +309,127 @@ function initBookmarksToolbar() {
   var bt = document.getElementById("bookmarksBarContent");
   if (!bt)
     return;
 
   bt.place =
     PlacesUtils.getQueryStringForFolder(PlacesUtils.bookmarks.toolbarFolder);
 }
 
+/**
+ * Add the special "Places" folder (with some special queries) to the personal toolbar folder
+ */
+function initPlacesDefaultQueries() {
+  var createdDefaultQueries = false;
+  try {
+    createdDefaultQueries = gPrefService.getBoolPref("browser.places.createdDefaultQueries");
+  } catch(ex) {}
+
+  if (createdDefaultQueries)
+    return;
+
+  var bmsvc = PlacesUtils.bookmarks;
+  var callback = {
+    runBatched: function() {
+      var placesFolderTitle =
+        PlacesUtils.getString("placesFolderTitle");
+      var recentlyCreatedBookmarksTitle =
+        PlacesUtils.getString("recentlyCreatedBookmarksTitle");
+      var recentlyVisitedBookmarksTitle =
+        PlacesUtils.getString("recentlyVisitedBookmarksTitle");
+      var mostVisitedBookmarksTitle =
+        PlacesUtils.getString("mostVisitedBookmarksTitle");
+      var recentlyUsedTagsTitle =
+        PlacesUtils.getString("recentlyUsedTagsTitle");
+      var mostUsedTagsTitle =
+        PlacesUtils.getString("mostUsedTagsTitle");
+      var mostVisitedSitesTitle =
+        PlacesUtils.getString("mostVisitedSitesTitle");
+
+      var bookmarksRoot = PlacesUtils.bookmarksRootId;
+      var unfiledRoot = PlacesUtils.unfiledRootId;
+      var tagRoot = PlacesUtils.tagRootId;
+      var defaultIndex = bmsvc.DEFAULT_INDEX;
+
+      // index = 0, make it the first folder
+      var placesFolder = bmsvc.createFolder(bmsvc.toolbarFolder,
+                                            placesFolderTitle,
+                                            0);
+
+      // XXX should this be a pref?  see bug #399268
+      var maxResults = 10;
+
+      // exclude queries so that user created "saved searches" 
+      // and these queries (added automatically) are excluded
+      var recentlyCreatedBookmarksItem = bmsvc.insertBookmark(placesFolder,
+        IO.newURI("place:folder=" + bookmarksRoot + "&folder=" + unfiledRoot +
+            "&queryType=" + Ci.nsINavHistoryQueryOptions.QUERY_TYPE_BOOKMARKS +
+            "&sort=" + 
+            Ci.nsINavHistoryQueryOptions.SORT_BY_DATEADDED_DESCENDING +
+            "&excludeItemIfParentHasAnnotation=livemark%2FfeedURI" +
+            "&maxResults=" + maxResults +
+            "&excludeQueries=1"),
+            defaultIndex, recentlyCreatedBookmarksTitle);
+
+      var recentlyVisitedBookmarksItem = bmsvc.insertBookmark(placesFolder,
+        IO.newURI("place:folder=" + bookmarksRoot + "&folder=" + unfiledRoot +
+            "&queryType=" + Ci.nsINavHistoryQueryOptions.QUERY_TYPE_BOOKMARKS +
+            "&sort=" + Ci.nsINavHistoryQueryOptions.SORT_BY_DATE_DESCENDING + 
+            "&minVisits=1&maxResults=" + maxResults),
+            defaultIndex, recentlyVisitedBookmarksTitle);
+
+      var mostVisitedBookmarksItem = bmsvc.insertBookmark(placesFolder,
+        IO.newURI("place:folder=" + bookmarksRoot + "&folder=" + unfiledRoot +
+            "&queryType=" + Ci.nsINavHistoryQueryOptions.QUERY_TYPE_BOOKMARKS +
+            "&sort=" + 
+            Ci.nsINavHistoryQueryOptions.SORT_BY_VISITCOUNT_DESCENDING + 
+            "&minVisits=1&maxResults=" + maxResults),
+            defaultIndex, mostVisitedBookmarksTitle);
+
+      var recentlyUsedTagsItem = bmsvc.insertBookmark(placesFolder,
+        IO.newURI("place:folder=" + tagRoot +
+            "&group=" + Ci.nsINavHistoryQueryOptions.GROUP_BY_FOLDER +
+            "&queryType=" + Ci.nsINavHistoryQueryOptions.QUERY_TYPE_BOOKMARKS +
+            "&applyOptionsToContainers=1" +  
+            "&sort=" + 
+            Ci.nsINavHistoryQueryOptions.SORT_BY_DATEADDED_DESCENDING + 
+            "&resolveNullBookmarkTitles=1" +
+            "&maxResults=" + maxResults),
+            defaultIndex, recentlyUsedTagsTitle);
+
+      var mostUsedTagsItem = bmsvc.insertBookmark(placesFolder,
+        IO.newURI("place:folder=" + tagRoot + 
+            "&group=" + Ci.nsINavHistoryQueryOptions.GROUP_BY_FOLDER +
+            "&queryType=" + Ci.nsINavHistoryQueryOptions.QUERY_TYPE_BOOKMARKS +
+            "&applyOptionsToContainers=1" +
+            "&sort=" + Ci.nsINavHistoryQueryOptions.SORT_BY_COUNT_DESCENDING + 
+            "&resolveNullBookmarkTitles=1" +
+            "&maxResults=" + maxResults),
+            defaultIndex, mostUsedTagsTitle);
+
+      var mostVisitedSitesItem = bmsvc.insertBookmark(placesFolder,
+        IO.newURI("place:queryType=" + 
+            Ci.nsINavHistoryQueryOptions.QUERY_TYPE_HISTORY +
+            "&sort=" + 
+            Ci.nsINavHistoryQueryOptions.SORT_BY_VISITCOUNT_DESCENDING + 
+            "&maxResults=" + maxResults),
+            defaultIndex, mostVisitedSitesTitle);
+    }
+  }
+  
+  try {
+    bmsvc.runInBatchMode(callback, null);
+  } finally {
+    // We need to persist this preference change, since we want to
+    // check it at next app start even if the browser exits abruptly
+    gPrefService.setBoolPref("browser.places.createdDefaultQueries", true);
+    gPrefService.savePrefFile(null);
+  }
+}
+
 const gSessionHistoryObserver = {
   observe: function(subject, topic, data)
   {
     if (topic != "browser:purge-session-history")
       return;
 
     var backCommand = document.getElementById("Browser:Back");
     backCommand.setAttribute("disabled", "true");
@@ -954,16 +1065,17 @@ function delayedStartup()
   Cc["@mozilla.org/login-manager;1"].getService(Ci.nsILoginManager);
 
   if (gMustLoadSidebar) {
     var sidebar = document.getElementById("sidebar");
     var sidebarBox = document.getElementById("sidebar-box");
     sidebar.setAttribute("src", sidebarBox.getAttribute("src"));
   }
 
+  initPlacesDefaultQueries();
   initBookmarksToolbar();
   PlacesUtils.bookmarks.addObserver(gBookmarksObserver, false);
   PlacesStarButton.init();
 
   // called when we go into full screen, even if it is
   // initiated by a web page script
   window.addEventListener("fullscreen", onFullScreen, true);
 
@@ -1210,24 +1322,29 @@ function nonBrowserWindowStartup()
 }
 
 function nonBrowserWindowDelayedStartup()
 {
   // init global pref service
   gPrefService = Components.classes["@mozilla.org/preferences-service;1"]
                            .getService(Components.interfaces.nsIPrefBranch2);
 
+  // initialise the offline listener
+  BrowserOffline.init();
+  
   // Set up Sanitize Item
   gSanitizeListener = new SanitizeListener();
 }
 
 function nonBrowserWindowShutdown()
 {
   if (gSanitizeListener)
     gSanitizeListener.shutdown();
+
+  BrowserOffline.uninit();
 }
 #endif
 
 function AutoHideTabbarPrefListener()
 {
   this.toggleAutoHideTabbar();
 }
 
@@ -2658,44 +2775,47 @@ const DOMLinkHandler = {
             }
           }
           break;
         case "icon":
           if (!iconAdded) {
             if (!gPrefService.getBoolPref("browser.chrome.site_icons"))
               break;
 
-            try {
-              var contentPolicy = Cc["@mozilla.org/layout/content-policy;1"].
-                                  getService(Ci.nsIContentPolicy);
-            } catch(e) {
-              break; // Refuse to load if we can't do a security check.
-            }
-
             var targetDoc = link.ownerDocument;
             var ios = Cc["@mozilla.org/network/io-service;1"].
                       getService(Ci.nsIIOService);
             var uri = ios.newURI(link.href, targetDoc.characterSet, null);
 
+            if (gBrowser.isFailedIcon(uri))
+              break;
+
             // Verify that the load of this icon is legal.
             // error pages can load their favicon, to be on the safe side,
             // only allow chrome:// favicons
             const aboutNeterr = "about:neterror?";
             if (targetDoc.documentURI.substr(0, aboutNeterr.length) != aboutNeterr ||
                 !uri.schemeIs("chrome")) {
               var ssm = Cc["@mozilla.org/scriptsecuritymanager;1"].
                         getService(Ci.nsIScriptSecurityManager);
               try {
                 ssm.checkLoadURIWithPrincipal(targetDoc.nodePrincipal, uri,
                                               Ci.nsIScriptSecurityManager.DISALLOW_SCRIPT);
               } catch(e) {
                 break;
               }
             }
 
+            try {
+              var contentPolicy = Cc["@mozilla.org/layout/content-policy;1"].
+                                  getService(Ci.nsIContentPolicy);
+            } catch(e) {
+              break; // Refuse to load if we can't do a security check.
+            }
+
             // Security says okay, now ask content policy
             if (contentPolicy.shouldLoad(Ci.nsIContentPolicy.TYPE_IMAGE,
                                          uri, targetDoc.documentURIObject,
                                          link, link.type, null)
                                          != Ci.nsIContentPolicy.ACCEPT)
               break;
 
             var browserIndex = gBrowser.getBrowserIndexForDocument(targetDoc);
@@ -3296,32 +3416,19 @@ nsBrowserStatusHandler.prototype =
     if (this.statusText != text) {
       this.statusTextField.label = text;
       this.statusText = text;
     }
   },
   
   onLinkIconAvailable : function(aBrowser)
   {
-    if (gProxyFavIcon &&
-        gBrowser.mCurrentBrowser == aBrowser &&
+    if (gProxyFavIcon && gBrowser.mCurrentBrowser == aBrowser &&
         gBrowser.userTypedValue === null)
-    {
-      // update the favicon in the URL bar
-      PageProxySetIcon(aBrowser.mIconURL);
-    }
-
-    // Save this favicon in the favicon service
-    if (aBrowser.mIconURL) {
-      var faviconService = Components.classes["@mozilla.org/browser/favicon-service;1"]
-        .getService(Components.interfaces.nsIFaviconService);
-      var uri = Components.classes["@mozilla.org/network/io-service;1"]
-        .getService(Components.interfaces.nsIIOService).newURI(aBrowser.mIconURL, null, null);
-      faviconService.setAndLoadFaviconForPage(aBrowser.currentURI, uri, false);
-    }
+      PageProxySetIcon(aBrowser.mIconURL); // update the favicon in the URL bar
   },
 
   onProgressChange : function (aWebProgress, aRequest,
                                aCurSelfProgress, aMaxSelfProgress,
                                aCurTotalProgress, aMaxTotalProgress)
   {
     if (aMaxTotalProgress > 0) {
       // This is highly optimized.  Don't touch this code unless
@@ -3578,16 +3685,25 @@ nsBrowserStatusHandler.prototype =
     // See bug 358202, when tabs are switched during a drag operation,
     // timers don't fire on windows (bug 203573)
     if (aRequest) {
       var self = this;
       setTimeout(function() { self.asyncUpdateUI(); }, 0);
     } 
     else
       this.asyncUpdateUI();
+
+    // Catch exceptions until bug 376222 gets fixed so we don't hork
+    // other progress listeners if this call throws an exception.
+    try {
+      ContentPrefSink.handleLocationChanged(aLocationURI);
+    }
+    catch(ex) {
+      Components.utils.reportError(ex);
+    }
   },
   
   asyncUpdateUI : function () {
     FeedHandler.updateFeeds();
     BrowserSearch.updateSearchButton();
   },
 
   onStatusChange : function(aWebProgress, aRequest, aStatus, aMessage)
--- a/browser/base/content/browser.xul
+++ b/browser/base/content/browser.xul
@@ -236,18 +236,17 @@
             <deck id="page-proxy-deck" onclick="PageProxyClickHandler(event);">
               <image id="page-proxy-button"
                      ondraggesture="PageProxyDragGesture(event);"
                      tooltiptext="&proxyIcon.tooltip;"/>
               <image id="page-proxy-favicon" validate="never"
                      ondraggesture="PageProxyDragGesture(event);"
                      onload="this.parentNode.selectedIndex = 1;
                              event.stopPropagation();"
-                     onerror="gBrowser.addToMissedIconCache(this.src);
-                              this.removeAttribute('src');
+                     onerror="this.removeAttribute('src');
                               this.parentNode.selectedIndex = 0;"
                      tooltiptext="&proxyIcon.tooltip;"/>
             </deck>
             <hbox id="urlbar-icons">
               <button type="menu"
                       style="-moz-user-focus: none"
                       class="plain"
                       id="feed-button"
--- a/browser/base/content/sanitize.js
+++ b/browser/base/content/sanitize.js
@@ -135,17 +135,20 @@ Sanitizer.prototype = {
                              .getService(Components.interfaces.nsIObserverService);
           os.notifyObservers(null, "browser:purge-session-history", "");
         }
         catch (e) { }
         
         // Clear last URL of the Open Web Location dialog
         var prefs = Components.classes["@mozilla.org/preferences-service;1"]
                               .getService(Components.interfaces.nsIPrefBranch2);
-        prefs.clearUserPref("general.open_location.last_url");
+        try {
+          prefs.clearUserPref("general.open_location.last_url");
+        }
+        catch (e) { }
       },
       
       get canClear()
       {
         // bug 347231: Always allow clearing history due to dependencies on
         // the browser:purge-session-history notification. (like error console)
         return true;
       }
--- a/browser/base/content/tabbrowser.xml
+++ b/browser/base/content/tabbrowser.xml
@@ -114,18 +114,17 @@
                     onclick="this.parentNode.parentNode.parentNode.onTabClick(event);"
                     xbl:inherits="onnewtab"
                     ondblclick="this.parentNode.parentNode.parentNode.onTabBarDblClick(event);"
                     onclosetab="var node = this.parentNode;
                                 while (node.localName != 'tabbrowser')
                                   node = node.parentNode;
                                 node.removeCurrentTab();">
             <xul:tab selected="true" validate="never"
-                     onerror="this.parentNode.parentNode.parentNode.parentNode.addToMissedIconCache(this.getAttribute('image'));
-                              this.removeAttribute('image');"
+                     onerror="this.removeAttribute('image');"
                      maxwidth="250" width="0" minwidth="100" flex="100"
                      class="tabbrowser-tab" label="&untitledTab;" crop="end"/>
           </xul:tabs>
         </xul:hbox>
         <xul:tabpanels flex="1" class="plain" selectedIndex="0" anonid="panelcontainer">
           <xul:notificationbox flex="1">
             <xul:browser flex="1" type="content-primary" message="true" disablehistory="true"
                          xbl:inherits="tooltip=contenttooltip,contextmenu=contentcontextmenu,autocompletepopup"/>
@@ -139,16 +138,20 @@
         Components.classes['@mozilla.org/preferences-service;1']
                   .getService(Components.interfaces.nsIPrefService)
                   .getBranch(null);
       </field>
       <field name="mURIFixup" readonly="true">
         Components.classes["@mozilla.org/docshell/urifixup;1"]
                   .getService(Components.interfaces.nsIURIFixup);
       </field>
+      <field name="mFaviconService" readonly="true">
+        Components.classes["@mozilla.org/browser/favicon-service;1"]
+                  .getService(Components.interfaces.nsIFaviconService);
+      </field>
       <field name="mTabBox" readonly="true">
         document.getAnonymousElementByAttribute(this, "anonid", "tabbox");
       </field>
       <field name="mTabDropIndicatorBar">
         this.mTabBox.childNodes[0]
       </field>
       <field name="mStrip" readonly="true">
         document.getAnonymousElementByAttribute(this, "anonid", "strip");
@@ -184,19 +187,16 @@
         new Array()
       </field>
       <field name="mTabbedMode">
         false
       </field>
       <field name="mIsBusy">
         false
       </field>
-      <field name="mMissedIconCache">
-        null
-      </field>
       <field name="mContextTab">
         null
       </field>
       <field name="arrowKeysShouldWrap" readonly="true">
 #ifdef XP_MACOSX
         true
 #else
         false
@@ -488,16 +488,26 @@
       <method name="setIcon">
         <parameter name="aTab"/>
         <parameter name="aURI"/>
         <body>
           <![CDATA[
             var browser = this.getBrowserForTab(aTab);
             browser.mIconURL = aURI;
 
+            if (aURI) {
+              if (!(aURI instanceof Components.interfaces.nsIURI)) {
+                var ios = Components.classes["@mozilla.org/network/io-service;1"]
+                                    .getService(Components.interfaces.nsIIOService);
+                aURI = ios.newURI(aURI, null, null);
+              }
+              this.mFaviconService.setAndLoadFaviconForPage(browser.currentURI,
+                                                            aURI, false);
+            }
+
             this.updateIcon(aTab);
 
             for (var i = 0; i < this.mProgressListeners.length; i++) {
               var p = this.mProgressListeners[i];
               if ('onLinkIconAvailable' in p)
                 p.onLinkIconAvailable(browser);
             }
           ]]>
@@ -547,71 +557,34 @@
                     return;
 
                   this.setIcon(aTab, browser.currentURI.spec);
                 } catch (e) { }
               }
             }
             else if (this.shouldLoadFavIcon(browser.currentURI)) {
               var url = browser.currentURI.prePath + "/favicon.ico";
-              if (!this.isIconKnownMissing(url))
+              if (!this.isFailedIcon(url))
                 this.setIcon(aTab, url);
             }
           ]]>
         </body>
       </method>
 
-      <method name="addToMissedIconCache">
+      <method name="isFailedIcon">
         <parameter name="aURI"/>
         <body>
           <![CDATA[
-            var entry = this.openCacheEntry(aURI, Components.interfaces.nsICache.ACCESS_READ_WRITE);
-            if (!entry)
-              return;
-
-            if (entry.accessGranted == Components.interfaces.nsICache.ACCESS_WRITE)
-              // It's a new entry.  Just write a bit of metadata in to the entry.
-              entry.setMetaDataElement("Icon", "Missed");
-            entry.markValid();
-            entry.close();
-          ]]>
-        </body>
-      </method>
-
-      <method name="openCacheEntry">
-        <parameter name="key"/>
-        <parameter name="access"/>
-        <body>
-          <![CDATA[
-            try {
-              if (!this.mMissedIconCache) {
-                var cacheService = Components.classes['@mozilla.org/network/cache-service;1'].getService(Components.interfaces.nsICacheService);
-                this.mMissedIconCache = cacheService.createSession("MissedIconCache", Components.interfaces.nsICache.STORE_ANYWHERE, true);
-                if (!this.mMissedIconCache)
-                  return null;
-              }
-              return this.mMissedIconCache.openCacheEntry(key, access, true);
+            if (!(aURI instanceof Components.interfaces.nsIURI)) {
+              var ios = Components.classes["@mozilla.org/network/io-service;1"]
+                                  .getService(Components.interfaces.nsIIOService);
+              aURI = ios.newURI(aURI, null, null);
             }
-            catch (e) {
-              return null;
-            }
-          ]]>
-        </body>
-      </method>
-
-      <method name="isIconKnownMissing">
-        <parameter name="key"/>
-        <body>
-          <![CDATA[
-            var e = this.openCacheEntry(key, Components.interfaces.nsICache.ACCESS_READ);
-            if (e) {
-                e.close();
-                return true;
-            }
-            return false;
+
+            return this.mFaviconService.isFailedFavicon(aURI);
           ]]>
         </body>
       </method>
 
       <method name="updateTitlebar">
         <body>
           <![CDATA[
             var newTitle = "";
@@ -1127,17 +1100,17 @@
               t.setAttribute("label", aURI);
 
             t.setAttribute("crop", "end");
             t.maxWidth = this.mTabContainer.mTabMaxWidth;
             t.minWidth = this.mTabContainer.mTabMinWidth;
             t.width = 0;
             t.setAttribute("flex", "100");
             t.setAttribute("validate", "never");
-            t.setAttribute("onerror", "this.parentNode.parentNode.parentNode.parentNode.addToMissedIconCache(this.getAttribute('image')); this.removeAttribute('image');");
+            t.setAttribute("onerror", "this.removeAttribute('image');");
             t.className = "tabbrowser-tab";
 
             this.mTabContainer.appendChild(t);
 
             if (document.defaultView
                         .getComputedStyle(this.mTabContainer, "")
                         .direction == "rtl") {
               /* In RTL UI, the tab is visually added to the left side of the
--- a/browser/components/places/content/bookmarkProperties.xul
+++ b/browser/components/places/content/bookmarkProperties.xul
@@ -159,16 +159,16 @@
         class="placesTree"
         collapsed="true"
         flex="1"
         type="places"
         height="150"
         persist="height"
         onselect="BookmarkPropertiesPanel.onFolderTreeSelect();"
         showRoot="true"
-        place="place:folder=2&amp;group=3&amp;excludeItems=1&amp;excludeQueries=1&amp;excludeReadOnlyFolders=1"
+        place="place:folder=2&amp;excludeItems=1&amp;excludeQueries=1&amp;excludeReadOnlyFolders=1"
         hidecolumnpicker="true">
     <treecols>
       <treecol id="title" flex="1" primary="true" hideheader="true"/>
     </treecols>
     <treechildren id="placesListChildren" view="placesList" flex="1"/>
   </tree>
 </dialog>
--- a/browser/components/places/content/controller.js
+++ b/browser/components/places/content/controller.js
@@ -35,17 +35,17 @@
  * 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 ***** */
 
 const NHRVO = Ci.nsINavHistoryResultViewObserver;
 
 // XXXmano: we should move most/all of these constants to PlacesUtils
-const ORGANIZER_ROOT_BOOKMARKS = "place:folder=2&group=3&excludeItems=1&queryType=1";
+const ORGANIZER_ROOT_BOOKMARKS = "place:folder=2&excludeItems=1&queryType=1";
 const ORGANIZER_SUBSCRIPTIONS_QUERY = "place:annotation=livemark%2FfeedURI";
 
 // No change to the view, preserve current selection
 const RELOAD_ACTION_NOTHING = 0;
 // Inserting items new to the view, select the inserted rows
 const RELOAD_ACTION_INSERT = 1;
 // Removing items from the view, select the first item after the last selected
 const RELOAD_ACTION_REMOVE = 2;
--- a/browser/components/places/content/editBookmarkOverlay.js
+++ b/browser/components/places/content/editBookmarkOverlay.js
@@ -401,17 +401,17 @@ var gEditItemOverlay = {
     if (aHideCollapsibleElements) {
       // hide the folder tree if it was previously visible
       if (!this._folderTree.collapsed)
         this.toggleFolderTreeVisibility();
 
       // hide the tag selector if it was previously visible
       var tagsSelector = this._element("tagsSelector");
       if (!tagsSelector.collapsed)
-        this._toggleTagsSelector();
+        this.toggleTagsSelector();
     }
 
     if (this._observersAdded) {
       PlacesUtils.bookmarks.removeObserver(this);
       this._observersAdded = false;
     }
     if (this._microsummaries) {
       this._microsummaries.removeObserver(this);
--- a/browser/components/places/content/editBookmarkOverlay.xul
+++ b/browser/components/places/content/editBookmarkOverlay.xul
@@ -139,17 +139,17 @@
 
         <tree id="editBMPanel_folderTree"
               class="placesTree"
               type="places"
               height="150"
               collapsed="true"
               onselect="gEditItemOverlay.onFolderTreeSelect();"
               showRoot="true"
-              place="place:folder=2&amp;group=3&amp;excludeItems=1&amp;excludeQueries=1&amp;excludeReadOnlyFolders=1"
+              place="place:folder=2&amp;excludeItems=1&amp;excludeQueries=1&amp;excludeReadOnlyFolders=1"
               hidecolumnpicker="true"
               observes="paneElementsBroadcaster">
           <treecols>
             <treecol anonid="title" flex="1" primary="true" hideheader="true"/>
           </treecols>
           <treechildren flex="1"/>
         </tree>
 
--- a/browser/components/places/content/menu.xml
+++ b/browser/components/places/content/menu.xml
@@ -42,70 +42,62 @@
           xmlns="http://www.mozilla.org/xbl"
           xmlns:xbl="http://www.mozilla.org/xbl"
           xmlns:html="http://www.w3.org/1999/xhtml"
           xmlns:xul="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul">
 
   <binding id="places-menupopup"
            extends="chrome://global/content/bindings/popup.xml#popup">
     <implementation>
-      <constructor><![CDATA[
-#if 0
-        // Support an asyncinit attribute that causes the view to populate
-        // itself only after the window has been shown. This is to ensure we
-        // do not regress browser window show time (Ts/Txul)
-        if (this.hasAttribute("asyncinit")) {
-          var self = this;
-          //setTimeout(function() { self._init(); }, 0);
-        }
-        else
-#endif
-        this._init();
-      ]]></constructor>
-
       <destructor><![CDATA[
         this._resultNode = null;
         if (this._result) {
           this._result.viewer = null;
           this._result = null;
         }
       ]]></destructor>
 
-      <method name="_init">
+      <field name="_initialized">false</field>
+      <method name="_ensureInitialized">
         <body><![CDATA[
+          if (this._initialized)
+            return;
+
           this._controller = new PlacesController(this);
           this.controllers.appendController(this._controller);
 
           // This function should only be called for top-level menus like the bookmarks menu.
           // Submenus get their _result and _resultNode from their parents.
           if (this.hasAttribute("place")) {
             // Do the initial build.
             this.place = this.place;
           }
+          this._initialized = true;
         ]]></body>
       </method>
 
       <property name="controller"
                 readonly="true"
                 onget="return this._controller;"/>
 
       <field name="_built">false</field>
 
+      <field name="_ignoreInvalidateContainer">false</field>
+
       <method name="onPopupShowing">
         <body><![CDATA[
-        if (!this._resultNode)
-          this._init();
+          this._ensureInitialized();
 
-        if (!this._resultNode.containerOpen)
-          this._resultNode.containerOpen = true;
-        if (!this._built)
-          this._rebuild();
+          if (!this._resultNode.containerOpen)
+            this._resultNode.containerOpen = true;
+          if (!this._built)
+            this._rebuild();
 
-        if (this.popupShowingCallback)
-          this.popupShowingCallback();
+          if (this.popupShowingCallback)
+            this.popupShowingCallback();
         ]]></body>
       </method>
 
       <field name="_selection">null</field>
 
       <method name="setResultAndNode">
         <parameter name="result"/>
         <parameter name="resultNode"/>
@@ -162,30 +154,36 @@
               continue;
             }
             if ((this._startMarker != -1) && (this._endMarker == -1))
               items.push(item);
           }
 
           // If static items at the beginning were found, remove all items between
           // them and the static content at the end.
-          for (var i = 0; i < items.length; ++i) {
-            items[i].parentNode.removeChild(items[i]);
-            if (this._endMarker > 0)
-              --this._endMarker;
+          for (var i = 0; i < items.length; ++i) { 
+            // skip the empty menu item
+            if (this._emptyMenuItem != items[i]) {
+              items[i].parentNode.removeChild(items[i]);
+              if (this._endMarker > 0)
+                --this._endMarker;
+            }
           }
 
           // If no static items were found at the beginning, remove all items before
           // the static items at the end.
           if (this._startMarker == -1) {
             var end = (this._endMarker == -1) ? this.childNodes.length - 1 : this._endMarker - 1;
             for (var i = end; i >=0; i--) {
-              this.removeChild(this.childNodes[i]);
-              if (this._endMarker > 0)
-                --this._endMarker;
+              // skip the empty menu item
+              if (this._emptyMenuItem != this.childNodes[i]) {
+                this.removeChild(this.childNodes[i]);
+                if (this._endMarker > 0)
+                  --this._endMarker;
+              }
             }
           }
           //LOG("KIDS = " + this.childNodes.length);
         ]]></body>
       </method>
 
       <method name="removeItem">
         <parameter name="child"/>
@@ -249,17 +247,17 @@
             if (this._needsBindingAttachment) {
               const MENU_URI = "chrome://browser/content/places/menu.xml#places-menupopup";
               document.addBinding(popup, MENU_URI);
             }
 #endif
             popup._containerNodesMap = this._containerNodesMap;
             this._containerNodesMap.push({ resultNode: child, domNode: popup });
           }
-
+          
           if (element) {
             element.node = child;
             element.node.viewIndex = 0;
             if (child.icon)
               element.setAttribute("image", child.icon.spec);
 
             if (before)
               this.insertBefore(element, before);
@@ -479,18 +477,29 @@
 
         containerOpened: function PMV_containerOpened(aNode) {
           this.invalidateContainer(aNode);
         },
 
         containerClosed: function PMV_containerClosed(aNode) {
           this.invalidateContainer(aNode);
         },
+ 
+        get ignoreInvalidateContainer() {
+          return this._self._ignoreInvalidateContainer;
+        },
+
+        set ignoreInvalidateContainer(val) {
+          return this._self._ignoreInvalidateContainer = val;
+        },
 
         invalidateContainer: function PMV_invalidateContainer(aContainer) {
+          if (this._self_ignoreInvalidateContainer)
+            return;
+
           if (!this._self._built)
             return;
 
           function isChildOf(node, container) {
             var parent = node.parent;
             while (parent) {
               if (parent == container)
                 return true;
@@ -912,16 +921,17 @@
         }
       })]]></field>
 
       <property name="selType" readonly="true" onget="return 'single';"/>
 
       <method name="buildContextMenu">
         <parameter name="aPopup"/>
         <body><![CDATA[
+          this._ensureInitialized();
           this.focus();
           return this.controller.buildContextMenu(aPopup);
         ]]></body>
       </method>
 
       <method name="destroyContextMenu">
         <parameter name="aPopup"/>
         <body>
--- a/browser/components/places/content/moveBookmarks.xul
+++ b/browser/components/places/content/moveBookmarks.xul
@@ -64,17 +64,17 @@
     <label id="movetolabel" value="&moveTo.label;" control="foldersTree"/>
     <hbox flex="1">
       <tree id="foldersTree"
             class="placesTree"
             flex="1"
             type="places"
             showRoot="true"
             seltype="single"
-            place="place:folder=2&amp;group=3&amp;excludeItems=1&amp;excludeReadOnlyFolders=1" 
+            place="place:folder=2&amp;excludeItems=1&amp;excludeReadOnlyFolders=1" 
             hidecolumnpicker="true">
         <treecols>
           <treecol id="title" flex="1" primary="true" hideheader="true"/>
         </treecols>
         <treechildren id="placesListChildren" view="placesList" flex="1"/>
       </tree>
       <vbox>
         <button id="newFolderButton"
--- a/browser/components/places/content/places.xul
+++ b/browser/components/places/content/places.xul
@@ -347,17 +347,17 @@
     </toolbar>
   </toolbox>
 
   <hbox flex="1" id="placesView">
     <tree id="placesList"
           class="placesTree"
           type="places"
           showRoot="true"
-          place="place:folder=2&amp;group=3&amp;excludeItems=1&amp;queryType=1"
+          place="place:folder=2&amp;excludeItems=1&amp;queryType=1"
           hidecolumnpicker="true" context="placesContext"
           onselect="PlacesOrganizer.onPlaceSelected(true);"
           onclick="PlacesOrganizer.onTreeClick(event);"
           seltype="single"
           persist="width"
           width="160">
       <treecols>
         <treecol id="title" flex="1" primary="true" hideheader="true"/>
--- a/browser/components/places/content/toolbar.xml
+++ b/browser/components/places/content/toolbar.xml
@@ -133,17 +133,19 @@
       <field name="_dropIndicatorBar">document.getAnonymousElementByAttribute(this, "class", "toolbar-drop-indicator-bar")</field>
       <field name="_chevron">document.getAnonymousElementByAttribute(this, "class", "chevron")</field>
       
       <field name="_selection">null</field>
       
       <field name="_openedMenuButton">null</field>
       
       <field name="_result">null</field>
-      
+
+      <field name="_ignoreInvalidateContainer">false</field>
+
       <!-- nsIPlacesView -->
       <method name="getResult">
         <body><![CDATA[
           return this._result;
         ]]></body>
       </method>
 
       <!-- nsIPlacesView -->
@@ -571,17 +573,28 @@
         containerOpened: function TV_V_containerOpened(aNode) {
           this.invalidateContainer(aNode);
         },
 
         containerClosed: function TV_V_containerClosed(aNode) {
           this.invalidateContainer(aNode);
         },
 
+        get ignoreInvalidateContainer() {
+          return this._self._ignoreInvalidateContainer;
+        },
+
+        set ignoreInvalidateContainer(val) {
+          return this._self._ignoreInvalidateContainer = val;
+        },
+
         invalidateContainer: function TV_V_invalidateContainer(aContainer) {
+          if (this._self._ignoreInvalidateContainer)
+            return;
+
           function isChildOf(node, container) {
             var parent = node.parent;
             while (parent) {
               if (parent == container)
                 return true;
               parent = parent.parent;
             }
             return false;
--- a/browser/components/places/content/tree.xml
+++ b/browser/components/places/content/tree.xml
@@ -760,102 +760,16 @@
         <body><![CDATA[
           var flavorSet = new FlavourSet();
           for (var i = 0; i < this.peerDropTypes.length; ++i)
             flavorSet.appendFlavour(this.peerDropTypes[i]);
           return flavorSet;
         ]]></body>
       </method>
       
-      <!--
-        Gets the nsINavHistoryResultNode adjacent to the specified InsertionPoint.
-        @param    insertionPoint
-                  The InsertionPoint where items are being inserted
-        @returns  a nsINavHistoryResultNode that is adjacent to the specified
-                  InsertionPoint 
-        -->
-      <method name="_getInsertionNode">
-        <parameter name="insertionPoint"/>
-        <body><![CDATA[ 
-          // The InsertionPoint defines a place within the view hierarchy where 
-          // items may be inserted. This function returns the node adjacent to 
-          // that point. In order to get the right node, we must enumerate the
-          // contents of the containing folder, but we cannot construct a new
-          // query for this, because if we do so the node will be a member of
-          // another result node (that constructed by |getFolderContents| say, 
-          // instead of the displayed tree view). So we need to walk the 
-          // children of the result to find the right folder. 
-          function findFolder(aItemId, aContainer) {
-            var wasOpen = aContainer.containerOpen;
-            aContainer.containerOpen = true;
-            var cc = aContainer.childCount;
-            var foundNode = null;
-            for (var i = 0; i < cc; ++i) {
-              var node = aContainer.getChild(i);
-              if (PlacesUtils.nodeIsFolder(node)) {
-                if (node.itemId == aItemId) {
-                  foundNode = node;
-                  break;
-                }
-                foundNode = findFolder(aItemId, node);
-                if (foundNode)
-                  break;
-              }
-            }
-            aContainer.containerOpen = wasOpen;
-            return foundNode;
-          }
-          var folder = null;
-          var root = asContainer(this.getResultNode());
-          if (PlacesUtils.nodeIsFolder(root) && 
-              root.itemId == insertionPoint.itemId)
-            folder = root;
-          else
-            folder = findFolder(insertionPoint.itemId, root);
-          
-          // Since we find the folder manually, using findFolder instead of 
-          // PlacesUtils.getFolderContents, the folder is not opened for
-          // us. We need to do that ourselves (and remember if it was closed,
-          // so that we can close it again later).
-          var folderWasOpen = folder.containerOpen;
-          folder.containerOpen = true;
-
-          var index = insertionPoint.index;
-          if (insertionPoint.index == -1 || insertionPoint.index >= folder.childCount)
-            index = folder.childCount - 1;
-          NS_ASSERT(index < folder.childCount, 
-                    "index out of range: " + index + " > " + folder);
-          var insertionNode = index > -1 ? folder.getChild(index) : null;
-          
-          // Now close the folder again, if it was before.
-          folder.containerOpen = folderWasOpen;
-          
-          return insertionNode;
-        ]]></body>
-      </method>
-      
-      <!--
-        Gets the tree-index of the node adjacent to the specified InsertionPoint
-        @param    insertionPoint
-                  The InsertionPoint where items are being inserted
-        @returns  the tree-index of the node adjacent to the specified InsertionPoint
-        -->
-      <method name="_getInsertionIndex">
-        <parameter name="insertionPoint"/>
-        <body><![CDATA[
-          var node = this._getInsertionNode(insertionPoint);
-          // This is the insertion index of the pivot. 
-          if (node)
-            return this.getResultView().treeIndexForNode(node);
-          else if (insertionPoint.orientation == NHRVO.DROP_ON)
-            return Ci.nsINavHistoryResultTreeViewer.INDEX_INVISIBLE;
-          return -1;
-        ]]></body>
-      </method>
-      
       <field name="_viewObserver"><![CDATA[({
         _self: this,
         
         canDrop: function VO_canDrop(index, orientation) {
           var result = this._self.getResult();
           var resultview = this._self.getResultView();
           var node = index != -1 ? resultview.nodeForTreeIndex(index) : result.root;
 
--- a/browser/components/places/content/treeHelpers.js
+++ b/browser/components/places/content/treeHelpers.js
@@ -205,17 +205,16 @@ var OptionsFilter = {
     this._grouper = grouper;
   
     var history = PlacesUtils.history;
     const NHQO = Ci.nsINavHistoryQueryOptions;
     
     var defaultHistoryOptions = history.getNewQueryOptions();
     defaultHistoryOptions.sortingMode = NHQO.SORT_BY_DATE_DESCENDING;
     var defaultBookmarksOptions = history.getNewQueryOptions();
-    defaultBookmarksOptions.setGroupingMode([NHQO.GROUP_BY_FOLDER], 1);
     var defaultSubscriptionsOptions = history.getNewQueryOptions();
   
     this.historyHandler = 
       new PrefHandler(PREF_PLACES_ORGANIZER_OPTIONS_HISTORY, 
                       defaultHistoryOptions, this);
     this.bookmarksHandler = 
       new PrefHandler(PREF_PLACES_ORGANIZER_OPTIONS_BOOKMARKS, 
                       defaultBookmarksOptions, this);
--- a/browser/components/places/content/treeView.js
+++ b/browser/components/places/content/treeView.js
@@ -295,17 +295,17 @@ PlacesTreeView.prototype = {
   _refreshVisibleSection: function PTV__refreshVisibleSection(aContainer) {
     NS_ASSERT(this._result, "Need to have a result to update");
     if (!this._tree)
       return;
 
     // The root node is invisible if showRoot is not set. Otherwise aContainer
     // must be visible
     if (this._showRoot || aContainer != this._result.root) {
-      if (aContainer.viewIndex < 0 &&
+      if (aContainer.viewIndex < 0 ||
           aContainer.viewIndex > this._visibleElements.length)
         throw "Trying to expand a node that is not visible";
 
       NS_ASSERT(this._visibleElements[aContainer.viewIndex] == aContainer,
                 "Visible index is out of sync!");
     }
 
     var startReplacement = aContainer.viewIndex + 1;
@@ -367,17 +367,27 @@ PlacesTreeView.prototype = {
       this._tree.rowCountChanged(startReplacement, -replaceCount);
     if (newElements.length)
       this._tree.rowCountChanged(startReplacement, newElements.length);
     this._tree.endUpdateBatch();
 
     // now, open any containers that were persisted
     for (var i = 0; i < toOpenElements.length; i++) {
       var item = asContainer(toOpenElements[i]);
-      item.containerOpen = !item.containerOpen;
+      var parent = item.parent;
+      // avoid recursively opening containers
+      while (parent) {
+        if (parent.uri == item.uri)
+          break;
+        parent = parent.parent;
+      }
+      // if we don't have a parent, we made it all the way to the root
+      // and didn't find a match, so we can open our item
+      if (!parent)
+        item.containerOpen = !item.containerOpen;
     }
 
     // restore selection
     if (nodesToSelect.length > 0) {
       for each (var node in nodesToSelect) {
         var index = node.viewIndex;
         selection.rangedSelect(index, index, true);
       }
@@ -721,17 +731,28 @@ PlacesTreeView.prototype = {
   containerOpened: function PTV_containerOpened(aItem) {
     this.invalidateContainer(aItem);
   },
 
   containerClosed: function PTV_containerClosed(aItem) {
     this.invalidateContainer(aItem);
   },
 
-  invalidateContainer: function PTV_invalidateContainer(aItem) {
+  get ignoreInvalidateContainer() {
+    return this._ignoreInvalidateContainer;
+  },
+
+  set ignoreInvalidateContainer(val) {
+    return this._ignoreInvalidateContainer = val;
+  },
+
+  invalidateContainer: function PTV_invalidateContainer(aItem) {
+    if (this._ignoreInvalidateContainer)
+      return;
+
     NS_ASSERT(this._result, "Got a notification but have no result!");
     if (!this._tree)
       return; // nothing to do, container is not visible
     var viewIndex = aItem.viewIndex;
     if (viewIndex >= this._visibleElements.length) {
       // be paranoid about visible indices since others can change it
       throw Cr.NS_ERROR_UNEXPECTED;
     }
@@ -1214,16 +1235,17 @@ PlacesTreeView.prototype = {
         else if (allowTriState &&
                  oldSort == NHQO.SORT_BY_ANNOTATION_DESCENDING &&
                  oldSortingAnnotation == DESCRIPTION_ANNO)
           newSort = NHQO.SORT_BY_NONE;
         else {
           newSort = NHQO.SORT_BY_ANNOTATION_ASCENDING;
           newSortingAnnotation = DESCRIPTION_ANNO;
         }
+
         break;
       case this.COLUMN_TYPE_DATEADDED:
         if (oldSort == NHQO.SORT_BY_DATEADDED_ASCENDING)
           newSort = NHQO.SORT_BY_DATEADDED_DESCENDING;
         else if (allowTriState &&
                  oldSort == NHQO.SORT_BY_DATEADDED_DESCENDING)
           newSort = NHQO.SORT_BY_NONE;
         else
@@ -1277,9 +1299,10 @@ function PlacesTreeView(aShowRoot) {
   this._tree = null;
   this._result = null;
   this._collapseDuplicates = true;
   this._showSessions = false;
   this._selection = null;
   this._visibleElements = [];
   this._observers = [];
   this._showRoot = aShowRoot;
+  this._ignoreInvalidateContainer = false;
 }
--- a/browser/components/places/content/utils.js
+++ b/browser/components/places/content/utils.js
@@ -882,17 +882,16 @@ var PlacesUtils = {
    * @returns A nsINavHistoryResult containing the contents of the
    *          folder. The result.root is guaranteed to be open.
    */
   getFolderContents:
   function PU_getFolderContents(aFolderId, aExcludeItems, aExpandQueries) {
     var query = this.history.getNewQuery();
     query.setFolders([aFolderId], 1);
     var options = this.history.getNewQueryOptions();
-    options.setGroupingMode([Ci.nsINavHistoryQueryOptions.GROUP_BY_FOLDER], 1);
     options.excludeItems = aExcludeItems;
     options.expandQueries = aExpandQueries;
 
     var result = this.history.executeQuery(query, options);
     result.root.containerOpen = true;
     asContainer(result.root);
     return result;
   },
@@ -1410,17 +1409,16 @@ var PlacesUtils = {
 
   /**
    * Helper for getting a serialized Places query for a particular folder.
    * @param aFolderId The folder id to get a query for.
    * @return string serialized place URI
    */
   getQueryStringForFolder: function PU_getQueryStringForFolder(aFolderId) {
     var options = this.history.getNewQueryOptions();
-    options.setGroupingMode([Ci.nsINavHistoryQueryOptions.GROUP_BY_FOLDER], 1);
     var query = this.history.getNewQuery();
     query.setFolders([aFolderId], 1);
     return this.history.queriesToQueryString([query], 1, options);
   },
 
   /**
    * Get the description associated with a document, as specified in a <META>
    * element.
--- a/browser/components/preferences/advanced.js
+++ b/browser/components/preferences/advanced.js
@@ -123,25 +123,16 @@ var gAdvancedPane = {
    * unchanged and represents a value not strictly allowed in UI.
    */
   writeCheckSpelling: function ()
   {
     var checkbox = document.getElementById("checkSpelling");
     return checkbox.checked ? (this._storedSpellCheck == 2 ? 2 : 1) : 0;
   },
 
-  /**
-   * Shows a dialog in which the preferred language for web content may be set.
-   */
-  showLanguages: function ()
-  {
-    document.documentElement.openSubDialog("chrome://browser/content/preferences/languages.xul",
-                                           "", null);
-  },
-
   // NETWORK TAB
 
   /*
    * Preferences:
    *
    * browser.cache.disk.capacity
    * - the size of the browser cache in KB
    */
--- a/browser/components/preferences/advanced.xul
+++ b/browser/components/preferences/advanced.xul
@@ -164,29 +164,16 @@
             <checkbox id="checkSpelling"
                       label="&checkSpelling.label;"
                       accesskey="&checkSpelling.accesskey;"
                       onsyncfrompreference="return gAdvancedPane.readCheckSpelling();"
                       onsynctopreference="return gAdvancedPane.writeCheckSpelling();"
                       preference="layout.spellcheckDefault"/>
           </groupbox>
 
-          <!-- Languages -->
-          <groupbox id="languagesGroup">
-            <caption label="&languages.label;"/>
-
-            <hbox id="languagesBox" align="center">
-              <description flex="1" control="chooseLanguage">&chooseLanguage.label;</description>
-              <button id="chooseLanguage"
-                      label="&chooseButton.label;"
-                      accesskey="&chooseButton.accesskey;"
-                      oncommand="gAdvancedPane.showLanguages();"/>
-            </hbox>
-          </groupbox>
-
         </tabpanel>
 
         <!-- Network -->
         <tabpanel id="networkPanel" orient="vertical">
 
            <!-- Connection -->
            <groupbox id="connectionGroup">
              <caption label="&connection.label;"/>
--- a/browser/components/preferences/applications.js
+++ b/browser/components/preferences/applications.js
@@ -148,16 +148,41 @@ function getLocalHandlerApp(aFile) {
   var localHandlerApp = Cc["@mozilla.org/uriloader/local-handler-app;1"].
                         createInstance(Ci.nsILocalHandlerApp);
   localHandlerApp.name = getDisplayNameForFile(aFile);
   localHandlerApp.executable = aFile;
 
   return localHandlerApp;
 }
 
+/**
+ * An enumeration of items in a JS array.
+ *
+ * FIXME: use ArrayConverter once it lands (bug 380839).
+ * 
+ * @constructor
+ */
+function ArrayEnumerator(aItems) {
+  this._index = 0;
+  this._contents = aItems;
+}
+
+ArrayEnumerator.prototype = {
+  _index: 0,
+  _contents: [],
+
+  hasMoreElements: function() {
+    return this._index < this._contents.length;
+  },
+
+  getNext: function() {
+    return this._contents[this._index++];
+  }
+};
+
 
 //****************************************************************************//
 // HandlerInfoWrapper
 
 /**
  * This object wraps nsIHandlerInfo with some additional functionality
  * the Applications prefpane needs to display and allow modification of
  * the list of handled types.
@@ -231,18 +256,17 @@ HandlerInfoWrapper.prototype = {
   },
 
   set preferredApplicationHandler(aNewValue) {
     this.wrappedHandlerInfo.preferredApplicationHandler = aNewValue;
 
     // Make sure the preferred handler is in the set of possible handlers.
     if (aNewValue) {
       var found = false;
-      var possibleApps = this.possibleApplicationHandlers.
-                         QueryInterface(Ci.nsIArray).enumerate();
+      var possibleApps = this.possibleApplicationHandlers.enumerate();
       while (possibleApps.hasMoreElements() && !found)
         found = possibleApps.getNext().equals(aNewValue);
       if (!found)
         this.possibleApplicationHandlers.appendElement(aNewValue, false);
     }
   },
 
   get possibleApplicationHandlers() {
@@ -258,32 +282,30 @@ HandlerInfoWrapper.prototype = {
   },
 
   // What to do with content of this type.
   get preferredAction() {
     // If we have an enabled plugin, then the action is to use that plugin.
     if (this.plugin && !this.isDisabledPluginType)
       return kActionUsePlugin;
 
-    // XXX nsIMIMEService::getFromTypeAndExtension returns handler infos
-    // whose default action is saveToDisk; should we do that here too?
-    // And will there ever be handler info objects with no preferred action?
-    if (!this.wrappedHandlerInfo.preferredAction) {
-      if (gApplicationsPane.isValidHandlerApp(this.preferredApplicationHandler))
-        return Ci.nsIHandlerInfo.useHelperApp;
-      else
+    // If the action is to use a helper app, but we don't have a preferred
+    // handler app, then switch to using the system default, if any; otherwise
+    // fall back to saving to disk, which is the default action in nsMIMEInfo.
+    // Note: "save to disk" is an invalid value for protocol info objects,
+    // but the alwaysAskBeforeHandling getter will detect that situation
+    // and always return true in that case to override this invalid value.
+    if (this.wrappedHandlerInfo.preferredAction == Ci.nsIHandlerInfo.useHelperApp &&
+        !gApplicationsPane.isValidHandlerApp(this.preferredApplicationHandler)) {
+      if (this.wrappedHandlerInfo.hasDefaultHandler)
         return Ci.nsIHandlerInfo.useSystemDefault;
+      else
+        return Ci.nsIHandlerInfo.saveToDisk;
     }
 
-    // If the action is to use a helper app, but we don't have a preferred
-    // helper app, switch to using the system default.
-    if (this.wrappedHandlerInfo.preferredAction == Ci.nsIHandlerInfo.useHelperApp &&
-        !gApplicationsPane.isValidHandlerApp(this.preferredApplicationHandler))
-      return Ci.nsIHandlerInfo.useSystemDefault;
-
     return this.wrappedHandlerInfo.preferredAction;
   },
 
   set preferredAction(aNewValue) {
     // We don't modify the preferred action if the new action is to use a plugin
     // because handler info objects don't understand our custom "use plugin"
     // value.  Also, leaving it untouched means that we can automatically revert
     // to the old setting if the user ever removes the plugin.
@@ -296,16 +318,26 @@ HandlerInfoWrapper.prototype = {
     // If this type is handled only by a plugin, we can't trust the value
     // in the handler info object, since it'll be a default based on the absence
     // of any user configuration, and the default in that case is to always ask,
     // even though we never ask for content handled by a plugin, so special case
     // plugin-handled types by returning false here.
     if (this.plugin && this.handledOnlyByPlugin)
       return false;
 
+    // If this is a protocol type and the preferred action is "save to disk",
+    // which is invalid for such types, then return true here to override that
+    // action.  This could happen when the preferred action is to use a helper
+    // app, but the preferredApplicationHandler is invalid, and there isn't
+    // a default handler, so the preferredAction getter returns save to disk
+    // instead.
+    if (!(this.wrappedHandlerInfo instanceof Ci.nsIMIMEInfo) &&
+        this.preferredAction == Ci.nsIHandlerInfo.saveToDisk)
+      return true;
+
     return this.wrappedHandlerInfo.alwaysAskBeforeHandling;
   },
 
   set alwaysAskBeforeHandling(aNewValue) {
     this.wrappedHandlerInfo.alwaysAskBeforeHandling = aNewValue;
   },
 
 
@@ -515,38 +547,65 @@ var feedHandlerInfo = {
       // a non-web handler (local app, Live Bookmarks, etc.) because the service
       // only uses the "auto handler" when the selected reader is a web handler.
       // We also don't have to unregister it when the user turns on "always ask"
       // (i.e. preview in browser), since that also overrides the auto handler.
       this._converterSvc.setAutoHandler(this.type, aNewValue);
     }
   },
 
+  _possibleApplicationHandlers: null,
+
   get possibleApplicationHandlers() {
-    var handlerApps = Cc["@mozilla.org/array;1"].
-                      createInstance(Ci.nsIMutableArray);
+    if (this._possibleApplicationHandlers)
+      return this._possibleApplicationHandlers;
+
+    // A minimal implementation of nsIMutableArray.  It only supports the two
+    // methods its callers invoke, namely appendElement and nsIArray::enumerate.
+    this._possibleApplicationHandlers = {
+      _inner: [],
+
+      QueryInterface: function(aIID) {
+        if (aIID.equals(Ci.nsIMutableArray) ||
+            aIID.equals(Ci.nsIArray) ||
+            aIID.equals(Ci.nsISupports))
+          return this;
 
-    // Add the "selected" local application, if there is one and it's different
-    // from the default handler for the OS.  Unlike for other types, there can
-    // be only one of these at a time for the feed type, since feed preferences
-    // only store a single local app.
+        throw Cr.NS_ERROR_NO_INTERFACE;
+      },
+
+      enumerate: function() {
+        return new ArrayEnumerator(this._inner);
+      },
+
+      appendElement: function(aHandlerApp, aWeak) {
+        this._inner.push(aHandlerApp);
+      }
+    };
+
+    // Add the selected local app if it's different from the OS default handler.
+    // Unlike for other types, we can store only one local app at a time for the
+    // feed type, since we store it in a preference that historically stores
+    // only a single path.  But we display all the local apps the user chooses
+    // while the prefpane is open, only dropping the list when the user closes
+    // the prefpane, for maximum usability and consistency with other types.
     var preferredAppFile = this.element(PREF_FEED_SELECTED_APP).value;
-    if (preferredAppFile && preferredAppFile.exists()) {
+    if (preferredAppFile) {
       let preferredApp = getLocalHandlerApp(preferredAppFile);
       let defaultApp = this._defaultApplicationHandler;
       if (!defaultApp || !defaultApp.equals(preferredApp))
-        handlerApps.appendElement(preferredApp, false);
+        this._possibleApplicationHandlers.appendElement(preferredApp, false);
     }
 
     // Add the registered web handlers.  There can be any number of these.
     var webHandlers = this._converterSvc.getContentHandlers(this.type, {});
     for each (let webHandler in webHandlers)
-      handlerApps.appendElement(webHandler, false);
+      this._possibleApplicationHandlers.appendElement(webHandler, false);
 
-    return handlerApps;
+    return this._possibleApplicationHandlers;
   },
 
   __defaultApplicationHandler: undefined,
   get _defaultApplicationHandler() {
     if (typeof this.__defaultApplicationHandler != "undefined")
       return this.__defaultApplicationHandler;
 
     var defaultFeedReader;
@@ -664,22 +723,16 @@ var feedHandlerInfo = {
   // nsIMIMEInfo
 
   get primaryExtension() {
     return "xml";
   },
 
 
   //**************************************************************************//
-  // Plugin Handling
-
-  handledOnlyByPlugin: false,
-
-
-  //**************************************************************************//
   // Storage
 
   // Changes to the preferred action and handler take effect immediately
   // (we write them out to the preferences right as they happen), so we don't
   // need to do anything when the controller calls store() after modifying
   // the handler.
   // XXX Should we hold off on making the changes until this method gets called?
   store: function() {},
@@ -701,16 +754,31 @@ var feedHandlerInfo = {
 
 //****************************************************************************//
 // Prefpane Controller
 
 var gApplicationsPane = {
   // The set of types the app knows how to handle.  A hash of HandlerInfoWrapper
   // objects, indexed by type.
   _handledTypes: {},
+  
+  // The list of types we can show, sorted by the sort column/direction.
+  // An array of HandlerInfoWrapper objects.  We build this list when we first
+  // load the data and then rebuild it when users change a pref that affects
+  // what types we can show or change the sort column/direction.
+  // Note: this isn't necessarily the list of types we *will* show; if the user
+  // provides a filter string, we'll only show the subset of types in this list
+  // that match that string.
+  _visibleTypes: [],
+
+  // A count of the number of times each visible type description appears.
+  // We use these counts to determine whether or not to annotate descriptions
+  // with their types to distinguish duplicate descriptions from each other.
+  // A hash of integer counts, indexed by string description.
+  _visibleTypeDescriptionCount: {},
 
 
   //**************************************************************************//
   // Convenience & Performance Shortcuts
 
   // These get defined by init().
   _brandShortName : null,
   _prefsBundle    : null,
@@ -755,33 +823,35 @@ var gApplicationsPane = {
     this._prefSvc.addObserver(PREF_FEED_SELECTED_WEB, this, false);
     this._prefSvc.addObserver(PREF_FEED_SELECTED_ACTION, this, false);
     this._prefSvc.addObserver(PREF_FEED_SELECTED_READER, this, false);
 
     // Listen for window unload so we can remove our preference observers.
     window.addEventListener("unload", this, false);
 
     // Figure out how we should be sorting the list.  We persist sort settings
-    // across sessions, so we can't assume the default sort column and direction.
+    // across sessions, so we can't assume the default sort column/direction.
     // XXX should we be using the XUL sort service instead?
     if (document.getElementById("typeColumn").hasAttribute("sortDirection"))
       this._sortColumn = document.getElementById("typeColumn");
     else if (document.getElementById("actionColumn").hasAttribute("sortDirection"))
       this._sortColumn = document.getElementById("actionColumn");
 
     // Load the data and build the list of handlers.
     // By doing this in a timeout, we let the preferences dialog resize itself
     // to an appropriate size before we add a bunch of items to the list.
     // Otherwise, if there are many items, and the Applications prefpane
     // is the one that gets displayed when the user first opens the dialog,
     // the dialog might stretch too much in an attempt to fit them all in.
     // XXX Shouldn't we perhaps just set a max-height on the richlistbox?
     var _delayedPaneLoad = function(self) {
       self._loadData();
-      self.rebuildView();
+      self._rebuildVisibleTypes();
+      self._sortVisibleTypes();
+      self._rebuildView();
     }
     setTimeout(_delayedPaneLoad, 0, this);
   },
 
   destroy: function() {
     window.removeEventListener("unload", this, false);
     this._prefSvc.removeObserver(PREF_SHOW_PLUGINS_IN_LIST, this);
     this._prefSvc.removeObserver(PREF_HIDE_PLUGINS_WITHOUT_EXTENSIONS, this);
@@ -806,18 +876,29 @@ var gApplicationsPane = {
 
 
   //**************************************************************************//
   // nsIObserver
 
   observe: function (aSubject, aTopic, aData) {
     // Rebuild the list when there are changes to preferences that influence
     // whether or not to show certain entries in the list.
-    if (aTopic == "nsPref:changed")
-      this.rebuildView();
+    if (aTopic == "nsPref:changed") {
+      // These two prefs alter the list of visible types, so we have to rebuild
+      // that list when they change.
+      if (aData == PREF_SHOW_PLUGINS_IN_LIST ||
+          aData == PREF_HIDE_PLUGINS_WITHOUT_EXTENSIONS) {
+        this._rebuildVisibleTypes();
+        this._sortVisibleTypes();
+      }
+
+      // All the prefs we observe can affect what we display, so we rebuild
+      // the view when any of them changes.
+      this._rebuildView();
+    }
   },
 
 
   //**************************************************************************//
   // nsIDOMEventListener
 
   handleEvent: function(aEvent) {
     if (aEvent.type == "unload") {
@@ -832,16 +913,17 @@ var gApplicationsPane = {
   _loadData: function() {
     this._loadFeedHandler();
     this._loadPluginHandlers();
     this._loadApplicationHandlers();
   },
 
   _loadFeedHandler: function() {
     this._handledTypes[TYPE_MAYBE_FEED] = feedHandlerInfo;
+    feedHandlerInfo.handledOnlyByPlugin = false;
   },
 
   /**
    * Load the set of handlers defined by plugins.
    *
    * Note: if there's more than one plugin for a given MIME type, we assume
    * the last one is the one that the application will use.  That may not be
    * correct, but it's how we've been doing it for years.
@@ -859,88 +941,65 @@ var gApplicationsPane = {
    * So even if we could use enabledPlugin to get the plugin that would be used,
    * we'd still need to check the pref ourselves to find out if it's enabled.
    */
   _loadPluginHandlers: function() {
     for (let i = 0; i < navigator.plugins.length; ++i) {
       let plugin = navigator.plugins[i];
       for (let j = 0; j < plugin.length; ++j) {
         let type = plugin[j].type;
+
         let handlerInfoWrapper;
-
-        if (typeof this._handledTypes[type] == "undefined") {
+        if (type in this._handledTypes)
+          handlerInfoWrapper = this._handledTypes[type];
+        else {
           let wrappedHandlerInfo =
             this._mimeSvc.getFromTypeAndExtension(type, null);
           handlerInfoWrapper = new HandlerInfoWrapper(type, wrappedHandlerInfo);
+          handlerInfoWrapper.handledOnlyByPlugin = true;
           this._handledTypes[type] = handlerInfoWrapper;
         }
-        else
-          handlerInfoWrapper = this._handledTypes[type];
 
         handlerInfoWrapper.plugin = plugin;
-        handlerInfoWrapper.handledOnlyByPlugin = true;
       }
     }
   },
 
   /**
    * Load the set of handlers defined by the application datastore.
    */
   _loadApplicationHandlers: function() {
     var wrappedHandlerInfos = this._handlerSvc.enumerate();
     while (wrappedHandlerInfos.hasMoreElements()) {
-      let wrappedHandlerInfo = wrappedHandlerInfos.getNext().
-                               QueryInterface(Ci.nsIHandlerInfo);
+      let wrappedHandlerInfo =
+        wrappedHandlerInfos.getNext().QueryInterface(Ci.nsIHandlerInfo);
       let type = wrappedHandlerInfo.type;
+
       let handlerInfoWrapper;
-
-      if (typeof this._handledTypes[type] == "undefined") {
+      if (type in this._handledTypes)
+        handlerInfoWrapper = this._handledTypes[type];
+      else {
         handlerInfoWrapper = new HandlerInfoWrapper(type, wrappedHandlerInfo);
         this._handledTypes[type] = handlerInfoWrapper;
       }
-      else
-        handlerInfoWrapper = this._handledTypes[type];
 
       handlerInfoWrapper.handledOnlyByPlugin = false;
     }
   },
 
 
   //**************************************************************************//
   // View Construction
 
-  rebuildView: function() {
-    // Clear the list of entries.
-    while (this._list.childNodes.length > 1)
-      this._list.removeChild(this._list.lastChild);
-
-    var visibleTypes = this._getVisibleTypes();
-
-    if (this._sortColumn)
-      this._sortTypes(visibleTypes);
+  _rebuildVisibleTypes: function() {
+    // Reset the list of visible types and the visible type description counts.
+    this._visibleTypes = [];
+    this._visibleTypeDescriptionCount = {};
 
-    for each (let visibleType in visibleTypes) {
-      let item = document.createElement("richlistitem");
-      item.setAttribute("type", visibleType.type);
-      item.setAttribute("typeDescription", visibleType.description);
-      if (visibleType.smallIcon)
-        item.setAttribute("typeIcon", visibleType.smallIcon);
-      item.setAttribute("actionDescription",
-                        this._describePreferredAction(visibleType));
-      item.setAttribute("actionIcon",
-                        this._getIconURLForPreferredAction(visibleType));
-      this._list.appendChild(item);
-    }
-
-    this._selectLastSelectedType();
-  },
-
-  _getVisibleTypes: function() {
-    var visibleTypes = [];
-
+    // Get the preferences that help determine what types to show.
     var showPlugins = this._prefSvc.getBoolPref(PREF_SHOW_PLUGINS_IN_LIST);
     var hideTypesWithoutExtensions =
       this._prefSvc.getBoolPref(PREF_HIDE_PLUGINS_WITHOUT_EXTENSIONS);
 
     for (let type in this._handledTypes) {
       let handlerInfo = this._handledTypes[type];
 
       // Hide types without extensions if so prefed so we don't show a whole
@@ -953,43 +1012,89 @@ var gApplicationsPane = {
           handlerInfo.wrappedHandlerInfo instanceof Ci.nsIMIMEInfo &&
           !handlerInfo.primaryExtension)
         continue;
 
       // Hide types handled only by plugins if so prefed.
       if (handlerInfo.handledOnlyByPlugin && !showPlugins)
         continue;
 
-      // If the user is filtering the list, then only show matching types.
-      if (this._filter.value && !this._matchesFilter(handlerInfo))
-        continue;
+      // We couldn't find any reason to exclude the type, so include it.
+      this._visibleTypes.push(handlerInfo);
+
+      if (handlerInfo.description in this._visibleTypeDescriptionCount)
+        this._visibleTypeDescriptionCount[handlerInfo.description]++;
+      else
+        this._visibleTypeDescriptionCount[handlerInfo.description] = 1;
+    }
+  },
+
+  _rebuildView: function() {
+    // Clear the list of entries.
+    while (this._list.childNodes.length > 1)
+      this._list.removeChild(this._list.lastChild);
 
-      // We couldn't find any reason to exclude the type, so include it.
-      visibleTypes.push(handlerInfo);
+    var visibleTypes = this._visibleTypes;
+
+    // If the user is filtering the list, then only show matching types.
+    if (this._filter.value)
+      visibleTypes = visibleTypes.filter(this._matchesFilter, this);
+
+    for each (let visibleType in visibleTypes) {
+      let item = document.createElement("richlistitem");
+      item.setAttribute("type", visibleType.type);
+      item.setAttribute("typeDescription", this._describeType(visibleType));
+      if (visibleType.smallIcon)
+        item.setAttribute("typeIcon", visibleType.smallIcon);
+      item.setAttribute("actionDescription",
+                        this._describePreferredAction(visibleType));
+      item.setAttribute("actionIcon",
+                        this._getIconURLForPreferredAction(visibleType));
+      this._list.appendChild(item);
     }
 
-    return visibleTypes;
+    this._selectLastSelectedType();
   },
 
   _matchesFilter: function(aType) {
     var filterValue = this._filter.value.toLowerCase();
-    return aType.description.toLowerCase().indexOf(filterValue) != -1 ||
+    return this._describeType(aType).toLowerCase().indexOf(filterValue) != -1 ||
            this._describePreferredAction(aType).toLowerCase().indexOf(filterValue) != -1;
   },
 
   /**
+   * Describe, in a human-readable fashion, the type represented by the given
+   * handler info object.  Normally this is just the description provided by
+   * the info object, but if more than one object presents the same description,
+   * then we annotate the duplicate descriptions with the type itself to help
+   * users distinguish between those types.
+   *
+   * @param aHandlerInfo {nsIHandlerInfo} the type being described
+   * @returns {string} a description of the type
+   */
+  _describeType: function(aHandlerInfo) {
+    if (this._visibleTypeDescriptionCount[aHandlerInfo.description] > 1)
+      return this._prefsBundle.getFormattedString("typeDescriptionWithType",
+                                                  [aHandlerInfo.description,
+                                                   aHandlerInfo.type]);
+
+    return aHandlerInfo.description;
+  },
+
+  /**
    * Describe, in a human-readable fashion, the preferred action to take on
    * the type represented by the given handler info object.
    *
    * XXX Should this be part of the HandlerInfoWrapper interface?  It would
    * violate the separation of model and view, but it might make more sense
    * nonetheless (f.e. it would make sortTypes easier).
    *
    * @param aHandlerInfo {nsIHandlerInfo} the type whose preferred action
    *                                      is being described
+   * @returns {string} a description of the action
    */
   _describePreferredAction: function(aHandlerInfo) {
     // alwaysAskBeforeHandling overrides the preferred action, so if that flag
     // is set, then describe that behavior instead.  For most types, this is
     // the "alwaysAsk" string, but for the feed type we show something special.
     if (aHandlerInfo.alwaysAskBeforeHandling) {
       if (aHandlerInfo.type == TYPE_MAYBE_FEED)
         return this._prefsBundle.getFormattedString("previewInApp",
@@ -1064,39 +1169,55 @@ var gApplicationsPane = {
    *
    * @returns {boolean} whether or not it's valid
    */
   isValidHandlerApp: function(aHandlerApp) {
     if (!aHandlerApp)
       return false;
 
     if (aHandlerApp instanceof Ci.nsILocalHandlerApp)
-      return aHandlerApp.executable &&
-             aHandlerApp.executable.exists() &&
-             aHandlerApp.executable.isExecutable();
+      return this._isValidHandlerExecutable(aHandlerApp.executable);
 
     if (aHandlerApp instanceof Ci.nsIWebHandlerApp)
       return aHandlerApp.uriTemplate;
 
     if (aHandlerApp instanceof Ci.nsIWebContentHandlerInfo)
       return aHandlerApp.uri;
 
     return false;
   },
 
+  _isValidHandlerExecutable: function(aExecutable) {
+    return aExecutable &&
+           aExecutable.exists() &&
+           aExecutable.isExecutable() &&
+// XXXben - we need to compare this with the running instance executable
+//          just don't know how to do that via script...
+// XXXmano TBD: can probably add this to nsIShellService
+#ifdef XP_WIN
+#expand    aExecutable.leafName != "__MOZ_APP_NAME__.exe";
+#else
+#ifdef XP_MACOSX
+#expand    aExecutable.leafName != "__MOZ_APP_DISPLAYNAME__.app";
+#else
+#expand    aExecutable.leafName != "__MOZ_APP_NAME__-bin";
+#endif
+#endif
+  },
+
   /**
    * Rebuild the actions menu for the selected entry.  Gets called by
    * the richlistitem constructor when an entry in the list gets selected.
    */
   rebuildActionsMenu: function() {
     var typeItem = this._list.selectedItem;
     var handlerInfo = this._handledTypes[typeItem.type];
     var menu =
       document.getAnonymousElementByAttribute(typeItem, "class", "actionsMenu");
-    var menuPopup = menu.firstChild;
+    var menuPopup = menu.menupopup;
 
     // Clear out existing items.
     while (menuPopup.hasChildNodes())
       menuPopup.removeChild(menuPopup.lastChild);
 
     {
       var askMenuItem = document.createElementNS(kXULNS, "menuitem");
       askMenuItem.setAttribute("alwaysAsk", "true");
@@ -1134,18 +1255,17 @@ var gApplicationsPane = {
       defaultMenuItem.setAttribute("label", handlerInfo.defaultDescription);
       defaultMenuItem.setAttribute("image", this._getIconURLForSystemDefault(handlerInfo));
 
       menuPopup.appendChild(defaultMenuItem);
     }
 
     // Create menu items for possible handlers.
     let preferredApp = handlerInfo.preferredApplicationHandler;
-    let possibleApps = handlerInfo.possibleApplicationHandlers.
-                       QueryInterface(Ci.nsIArray).enumerate();
+    let possibleApps = handlerInfo.possibleApplicationHandlers.enumerate();
     var possibleAppMenuItems = [];
     while (possibleApps.hasMoreElements()) {
       let possibleApp = possibleApps.getNext();
       if (!this.isValidHandlerApp(possibleApp))
         continue;
 
       let menuItem = document.createElementNS(kXULNS, "menuitem");
       menuItem.setAttribute("action", Ci.nsIHandlerInfo.useHelperApp);
@@ -1243,61 +1363,62 @@ var gApplicationsPane = {
     this._sortColumn = column;
 
     // Set (or switch) the sort direction indicator.
     if (column.getAttribute("sortDirection") == "ascending")
       column.setAttribute("sortDirection", "descending");
     else
       column.setAttribute("sortDirection", "ascending");
 
-    this.rebuildView();
+    this._sortVisibleTypes();
+    this._rebuildView();
   },
 
   /**
-   * Given an array of HandlerInfoWrapper objects, sort them according to
-   * the current sort order.  Used by rebuildView to sort the set of visible
-   * types before building the list from them.
+   * Sort the list of visible types by the current sort column/direction.
    */
-  _sortTypes: function(aTypes) {
+  _sortVisibleTypes: function() {
     if (!this._sortColumn)
       return;
 
+    var t = this;
+
     function sortByType(a, b) {
-      return a.description.toLowerCase().localeCompare(b.description.toLowerCase());
+      return t._describeType(a).toLowerCase().
+             localeCompare(t._describeType(b).toLowerCase());
     }
 
-    var t = this;
     function sortByAction(a, b) {
       return t._describePreferredAction(a).toLowerCase().
              localeCompare(t._describePreferredAction(b).toLowerCase());
     }
 
     switch (this._sortColumn.getAttribute("value")) {
       case "type":
-        aTypes.sort(sortByType);
+        this._visibleTypes.sort(sortByType);
         break;
       case "action":
-        aTypes.sort(sortByAction);
+        this._visibleTypes.sort(sortByAction);
         break;
     }
 
     if (this._sortColumn.getAttribute("sortDirection") == "descending")
-      aTypes.reverse();
+      this._visibleTypes.reverse();
   },
 
   /**
    * Filter the list when the user enters a filter term into the filter field.
    */
   filter: function() {
     if (this._filter.value == "") {
       this.clearFilter();
       return;
     }
 
-    this.rebuildView();
+    this._rebuildView();
 
     document.getElementById("clearFilter").disabled = false;
   },
 
   _filterTimeout: null,
 
   onFilterInput: function() {
     if (this._filterTimeout)
@@ -1308,66 +1429,69 @@ var gApplicationsPane = {
 
   onFilterKeyPress: function(aEvent) {
     if (aEvent.keyCode == KeyEvent.DOM_VK_ESCAPE)
       this.clearFilter();
   },
   
   clearFilter: function() {
     this._filter.value = "";
-    this.rebuildView();
+    this._rebuildView();
 
     this._filter.focus();
     document.getElementById("clearFilter").disabled = true;
   },
 
   focusFilterBox: function() {
     this._filter.focus();
     this._filter.select();
   },
 
 
   //**************************************************************************//
   // Changes
 
-  onSelectAction: function(event) {
-    var actionItem = event.originalTarget;
+  onSelectAction: function(aActionItem) {
     var typeItem = this._list.selectedItem;
     var handlerInfo = this._handledTypes[typeItem.type];
 
-    if (actionItem.hasAttribute("alwaysAsk")) {
+    if (aActionItem.hasAttribute("alwaysAsk")) {
       handlerInfo.alwaysAskBeforeHandling = true;
     }
-    else if (actionItem.hasAttribute("action")) {
-      let action = parseInt(actionItem.getAttribute("action"));
+    else if (aActionItem.hasAttribute("action")) {
+      let action = parseInt(aActionItem.getAttribute("action"));
 
       // Set the plugin state if we're enabling or disabling a plugin.
       if (action == kActionUsePlugin)
         handlerInfo.enablePluginType();
       else if (handlerInfo.plugin && !handlerInfo.isDisabledPluginType)
         handlerInfo.disablePluginType();
 
       // Set the preferred application handler.
       // We leave the existing preferred app in the list when we set
       // the preferred action to something other than useHelperApp so that
       // legacy datastores that don't have the preferred app in the list
       // of possible apps still include the preferred app in the list of apps
       // the user can choose to handle the type.
       if (action == Ci.nsIHandlerInfo.useHelperApp)
-        handlerInfo.preferredApplicationHandler = actionItem.handlerApp;
+        handlerInfo.preferredApplicationHandler = aActionItem.handlerApp;
 
       // Set the "always ask" flag.
       handlerInfo.alwaysAskBeforeHandling = false;
 
       // Set the preferred action.
       handlerInfo.preferredAction = action;
     }
 
     handlerInfo.store();
 
+    // Make sure the handler info object is flagged to indicate that there is
+    // now some user configuration for the type.
+    handlerInfo.handledOnlyByPlugin = false;
+
     // Update the action label and image to reflect the new preferred action.
     typeItem.setAttribute("actionDescription",
                           this._describePreferredAction(handlerInfo));
     typeItem.setAttribute("actionIcon",
                           this._getIconURLForPreferredAction(handlerInfo));
   },
 
   chooseApp: function(aEvent) {
@@ -1375,49 +1499,52 @@ var gApplicationsPane = {
     // as we handle it specially ourselves.
     aEvent.stopPropagation();
 
     var fp = Cc["@mozilla.org/filepicker;1"].createInstance(Ci.nsIFilePicker);
     var winTitle = this._prefsBundle.getString("fpTitleChooseApp");
     fp.init(window, winTitle, Ci.nsIFilePicker.modeOpen);
     fp.appendFilters(Ci.nsIFilePicker.filterApps);
 
-    if (fp.show() == Ci.nsIFilePicker.returnOK && fp.file) {
-      // XXXben - we need to compare this with the running instance executable
-      //          just don't know how to do that via script...
-      // XXXmano TBD: can probably add this to nsIShellService
-#ifdef XP_WIN
-#expand      if (fp.file.leafName == "__MOZ_APP_NAME__.exe")
-#else
-#ifdef XP_MACOSX
-#expand      if (fp.file.leafName == "__MOZ_APP_DISPLAYNAME__.app")
-#else
-#expand      if (fp.file.leafName == "__MOZ_APP_NAME__-bin")
-#endif
-#endif
-        { this.rebuildActionsMenu(); return; }
+    var handlerApp;
 
-      let handlerApp = Cc["@mozilla.org/uriloader/local-handler-app;1"].
-                       createInstance(Ci.nsIHandlerApp);
+    // Prompt the user to pick an app.  If they pick one, and it's a valid
+    // selection, then add it to the list of possible handlers.
+    if (fp.show() == Ci.nsIFilePicker.returnOK && fp.file &&
+        this._isValidHandlerExecutable(fp.file)) {
+      handlerApp = Cc["@mozilla.org/uriloader/local-handler-app;1"].
+                   createInstance(Ci.nsILocalHandlerApp);
       handlerApp.name = getDisplayNameForFile(fp.file);
-      handlerApp.QueryInterface(Ci.nsILocalHandlerApp);
       handlerApp.executable = fp.file;
 
-      var handlerInfo = this._handledTypes[this._list.selectedItem.type];
-
-      handlerInfo.preferredApplicationHandler = handlerApp;
-      handlerInfo.preferredAction = Ci.nsIHandlerInfo.useHelperApp;
-
-      handlerInfo.store();
+      // Add the app to the type's list of possible handlers.
+      let handlerInfo = this._handledTypes[this._list.selectedItem.type];
+      handlerInfo.possibleApplicationHandlers.appendElement(handlerApp, false);
     }
 
-    // We rebuild the actions menu whether the user picked an app or canceled.
+    // Rebuild the actions menu whether the user picked an app or canceled.
     // If they picked an app, we want to add the app to the menu and select it.
     // If they canceled, we want to go back to their previous selection.
     this.rebuildActionsMenu();
+
+    // If the user picked a new app from the menu, select it.
+    if (handlerApp) {
+      let typeItem = this._list.selectedItem;
+      let actionsMenu =
+        document.getAnonymousElementByAttribute(typeItem, "class", "actionsMenu");
+      let menuItems = actionsMenu.menupopup.childNodes;
+      for (let i = 0; i < menuItems.length; i++) {
+        let menuItem = menuItems[i];
+        if (menuItem.handlerApp && menuItem.handlerApp.equals(handlerApp)) {
+          actionsMenu.selectedIndex = i;
+          this.onSelectAction(menuItem);
+          break;
+        }
+      }
+    }
   },
 
   // Mark which item in the list was last selected so we can reselect it
   // when we rebuild the list or when the user returns to the prefpane.
   onSelectionChanged: function() {
     if (this._list.selectedItem)
       this._list.setAttribute("lastSelectedType",
                               this._list.selectedItem.getAttribute("type"));
--- a/browser/components/preferences/content.js
+++ b/browser/components/preferences/content.js
@@ -257,11 +257,21 @@ var gContentPane = {
   /**
    * Displays the colors dialog, where default web page/link/etc. colors can be
    * configured.
    */
   configureColors: function ()
   {
     document.documentElement.openSubDialog("chrome://browser/content/preferences/colors.xul",
                                            "", null);  
-  }
+  },
+
+  // LANGUAGES
 
+  /**
+   * Shows a dialog in which the preferred language for web content may be set.
+   */
+  showLanguages: function ()
+  {
+    document.documentElement.openSubDialog("chrome://browser/content/preferences/languages.xul",
+                                           "", null);
+  }
 };
--- a/browser/components/preferences/content.xul
+++ b/browser/components/preferences/content.xul
@@ -197,11 +197,24 @@
                     label="&colors.label;"
                     accesskey="&colors.accesskey;"
                     oncommand="gContentPane.configureColors();"/>
           </row>
         </rows>
       </grid>
     </groupbox>
 
+    <!-- Languages -->
+    <groupbox id="languagesGroup">
+      <caption label="&languages.label;"/>
+
+      <hbox id="languagesBox" align="center">
+        <description flex="1" control="chooseLanguage">&chooseLanguage.label;</description>
+        <button id="chooseLanguage"
+                label="&chooseButton.label;"
+                accesskey="&chooseButton.accesskey;"
+                oncommand="gContentPane.showLanguages();"/>
+      </hbox>
+    </groupbox>
+
   </prefpane>
 
 </overlay>
--- a/browser/components/preferences/handlers.xml
+++ b/browser/components/preferences/handlers.xml
@@ -79,17 +79,17 @@
       <xul:hbox flex="1" equalsize="always">
         <xul:hbox flex="1" align="center">
           <xul:image src="moz-icon://goat?size=16"
                      xbl:inherits="src=typeIcon" height="16" width="16"/>
           <xul:label flex="1" crop="end" xbl:inherits="value=typeDescription"/>
         </xul:hbox>
         <xul:hbox flex="1">
           <xul:menulist class="actionsMenu" flex="1" crop="end" selectedIndex="1"
-                        oncommand="gApplicationsPane.onSelectAction(event)">
+                        oncommand="gApplicationsPane.onSelectAction(event.originalTarget)">
             <xul:menupopup/>
           </xul:menulist>
         </xul:hbox>
       </xul:hbox>
     </content>
 
     <implementation>
       <constructor>
--- a/browser/components/preferences/security.xul
+++ b/browser/components/preferences/security.xul
@@ -54,20 +54,23 @@
       <!-- XXX buttons -->
       <preference id="pref.privacy.disable_button.view_passwords"
                   name="pref.privacy.disable_button.view_passwords"
                   type="bool"/>
       <preference id="pref.privacy.disable_button.view_passwords_exceptions"
                   name="pref.privacy.disable_button.view_passwords_exceptions"
                   type="bool"/>
 
-      <!-- Add-ons, phishing -->
+      <!-- Add-ons, malware, phishing -->
       <preference id="xpinstall.whitelist.required"
                   name="xpinstall.whitelist.required"
                   type="bool"/>
+      <preference id="browser.safebrowsing.malware.enabled"
+                  name="browser.safebrowsing.malware.enabled"
+                  type="bool"/>
       <preference id="browser.safebrowsing.enabled"
                   name="browser.safebrowsing.enabled"
                   type="bool"
                   onchange="gSecurityPane.onSBChange();"/>
       <preference id="browser.safebrowsing.remoteLookups"
                   name="browser.safebrowsing.remoteLookups"
                   type="bool"/>
       <preference id="browser.safebrowsing.dataProvider"
@@ -94,17 +97,20 @@
                   onsyncfrompreference="return gSecurityPane.readWarnAddonInstall();"/>
         <button id="addonExceptions"
                 label="&addonExceptions.label;"
                 accesskey="&addonExceptions.accesskey;"
                 oncommand="gSecurityPane.showAddonExceptions();"/>
       </hbox>
 
       <separator class="thin"/>
-
+      <checkbox id="tellMaybeAttackSite"
+                label="&tellMaybeAttackSite.label;"
+                accesskey="&tellMaybeAttackSite.accesskey;"
+                preference="browser.safebrowsing.malware.enabled" />
       <checkbox id="tellMaybeForgery"
                 label="&tellMaybeForgery.label;"
                 accesskey="&tellMaybeForgery.accesskey;"
                 preference="browser.safebrowsing.enabled"
                 onsyncfrompreference="return gSecurityPane.readCheckPhish();"/>
       <radiogroup id="checkPhishChoice" class="indent"
                   preference="browser.safebrowsing.remoteLookups"
                   onsynctopreference="return gSecurityPane.writePhishChoice();">
--- a/browser/components/preferences/selectBookmark.xul
+++ b/browser/components/preferences/selectBookmark.xul
@@ -20,17 +20,17 @@
           src="chrome://browser/content/preferences/selectBookmark.js"/>
   
   <description>&selectBookmark.label;</description>
 
   <separator class="thin"/>
 
   <tree id="bookmarks" flex="1" type="places" 
         style="height: 15em;" 
-        place="place:folder=2&amp;group=3&amp;excludeQueries=1"
+        place="place:folder=2&amp;excludeQueries=1"
         hidecolumnpicker="true"
         seltype="single"
         ondblclick="SelectBookmarkDialog.onItemDblClick();"
         onselect="SelectBookmarkDialog.selectionChanged();">
     <treecols>
       <treecol id="title" flex="1" primary="true" hideheader="true"/>
     </treecols>
     <treechildren id="bookmarksChildren" flex="1"/>
--- a/browser/components/sessionstore/src/nsSessionStore.js
+++ b/browser/components/sessionstore/src/nsSessionStore.js
@@ -800,18 +800,18 @@ SessionStoreService.prototype = {
         tabs.push(tabData);
         continue;
       }
       else if (browser.parentNode.__SS_data && browser.parentNode.__SS_data._tab) {
         // use the data to be restored when the tab hasn't been completely loaded
         tabs.push(browser.parentNode.__SS_data);
         continue;
       }
+
       var history = null;
-      
       try {
         history = browser.sessionHistory;
       }
       catch (ex) { } // this could happen if we catch a tab during (de)initialization
       
       if (history && browser.parentNode.__SS_data && browser.parentNode.__SS_data.entries[history.index]) {
         tabData = browser.parentNode.__SS_data;
         tabData.index = history.index + 1;
@@ -823,32 +823,38 @@ SessionStoreService.prototype = {
         tabData.index = history.index + 1;
         
         browser.parentNode.__SS_data = tabData;
       }
       else {
         tabData.entries[0] = { url: browser.currentURI.spec };
         tabData.index = 1;
       }
+
       tabData.zoom = browser.markupDocumentViewer.textZoom;
       
-      var disallow = CAPABILITIES.filter(function(aCapability) {
-        return !browser.docShell["allow" + aCapability];
-      });
-      tabData.disallow = disallow.join(",");
+      var disallow = [];
+      for (let i = 0; i < CAPABILITIES.length; i++) {
+        if (!browser.docShell["allow" + CAPABILITIES[i]])
+          disallow.push(CAPABILITIES[i]); 
+      }
+      if (disallow.length != 0)
+        tabData.disallow = disallow.join(",");
       
-      var _this = this;
-      var xulattr = Array.filter(tabbrowser.mTabs[i].attributes, function(aAttr) {
-        return (_this.xulAttributes.indexOf(aAttr.name) > -1);
-      }).map(function(aAttr) {
-        return aAttr.name + "=" + encodeURI(aAttr.value);
-      });
-      tabData.xultab = xulattr.join(" ");
+      if (this.xulAttributes.length != 0) {
+        var xulattr = Array.filter(tabbrowser.mTabs[i].attributes, function(aAttr) {
+          return (this.xulAttributes.indexOf(aAttr.name) > -1);
+        }, this).map(function(aAttr) {
+          return aAttr.name + "=" + encodeURI(aAttr.value);
+        });
+        tabData.xultab = xulattr.join(" ");
+      }
       
-      tabData.extData = tabbrowser.mTabs[i].__SS_extdata || null;
+      if (tabbrowser.mTabs[i].__SS_extdata)
+        tabData.extData = tabbrowser.mTabs[i].__SS_extdata;
       
       tabs.push(tabData);
       
       if (browser == tabbrowser.selectedBrowser) {
         this._windows[aWindow.__SSi].selected = i + 1;
       }
     }
   },
@@ -856,41 +862,44 @@ SessionStoreService.prototype = {
   /**
    * Get an object that is a serialized representation of a History entry
    * Used for data storage
    * @param aEntry
    *        nsISHEntry instance
    * @returns object
    */
   _serializeHistoryEntry: function sss_serializeHistoryEntry(aEntry) {
-    var entry = { url: aEntry.URI.spec, children: [] };
+    var entry = { url: aEntry.URI.spec };
     
     if (aEntry.title && aEntry.title != entry.url) {
       entry.title = aEntry.title;
     }
     if (aEntry.isSubFrame) {
       entry.subframe = true;
     }
     if (!(aEntry instanceof Ci.nsISHEntry)) {
       return entry;
     }
     
     var cacheKey = aEntry.cacheKey;
-    if (cacheKey && cacheKey instanceof Ci.nsISupportsPRUint32) {
+    if (cacheKey && cacheKey instanceof Ci.nsISupportsPRUint32 &&
+        cacheKey.data != 0) {
       // XXXbz would be better to have cache keys implement
       // nsISerializable or something.
       entry.cacheKey = cacheKey.data;
     }
     entry.ID = aEntry.ID;
     
-    entry.contentType = aEntry.contentType;
+    if (aEntry.contentType)
+      entry.contentType = aEntry.contentType;
     
     var x = {}, y = {};
     aEntry.getScrollPosition(x, y);
-    entry.scroll = x.value + "," + y.value;
+    if (x.value != 0 || y.value != 0)
+      entry.scroll = x.value + "," + y.value;
     
     try {
       var prefPostdata = this._prefBranch.getIntPref("sessionstore.postdata");
       if (prefPostdata && aEntry.postData && this._checkPrivacyLevel(aEntry.URI.schemeIs("https"))) {
         aEntry.postData.QueryInterface(Ci.nsISeekableStream).
                         seek(Ci.nsISeekableStream.NS_SEEK_SET, 0);
         var stream = Cc["@mozilla.org/binaryinputstream;1"].
                      createInstance(Ci.nsIBinaryInputStream);
@@ -934,23 +943,26 @@ SessionStoreService.prototype = {
       }
       catch (ex) { debug(ex); }
     }
     
     if (!(aEntry instanceof Ci.nsISHContainer)) {
       return entry;
     }
     
-    for (var i = 0; i < aEntry.childCount; i++) {
-      var child = aEntry.GetChildAt(i);
-      if (child) {
-        entry.children.push(this._serializeHistoryEntry(child));
-      }
-      else { // to maintain the correct frame order, insert a dummy entry 
-        entry.children.push({ url: "about:blank" });
+    if (aEntry.childCount > 0) {
+      entry.children = [];
+      for (var i = 0; i < aEntry.childCount; i++) {
+        var child = aEntry.GetChildAt(i);
+        if (child) {
+          entry.children.push(this._serializeHistoryEntry(child));
+        }
+        else { // to maintain the correct frame order, insert a dummy entry 
+          entry.children.push({ url: "about:blank" });
+        }
       }
     }
     
     return entry;
   },
 
   /**
    * Updates the current document's cache of user entered text data
@@ -1044,17 +1056,18 @@ SessionStoreService.prototype = {
               data.cache = encodeURI(data.element.value);
             }
             text.push(data.id + "=" + data.cache);
           }
         }
         if (aBrowser.currentURI.spec == "about:config") {
           text = ["#textbox=" + encodeURI(aBrowser.contentDocument.getElementById("textbox").wrappedJSObject.value)];
         }
-        tabData.text = text.join(" ");
+        if (text.length != 0)
+          tabData.text = text.join(" ");
         
         updateRecursively(aBrowser.contentWindow, tabData.entries[tabData.index - 1]);
       }
       catch (ex) { debug(ex); } // get as much data as possible, ignore failures (might succeed the next time)
     }, this);
   },
 
   /**
@@ -1134,24 +1147,39 @@ SessionStoreService.prototype = {
    * Store window dimensions, visibility, sidebar
    * @param aWindow
    *        Window reference
    */
   _updateWindowFeatures: function sss_updateWindowFeatures(aWindow) {
     var winData = this._windows[aWindow.__SSi];
     
     WINDOW_ATTRIBUTES.forEach(function(aAttr) {
-      winData[aAttr] = this._getWindowDimension(aWindow, aAttr);
+      var value = this._getWindowDimension(aWindow, aAttr);
+      switch (aAttr) {
+        case "screenX":
+        case "screenY":
+          if (value != 0)
+            winData[aAttr] = value;
+          break;
+        default:
+          winData[aAttr] = value;
+      }
     }, this);
     
-    winData.hidden = WINDOW_HIDEABLE_FEATURES.filter(function(aItem) {
-      return aWindow[aItem] && !aWindow[aItem].visible;
-    }).join(",");
-    
-    winData.sidebar = aWindow.document.getElementById("sidebar-box").getAttribute("sidebarcommand");
+    var hidden = [];
+    WINDOW_HIDEABLE_FEATURES.forEach(function(aItem) {
+      if (aWindow[aItem] && !aWindow[aItem].visible)
+        hidden.push(aItem);
+    });
+    if (hidden.length != 0)
+      winData.hidden = hidden.join(",");
+
+    var sidebar = aWindow.document.getElementById("sidebar-box").getAttribute("sidebarcommand");
+    if (sidebar)
+      winData.sidebar = sidebar;
   },
 
   /**
    * serialize session data as Ini-formatted string
    * @returns string
    */
   _getCurrentState: function sss_getCurrentState() {
     var activeWindow = this._getMostRecentBrowserWindow();
@@ -1463,41 +1491,46 @@ SessionStoreService.prototype = {
   _deserializeHistoryEntry: function sss_deserializeHistoryEntry(aEntry, aIdMap) {
     var shEntry = Cc["@mozilla.org/browser/session-history-entry;1"].
                   createInstance(Ci.nsISHEntry);
     
     var ioService = Cc["@mozilla.org/network/io-service;1"].
                     getService(Ci.nsIIOService);
     shEntry.setURI(ioService.newURI(aEntry.url, null, null));
     shEntry.setTitle(aEntry.title || aEntry.url);
-    shEntry.setIsSubFrame(aEntry.subframe || false);
+    if (aEntry.subframe)
+      shEntry.setIsSubFrame(aEntry.subframe || false);
     shEntry.loadType = Ci.nsIDocShellLoadInfo.loadHistory;
-    shEntry.contentType = aEntry.contentType;
+    if (aEntry.contentType)
+      shEntry.contentType = aEntry.contentType;
     
     if (aEntry.cacheKey) {
       var cacheKey = Cc["@mozilla.org/supports-PRUint32;1"].
                      createInstance(Ci.nsISupportsPRUint32);
       cacheKey.data = aEntry.cacheKey;
       shEntry.cacheKey = cacheKey;
     }
+
     if (aEntry.ID) {
       // get a new unique ID for this frame (since the one from the last
       // start might already be in use)
       var id = aIdMap[aEntry.ID] || 0;
       if (!id) {
         for (id = Date.now(); aIdMap.used[id]; id++);
         aIdMap[aEntry.ID] = id;
         aIdMap.used[id] = true;
       }
       shEntry.ID = id;
     }
     
-    var scrollPos = (aEntry.scroll || "0,0").split(",");
-    scrollPos = [parseInt(scrollPos[0]) || 0, parseInt(scrollPos[1]) || 0];
-    shEntry.setScrollPosition(scrollPos[0], scrollPos[1]);
+    if (aEntry.scroll) {
+      var scrollPos = (aEntry.scroll || "0,0").split(",");
+      scrollPos = [parseInt(scrollPos[0]) || 0, parseInt(scrollPos[1]) || 0];
+      shEntry.setScrollPosition(scrollPos[0], scrollPos[1]);
+    }
 
     var postdata;
     if (aEntry.postdata_b64) {  // Firefox 3
       postdata = atob(aEntry.postdata_b64);
     } else if (aEntry.postdata) { // Firefox 2
       postdata = aEntry.postdata;
     }
 
--- a/browser/installer/windows/packages-static
+++ b/browser/installer/windows/packages-static
@@ -29,22 +29,25 @@ bin\uninstall\helper.exe
 bin\updater.ini
 bin\dictionaries\*
 
 [xpcom]
 bin\js3250.dll
 bin\plc4.dll
 bin\plds4.dll
 bin\xpcom.dll
+bin\nspr4.dll
+#ifdef MOZ_ENABLE_LIBXUL
+bin\xul.dll
+#else
 bin\xpcom_core.dll
 bin\xpistub.dll
-bin\nspr4.dll
-bin\xul.dll
 bin\components\xpinstal.dll
 bin\components\jar50.dll
+#endif
 bin\Microsoft.VC80.CRT.manifest
 bin\msvcm80.dll
 bin\msvcp80.dll
 bin\msvcr80.dll
 
 [browser]
 ; [Base Browser Files]
 bin\@MOZ_APP_NAME@.exe
@@ -116,17 +119,19 @@ bin\components\find.xpt
 bin\components\fuel.xpt
 bin\components\gfx.xpt
 bin\components\htmlparser.xpt
 bin\components\imglib2.xpt
 bin\components\imgicon.xpt
 bin\components\intl.xpt
 bin\components\jar.xpt
 bin\components\jsconsole-clhandler.js
+#ifndef MOZ_ENABLE_LIBXUL
 bin\components\jsd3250.dll
+#endif
 bin\components\jsdservice.xpt
 bin\components\layout_base.xpt
 bin\components\layout_printing.xpt
 bin\components\layout_xul.xpt
 bin\components\layout_xul_tree.xpt
 bin\components\inspector.xpt
 bin\components\locale.xpt
 bin\components\lwbrk.xpt
@@ -149,38 +154,34 @@ bin\components\necko_socket.xpt
 bin\components\necko_viewsource.xpt
 bin\components\oji.xpt
 bin\components\loginmgr.xpt
 bin\components\places.xpt
 bin\components\plugin.xpt
 bin\components\pref.xpt
 bin\components\prefetch.xpt
 bin\components\profile.xpt
-bin\components\progressDlg.xpt
 bin\components\proxyObject.xpt
 bin\components\rdf.xpt
 bin\components\satchel.xpt
 bin\components\saxparser.xpt
 bin\components\shistory.xpt
-bin\components\signonviewer.xpt
 bin\components\storage.xpt
 bin\components\toolkitprofile.xpt
 bin\components\txtsvc.xpt
 bin\components\txmgr.xpt
+#ifdef MOZ_USE_NATIVE_UCONV
 bin\components\ucnative.xpt
+#endif
 bin\components\uconv.xpt
 bin\components\unicharutil.xpt
 bin\components\uriloader.xpt
-bin\components\wallet.xpt
-bin\components\walleteditor.xpt
-bin\components\walletpreview.xpt
 bin\components\webBrowser_core.xpt
 bin\components\webbrowserpersist.xpt
 bin\components\webshell_idls.xpt
-bin\components\websrvcs.xpt
 bin\components\widget.xpt
 bin\components\windowds.xpt
 bin\components\windowwatcher.xpt
 bin\components\shellservice.xpt
 bin\components\xpcom_base.xpt
 bin\components\xpcom_system.xpt
 bin\components\xpcom_components.xpt
 bin\components\xpcom_ds.xpt
@@ -198,17 +199,16 @@ bin\components\FeedProcessor.js
 bin\components\FeedConverter.js
 bin\components\FeedWriter.js
 bin\components\fuelApplication.js
 bin\components\WebContentConverter.js
 bin\components\nsBrowserContentHandler.js
 bin\components\nsBrowserGlue.js
 bin\components\nsSetDefaultBrowser.js
 bin\components\nsTryToClose.js
-bin\components\nsDictionary.js
 bin\components\nsHelperAppDlg.js
 bin\components\nsDownloadManagerUI.js
 bin\components\nsProxyAutoConfig.js
 bin\components\nsSearchService.js
 bin\components\nsSearchSuggestions.js
 bin\components\nsSidebar.js
 bin\components\nsExtensionManager.js
 bin\components\nsBlocklistService.js
--- a/browser/locales/en-US/chrome/browser/browser.dtd
+++ b/browser/locales/en-US/chrome/browser/browser.dtd
@@ -162,28 +162,23 @@
 
 <!ENTITY viewMenu.label         "View"> 
 <!ENTITY viewMenu.accesskey       "V"> 
 <!ENTITY viewToolbarsMenu.label       "Toolbars"> 
 <!ENTITY viewToolbarsMenu.accesskey     "T"> 
 <!ENTITY viewSidebarMenu.label "Sidebar">
 <!ENTITY viewSidebarMenu.accesskey "e">
 <!ENTITY viewCustomizeToolbar.label       "Customize..."> 
-<!ENTITY viewCustomizeToolbar.accesskey     "C"> 
+<!ENTITY viewCustomizeToolbar.accesskey     "C">
 
-<!-- XXX historyMenu entities are used with or without places (bug 336058) -->
 <!ENTITY historyMenu.label "History">
 <!ENTITY historyMenu.accesskey "s">
 <!ENTITY historyUndoMenu.label "Recently Closed Tabs">
 
-<!-- XXX places only -->
 <!ENTITY historyHomeCmd.label "Home">
-<!-- XXX remove below if places sticks -->
-<!ENTITY goHomeCmd.label "Home">
-<!-- XXX remove above if places sticks --> 
 <!ENTITY historyShowSidebarCmd.label "Show in Sidebar">
 
 <!ENTITY openCmd.commandkey           "l">
 <!ENTITY urlbar.accesskey             "d">
 
 <!-- 
   Comment duplicated from browser-sets.inc:
 
--- a/browser/locales/en-US/chrome/browser/places/places.dtd
+++ b/browser/locales/en-US/chrome/browser/places/places.dtd
@@ -204,10 +204,9 @@
 
 <!ENTITY forwardCmd.label       "Forward">
 <!ENTITY forwardCmd.accesskey   "F">
 <!ENTITY forwardButton.tooltip  "Go forward">
 
 <!ENTITY detailsPane.more.label "More">
 <!ENTITY detailsPane.less.label "Less">
 <!ENTITY detailsPane.noPreviewAvailable.label "Preview">
-<!ENTITY detailsPane.selectAnItemText.description
-         "Select an item to view and edit its properties">
+<!ENTITY detailsPane.selectAnItemText.description "Select an item to view and edit its properties">
--- a/browser/locales/en-US/chrome/browser/places/places.properties
+++ b/browser/locales/en-US/chrome/browser/places/places.properties
@@ -92,8 +92,16 @@ EnterExport=Export Bookmarks File
 
 saveSearch.title=Save Search
 saveSearch.inputLabel=Name:
 saveSearch.defaultText=New Query
 
 detailsPane.noItems=No items
 detailsPane.oneItem=One item
 detailsPane.multipleItems=%S items
+
+placesFolderTitle=Places
+recentlyCreatedBookmarksTitle=Recently Starred Pages
+recentlyVisitedBookmarksTitle=Recently Visited Starred Pages
+mostVisitedBookmarksTitle=Most Visited Starred Pages
+recentlyUsedTagsTitle=Recently Used Tags
+mostUsedTagsTitle=Most Used Tags
+mostVisitedSitesTitle=Most Visited Pages
--- a/browser/locales/en-US/chrome/browser/preferences/advanced.dtd
+++ b/browser/locales/en-US/chrome/browser/preferences/advanced.dtd
@@ -1,10 +1,10 @@
 <!-- Note: due to bug 143065, the only remaining accesskeys available to be used
-     in the Advanced pane are: "j", "q", "z" -->
+     in the Advanced pane are: "j", "o", "q", "z" -->
 
 <!ENTITY generalTab.label                "General">
 
 <!ENTITY accessibility.label             "Accessibility">
 
 <!ENTITY useCursorNavigation.label       "Always use the cursor keys to navigate within pages">
 <!ENTITY useCursorNavigation.accesskey   "c">
 <!ENTITY searchStartTyping.label         "Search for text when I start typing">
@@ -16,23 +16,16 @@
 
 <!ENTITY useAutoScroll.label             "Use autoscrolling">
 <!ENTITY useAutoScroll.accesskey         "a">
 <!ENTITY useSmoothScrolling.label        "Use smooth scrolling">
 <!ENTITY useSmoothScrolling.accesskey    "m">
 <!ENTITY checkSpelling.label             "Check my spelling as I type">
 <!ENTITY checkSpelling.accesskey         "t">
 
-<!ENTITY languages.label                 "Languages">
-
-<!ENTITY chooseLanguage.label            "Choose your preferred language for displaying pages">
-<!ENTITY chooseButton.label              "Choose...">
-<!ENTITY chooseButton.accesskey          "o">
-
-
 <!ENTITY networkTab.label                "Network">
 
 <!ENTITY connection.label                "Connection">
 
 <!ENTITY connectionDesc.label            "Configure how &brandShortName; connects to the Internet">
 <!ENTITY connectionSettings.label        "Settings...">
 <!ENTITY connectionSettings.accesskey    "e">
 
--- a/browser/locales/en-US/chrome/browser/preferences/content.dtd
+++ b/browser/locales/en-US/chrome/browser/preferences/content.dtd
@@ -24,8 +24,14 @@
 <!ENTITY  defaultSize.label           "Size:">
 <!ENTITY  defaultSize.accesskey       "S">
 
 <!ENTITY  advancedFonts.label         "Advanced...">
 <!ENTITY  advancedFonts.accesskey     "A">
 
 <!ENTITY  colors.label                "Colors...">
 <!ENTITY  colors.accesskey            "C">
+
+
+<!ENTITY languages.label              "Languages">
+<!ENTITY chooseLanguage.label         "Choose your preferred language for displaying pages">
+<!ENTITY chooseButton.label           "Choose...">
+<!ENTITY chooseButton.accesskey       "o">
--- a/browser/locales/en-US/chrome/browser/preferences/preferences.properties
+++ b/browser/locales/en-US/chrome/browser/preferences/preferences.properties
@@ -56,16 +56,21 @@ alwaysAsk=Always ask
 # %1$S = plugin name (for example "QuickTime Plugin-in 7.2")
 # %2$S = brandShortName from brand.properties (for example "Minefield")
 pluginName=%S (in %S)
 
 # LOCALIZATION NOTE (previewInApp, liveBookmarksInApp): %S = brandShortName
 previewInApp=Preview in %S
 liveBookmarksInApp=Live Bookmarks in %S
 
+# LOCALIZATION NOTE (typeDescriptionWithType):
+# %1$S = type description (for example "Portable Document Format")
+# %2$S = type (for example "application/pdf")
+typeDescriptionWithType=%S (%S)
+
 
 #### Cookie Viewer
 
 hostColon=Host:
 domainColon=Domain:
 forSecureOnly=Encrypted connections only
 forAnyConnection=Any type of connection
 AtEndOfSession = at end of session
--- a/browser/locales/en-US/chrome/browser/preferences/security.dtd
+++ b/browser/locales/en-US/chrome/browser/preferences/security.dtd
@@ -1,18 +1,21 @@
 <!ENTITY  warnAddonInstall.label        "Warn me when sites try to install add-ons">
 <!ENTITY  warnAddonInstall.accesskey    "W">
 
-<!-- LOCALIZATION NOTE (tellMaybeForgery.label):
-  The methods by which forged (phished) sites will be detected by phishing
-  providers will vary from human review to machine-based heuristics to a
-  combination of both, so it's important that this string and
+<!-- LOCALIZATION NOTE (tellMaybeForgery.label, tellMaybeAttackSite.label):
+  The methods by which forged (phished) and attack sites will be detected by
+  phishing providers will vary from human review to machine-based heuristics to a
+  combination of both, so it's important that these strings and
   useDownloadedList.label convey the meaning "suspected" (and not something like
   "known").
 -->
+<!ENTITY  tellMaybeAttackSite.label     "Tell me if the site I'm visiting is a suspected attack site">
+<!ENTITY  tellMaybeAttackSite.accesskey "k">
+
 <!ENTITY  tellMaybeForgery.label     "Tell me if the site I'm visiting is a suspected forgery">
 <!ENTITY  tellMaybeForgery.accesskey "T">
 
 <!ENTITY  useDownloadedList.label     "Check using a downloaded list of suspected sites">
 <!ENTITY  useDownloadedList.accesskey "d">
 
 <!-- LOCALIZATION NOTE (askThirdParty.label):
   The entities askThirdParty.label and askThirdPartyAfter.label appear on a
--- a/browser/locales/en-US/chrome/help/prefs.xhtml
+++ b/browser/locales/en-US/chrome/help/prefs.xhtml
@@ -274,16 +274,28 @@ Contributors:
       and this &pref.singular; has no effect on those sites.</p>
 
     <p><em>Allow pages to choose their own colors, instead of my selections
       above</em><br/>
       By default, &brandShortName; uses the colors specified by the web page
       author. Disabling this &pref.singular; will force all sites to use your
       default colors instead.</p>
 
+  <h3 id="languages">Languages</h3>
+  <p>Some web pages are offered in more than one language. Click the
+    <em>Choose...</em> button to specify your preferred language or
+    languages.</p>
+
+  <p><strong>Languages Dialog</strong><br/>
+    To add a language, click <em>Select a language to add...</em>, choose the
+    language, and click the <em>Add</em> button.  Remove a language by
+    selecting it in the list of active languages and clicking the
+    <em>Remove</em> button. You can also reorder languages using the <em>Move
+    Up</em> and <em>Move Down</em> buttons to determine the most preferred one
+    in case a page is provided in multiple languages .</p>
 
 <h2 id="applications_options">Applications &pref.pluralCaps;</h2>
 
 <p>The <em>Applications</em> panel lets you choose applications and other
   handlers to handle different types of content (e.g. PDF documents).  It shows
   you a list of content types and lets you select a handler for each type.</p>
 
 <p>You can choose a local application to handle any type.  For some types,
@@ -531,29 +543,16 @@ Contributors:
       When this preference is enabled, &brandShortName; will check your spelling
       and offer possible corrections as you type in web forms.  Note that you
       may need to download a dictionary; to do so, <span
       class="noMac">right-click</span><span class="mac">press &ctrlKey; and
       click</span> on any text field, enable spellchecking if necessary, and
       then use the provided <span class="menuPath">Languages</span> menu to
       download a dictionary.</p>
 
-    <h4 id="languages">Languages</h4>
-    <p>Some web pages are offered in more than one language. Click the
-      <em>Choose...</em> button to specify your preferred language or
-      languages.</p>
-
-    <p><strong>Languages Dialog</strong><br/>
-      To add a language, click <em>Select a language to add...</em>, choose the
-      language, and click the <em>Add</em> button.  Remove a language by
-      selecting it in the list of active languages and clicking the
-      <em>Remove</em> button.  You can also reorder languages using the <em>Move
-      Up</em> and <em>Move Down</em> buttons to determine the most preferred one
-      in case a page is provided in multiple languages .</p>
-
   <h3 id="advanced_network">Network tab</h3>
 
     <h4 id="connection_settings">Connection</h4>
     <p>Your organization or Internet service provider may offer or require you
       to use a proxy.  A proxy acts as an intermediary between your computer and
       the Internet.  It intercepts all requests to the Internet to see if it can
       fulfill the request using its cache.  Proxies are used to improve
       performance, filter requests, and hide your computer from the Internet to
@@ -647,47 +646,52 @@ Contributors:
 
     <p><em>Use TLS 1.0</em><br/>
       Specifies whether you want to send and receive secured information through
       TLS (Transport Layer Security), a security standard similar to SSL3
       (Secure Sockets Layer).  Disabling it will prevent you from visiting some
       sites.</p>
 
     <h4 id="certificates">Certificates</h4>
-    <p>Certificates help perform encryption and decryption of connections to
-      <a href="glossary.xhtml#secure_site">secure sites</a>.</p>
+    <p><a href="glossary.xhtml#certificate">Certificates</a> help perform
+      encryption and decryption of connections to <a
+      href="glossary.xhtml#secure_site">secure sites</a>.</p>
 
     <p><em>When a web site requires a certificate:</em><br/>
-      When a web site requests a secure connection, &brandShortName; will by
-      default automatically use an appropriate certificate.  If you wish to
-      manually choose a certificate (for example, if you wish to use a certain
-      type of encryption instead of what is automatically selected), select the
-      &pref.singular; <em>Ask me every time</em> and you'll be in complete
-      control of what certificates you use while browsing.</p>
+      Some servers ask you to identify yourself with a personal certificate. In
+      order to do so, they ask &brandShortName; to generate one for you. When
+      you visit the site in the future, &brandShortName; selects the certificate
+      without asking you by default. If you wish to manually choose a
+      certificate (for example, if you have multiple certificates stored for
+      multiple web sites), select the <em>Ask me every time</em> &pref.singular;
+      and you'll be in complete control of what certificates are being sent to
+      web sites while browsing.</p>
 
     <p><em>View Certificates</em><br/>
       Click this button to view stored certificates, import new certificates,
       and back up or delete old certificates in &brandShortName;.</p>
 
     <p><em>Revocation Lists</em><br/>
       &brandShortName; can use Certificate Revocation Lists (also known as
       CRLs) to ensure that your certificates are always valid.  Click the
       <em>Revocation Lists</em> button to manage the CRLs installed on your
       computer.</p>
 
-    <p><em>Verification</em><br/>
-      &brandShortName; verify the validity of your certificates using OCSP
-      (Online Certificate Status Protocol) every time they are viewed or used.
-      &brandShortName; does not use OCSP by default, but if you want to enable
-      it, you can do so here.  You will most likely only need to change this if
-      your Internet environment requires it.</p>
+    <p><em>Validation</em><br/>
+      &brandShortName; may ask an OCSP (Online Certificate Status Protocol)
+      server to confirm that a certificate is still valid. By default,
+      &brandShortName; validates a certificate if the certificate provides an
+      OCSP server. Alternately, you can choose an OCSP server against which to
+      validate all certificates. Click the <em>Validation</em> button to manage
+      these &pref.plural;. You will most likely only need to change this if your
+      Internet environment requires it.</p>
 
     <p><em>Security Devices</em><br/>
       Security devices can encrypt and decrypt connections and store
       certificates and passwords.  If you need to use a security device other
       than the one in &brandShortName;, click the <em>Security Devices</em>
       button.</p>
 
-<div class="contentsBox"><em>07 October 2007</em></div>
+<div class="contentsBox"><em>09 October 2007</em></div>
 <p>Copyright &copy; &copyright.years; Contributors to the Mozilla Help Viewer Project.</p>
 
 </body>
 </html>
--- a/browser/modules/Sanitizer.jsm
+++ b/browser/modules/Sanitizer.jsm
@@ -131,16 +131,24 @@ Sanitizer.prototype = {
         globalHistory.removeAllPages();
         
         try {
           var os = Components.classes["@mozilla.org/observer-service;1"]
                              .getService(Components.interfaces.nsIObserverService);
           os.notifyObservers(null, "browser:purge-session-history", "");
         }
         catch (e) { }
+        
+        // Clear last URL of the Open Web Location dialog
+        var prefs = Components.classes["@mozilla.org/preferences-service;1"]
+                              .getService(Components.interfaces.nsIPrefBranch2);
+        try {
+          prefs.clearUserPref("general.open_location.last_url");
+        }
+        catch (e) { }
       },
       
       get canClear()
       {
         // bug 347231: Always allow clearing history due to dependencies on
         // the browser:purge-session-history notification. (like error console)
         return true;
       }
--- a/browser/themes/pinstripe/browser/browser.css
+++ b/browser/themes/pinstripe/browser/browser.css
@@ -65,16 +65,20 @@
 }
 
 /* ----- BOOKMARK BUTTONS ----- */	
 
 .bookmark-item[container] {
   list-style-image: url("chrome://global/skin/tree/folder.png");
 }
 
+.query-item[container] {
+  list-style-image: url("chrome://browser/skin/places/query.png");
+}
+
 toolbarbutton.bookmark-item:hover
 {
   background: url("chrome://global/skin/toolbar/toolbarbutton-customhover-left.png") no-repeat left center;
 }
 
 toolbarbutton.bookmark-item:hover:active, toolbarbutton.bookmark-item[open="true"] {
   background:url("chrome://browser/skin/bookmark-open-left.png") no-repeat left center;
 }
--- a/browser/themes/winstripe/browser/browser.css
+++ b/browser/themes/winstripe/browser/browser.css
@@ -237,16 +237,22 @@ menuitem.bookmark-item {
   -moz-image-region: rect(0px, 32px, 16px, 16px) !important;
 }
 
 .bookmark-item[type="menu"][livemark="true"][open="true"],
 .bookmark-item[type="menu"][livemark="true"][open="true"][chromedir="rtl"] { 
   -moz-image-region: rect(16px, 32px, 32px, 16px) !important;
 }
 
+/* ::::: query items ::::: */
+
+.query-item[container] {
+  list-style-image: url("chrome://browser/skin/places/query.png");
+}
+
 /* ::::: primary toolbar buttons ::::: */
 
 .toolbarbutton-1 {
   -moz-box-orient: vertical;
   min-width: 0;
   list-style-image: url("chrome://browser/skin/Toolbar.png");
 }
 
--- a/browser/themes/winstripe/browser/places/places.css
+++ b/browser/themes/winstripe/browser/places/places.css
@@ -1,8 +1,20 @@
+/* Sidebars */
+
+page > .placesTree > treechildren::-moz-tree-cell(leaf) ,
+page > .placesTree > treechildren::-moz-tree-image(leaf) {
+  cursor: pointer;
+}
+
+page > .placesTree > treechildren::-moz-tree-cell-text(leaf, hover) {
+  cursor: pointer;
+  text-decoration: underline;
+}
+
 /* Toolbar */
 #placesToolbar {
   border: none;
 }
 
 /* back button */
 
 #back-button {
--- a/client.py
+++ b/client.py
@@ -1,12 +1,12 @@
 #!/usr/bin/python
 
-NSPR_CO_TAG = 'NSPR_HEAD_20070820'
-NSS_CO_TAG  = 'NSS_3_12_ALPHA1B'
+NSPR_CO_TAG = 'NSPR_HEAD_20071009'
+NSS_CO_TAG  = 'NSS_3_12_ALPHA_2'
 
 NSPR_DIRS = ('nsprpub',)
 NSS_DIRS  = ('dbm',
              'security/nss',
              'security/coreconf',
              'security/dbm')
 
 # URL of the default hg repository to clone for Tamarin.
--- a/config/autoconf.mk.in
+++ b/config/autoconf.mk.in
@@ -71,16 +71,18 @@ DIST		= $(DEPTH)/dist
 LIBXUL_SDK      = @LIBXUL_SDK@
 
 ifdef LIBXUL_SDK
 LIBXUL_DIST = $(LIBXUL_SDK)
 else
 LIBXUL_DIST = $(DIST)
 endif
 
+XULRUNNER_STUB_NAME = @XULRUNNER_STUB_NAME@
+
 MOZ_CHROME_FILE_FORMAT	= @MOZ_CHROME_FILE_FORMAT@
 
 MOZ_WIDGET_TOOLKIT	= @MOZ_WIDGET_TOOLKIT@
 MOZ_GFX_TOOLKIT		= @MOZ_GFX_TOOLKIT@
 MOZ_X11			= @MOZ_X11@
 
 MOZ_JS_LIBS		   = @MOZ_JS_LIBS@
 
@@ -582,16 +584,17 @@ MOZ_DISTRIBUTION_ID = @MOZ_DISTRIBUTION_
 MINIMO		= @MINIMO@
 
 MACOS_SDK_DIR	= @MACOS_SDK_DIR@
 NEXT_ROOT	= @NEXT_ROOT@
 GCC_VERSION	= @GCC_VERSION@
 XCODEBUILD_VERSION= @XCODEBUILD_VERSION@
 HAS_XCODE_2_1	= @HAS_XCODE_2_1@
 UNIVERSAL_BINARY= @UNIVERSAL_BINARY@
+HAVE_DTRACE= @HAVE_DTRACE@
 
 VISIBILITY_FLAGS = @VISIBILITY_FLAGS@
 WRAP_SYSTEM_INCLUDES = @WRAP_SYSTEM_INCLUDES@
 
 MOZ_V1_STRING_ABI = @MOZ_V1_STRING_ABI@
 
 MOZ_EMBEDDING_LEVEL_DEFAULT = @MOZ_EMBEDDING_LEVEL_DEFAULT@
 MOZ_EMBEDDING_LEVEL_BASIC = @MOZ_EMBEDDING_LEVEL_BASIC@
--- a/config/config.mk
+++ b/config/config.mk
@@ -526,17 +526,17 @@ endif
 INCLUDES	= $(LOCAL_INCLUDES) $(REQ_INCLUDES) $(REQ_INCLUDES_SDK) -I$(PUBLIC) $(OS_INCLUDES)
 
 ifndef MOZILLA_INTERNAL_API
 INCLUDES	+= -I$(LIBXUL_DIST)/sdk/include
 endif
 
 CFLAGS		= $(OS_CFLAGS)
 CXXFLAGS	= $(OS_CXXFLAGS)
-LDFLAGS		= $(OS_LDFLAGS)
+LDFLAGS		= $(OS_LDFLAGS) $(MOZ_FIX_LINK_PATHS)
 
 # Allow each module to override the *default* optimization settings
 # by setting MODULE_OPTIMIZE_FLAGS if the developer has not given
 # arguments to --enable-optimize
 ifdef MOZ_OPTIMIZE
 ifeq (1,$(MOZ_OPTIMIZE))
 ifdef MODULE_OPTIMIZE_FLAGS
 CFLAGS		+= $(MODULE_OPTIMIZE_FLAGS)
--- a/config/rules.mk
+++ b/config/rules.mk
@@ -302,16 +302,18 @@ ifndef NO_GEN_XPT
 MDDEPFILES		+= $(addprefix $(MDDEPDIR)/,$(XPIDLSRCS:.idl=.xpt)) \
 			   $(addprefix $(MDDEPDIR)/,$(SDK_XPIDLSRCS:.idl=.xpt))
 endif
 endif
 endif
 
 ALL_TRASH = \
 	$(GARBAGE) $(TARGETS) $(OBJS) $(PROGOBJS) LOGS TAGS a.out \
+	$(OBJS:.$(OBJ_SUFFIX)=.s) $(OBJS:.$(OBJ_SUFFIX)=.ii) \
+	$(OBJS:.$(OBJ_SUFFIX)=.i) \
 	$(HOST_PROGOBJS) $(HOST_OBJS) $(IMPORT_LIBRARY) $(DEF_FILE)\
 	$(EXE_DEF_FILE) so_locations _gen _stubs $(wildcard *.res) $(wildcard *.RES) \
 	$(wildcard *.pdb) $(CODFILE) $(MAPFILE) $(IMPORT_LIBRARY) \
 	$(SHARED_LIBRARY:$(DLL_SUFFIX)=.exp) $(wildcard *.ilk) \
 	$(PROGRAM:$(BIN_SUFFIX)=.exp) $(SIMPLE_PROGRAMS:$(BIN_SUFFIX)=.exp) \
 	$(PROGRAM:$(BIN_SUFFIX)=.lib) $(SIMPLE_PROGRAMS:$(BIN_SUFFIX)=.lib) \
 	$(SIMPLE_PROGRAMS:$(BIN_SUFFIX)=.$(OBJ_SUFFIX)) \
 	$(wildcard gts_tmp_*) $(LIBRARY:%.a=.%.timestamp)
@@ -976,16 +978,22 @@ ifneq (,$(filter OSF1 BSD_OS FreeBSD Net
 CLEANUP1	:= | egrep -v '(________64ELEL_|__.SYMDEF)'
 CLEANUP2	:= rm -f ________64ELEL_ __.SYMDEF
 else
 CLEANUP2	:= true
 endif
 SUB_LOBJS	= $(shell for lib in $(SHARED_LIBRARY_LIBS); do $(AR_LIST) $${lib} $(CLEANUP1); done;)
 endif
 endif
+ifdef MOZILLA_PROBE_LIBS
+PROBE_LOBJS	= $(shell for lib in $(MOZILLA_PROBE_LIBS); do $(AR_LIST) $${lib} $(CLEANUP1); done;)
+endif
+ifdef DTRACE_PROBE_OBJ
+EXTRA_DEPS += $(DTRACE_PROBE_OBJ)
+endif
 
 $(LIBRARY): $(OBJS) $(LOBJS) $(SHARED_LIBRARY_LIBS) $(EXTRA_DEPS) Makefile Makefile.in
 	rm -f $@
 ifneq (,$(GNU_LD)$(filter-out OS2 WINNT WINCE, $(OS_ARCH)))
 ifdef SHARED_LIBRARY_LIBS
 	@rm -f $(SUB_LOBJS)
 	@for lib in $(SHARED_LIBRARY_LIBS); do $(AR_EXTRACT) $${lib}; $(CLEANUP2); done
 endif
@@ -1065,17 +1073,36 @@ ifdef IS_COMPONENT
 endif
 endif
 ifdef NO_LD_ARCHIVE_FLAGS
 ifdef SHARED_LIBRARY_LIBS
 	@rm -f $(SUB_SHLOBJS)
 	@for lib in $(SHARED_LIBRARY_LIBS); do $(AR_EXTRACT) $${lib}; $(CLEANUP2); done
 endif # SHARED_LIBRARY_LIBS
 endif # NO_LD_ARCHIVE_FLAGS
-	$(MKSHLIB) $(SHLIB_LDSTARTFILE) $(OBJS) $(LOBJS) $(SUB_SHLOBJS) $(RESFILE) $(LDFLAGS) $(EXTRA_DSO_LDOPTS) $(OS_LIBS) $(EXTRA_LIBS) $(DEF_FILE) $(SHLIB_LDENDFILE)
+ifdef NEED_DTRACE_PROBE_OBJ
+	@rm -f $(PROBE_LOBJS)
+	@for lib in $(MOZILLA_PROBE_LIBS); do $(AR_EXTRACT) $${lib}; $(CLEANUP2); done
+	dtrace -G -C -32 -s $(MOZILLA_DTRACE_SRC) -o  $(NEED_DTRACE_PROBE_OBJ) $(PROBE_LOBJS)
+	@for lib in $(MOZILLA_PROBE_LIBS); do \
+		ofiles=`$(AR_LIST) $${lib}`; \
+		$(AR_DELETE) $${lib} $$ofiles; \
+	done
+	$(MKSHLIB) $(SHLIB_LDSTARTFILE) $(OBJS) $(LOBJS) $(SUB_SHLOBJS) $(NEED_DTRACE_PROBE_OBJ) $(PROBE_LOBJS) $(RESFILE) $(LDFLAGS) $(EXTRA_DSO_LDOPTS) $(OS_LIBS) $(EXTRA_LIBS) $(DEF_FILE) $(SHLIB_LDENDFILE)
+	@rm -f $(PROBE_LOBJS)
+	@rm -f $(NEED_DTRACE_PROBE_OBJ)
+	@for lib in $(MOZILLA_PROBE_LIBS); do \
+		if [ -L $${lib} ]; then rm -f `readlink $${lib}`; fi; \
+	done
+	@rm -f $(MOZILLA_PROBE_LIBS)
+
+else
+	$(MKSHLIB) $(SHLIB_LDSTARTFILE) $(OBJS) $(DTRACE_PROBE_OBJ) $(LOBJS) $(SUB_SHLOBJS) $(RESFILE) $(LDFLAGS) $(EXTRA_DSO_LDOPTS) $(OS_LIBS) $(EXTRA_LIBS) $(DEF_FILE) $(SHLIB_LDENDFILE)
+endif # NEED_DTRACE_PROBE_OBJ
+
 ifeq (_WINNT,$(GNU_CC)_$(OS_ARCH))
 ifdef MSMANIFEST_TOOL
 ifdef EMBED_MANIFEST_AT
 	@if test -f $@.manifest; then \
 		mt.exe -NOLOGO -MANIFEST $@.manifest -OUTPUTRESOURCE:$@\;$(EMBED_MANIFEST_AT); \
 		rm -f $@.manifest; \
 	fi
 endif   # EMBED_MANIFEST_AT
@@ -1184,24 +1211,26 @@ host_%.$(OBJ_SUFFIX): %.mm Makefile Make
 %.$(OBJ_SUFFIX): %.c Makefile Makefile.in
 	$(REPORT_BUILD)
 	@$(MAKE_DEPS_AUTO_CC)
 	$(ELOG) $(CC) $(OUTOPTION)$@ -c $(COMPILE_CFLAGS) $(_VPATH_SRCS)
 
 moc_%.cpp: %.h Makefile Makefile.in
 	$(MOC) $< $(OUTOPTION)$@ 
 
+ifdef ASFILES
 # The AS_DASH_C_FLAG is needed cause not all assemblers (Solaris) accept
 # a '-c' flag.
 %.$(OBJ_SUFFIX): %.$(ASM_SUFFIX) Makefile Makefile.in
 ifeq ($(MOZ_OS2_TOOLS),VACPP)
 	$(AS) -Fdo:./$(OBJDIR) -Feo:.$(OBJ_SUFFIX) $(ASFLAGS) $(AS_DASH_C_FLAG) $<
 else
 	$(AS) -o $@ $(ASFLAGS) $(AS_DASH_C_FLAG) $(_VPATH_SRCS)
 endif
+endif
 
 %.$(OBJ_SUFFIX): %.S Makefile Makefile.in
 	$(AS) -o $@ $(ASFLAGS) -c $<
 
 %: %.cpp Makefile Makefile.in
 	@$(MAKE_DEPS_AUTO_CXX)
 	$(CCC) $(OUTOPTION)$@ $(CXXFLAGS) $(_VPATH_SRCS) $(LDFLAGS)
 
@@ -1984,17 +2013,16 @@ ifneq (,$(filter 1200 1300 1310,$(_MSC_V
 .NOTPARALLEL:
 endif
 
 #
 # Re-define the list of default suffixes, so gmake won't have to churn through
 # hundreds of built-in suffix rules for stuff we don't need.
 #
 .SUFFIXES:
-.SUFFIXES: .out .a .ln .o .c .cc .C .cpp .y .l .s .S .h .sh .i .pl .class .java .html .pp .mk .in .$(OBJ_SUFFIX) .m .mm .idl $(BIN_SUFFIX)
 
 #
 # Fake targets.  Always run these rules, even if a file/directory with that
 # name already exists.
 #
 .PHONY: all all_platforms alltags boot checkout chrome realchrome clean clobber clobber_all export install libs makefiles realclean run_viewer run_apprunner tools $(DIRS) $(TOOL_DIRS) FORCE check check-interactive
 
 # Used as a dependency to force targets to rebuild
--- a/config/system-headers
+++ b/config/system-headers
@@ -133,16 +133,19 @@ CPString.cpp
 CPString.h
 crtdbg.h
 crt_externs.h
 crypt.h
 cstdio
 cstdlib
 cstring
 ctype.h
+curl/curl.h
+curl/easy.h
+curl/types.h
 curses.h
 cxxabi.h
 DateTimeUtils.h
 dbus/dbus.h
 dbus/dbus-glib.h
 dbus/dbus-glib-lowlevel.h
 ddeml.h
 Debug.h
--- a/configure.in
+++ b/configure.in
@@ -884,17 +884,17 @@ MOZ_JPEG_LIBS='$(call EXPAND_LIBNAME_PAT
 MOZ_ZLIB_CFLAGS=
 MOZ_ZLIB_LIBS='$(call EXPAND_LIBNAME_PATH,mozz,$(DEPTH)/modules/zlib/src)'
 MOZ_PNG_CFLAGS=
 MOZ_PNG_LIBS='$(call EXPAND_LIBNAME_PATH,mozpng,$(DEPTH)/modules/libimg/png)'
 
 MOZ_JS_LIBS='-L$(LIBXUL_DIST)/bin -lmozjs'
 DYNAMIC_XPCOM_LIBS='-L$(LIBXUL_DIST)/bin -lxpcom -lxpcom_core'
 MOZ_FIX_LINK_PATHS='-Wl,-rpath-link,$(LIBXUL_DIST)/bin'
-XPCOM_FROZEN_LDOPTS='-L$(LIBXUL_DIST)/bin $(MOZ_FIX_LINK_PATHS) -lxpcom'
+XPCOM_FROZEN_LDOPTS='-L$(LIBXUL_DIST)/bin -lxpcom'
 LIBXUL_LIBS='$(XPCOM_FROZEN_LDOPTS) -lxul'
 XPCOM_GLUE_LDOPTS='$(LIBXUL_DIST)/lib/$(LIB_PREFIX)xpcomglue_s.$(LIB_SUFFIX) $(XPCOM_FROZEN_LDOPTS)'
 XPCOM_STANDALONE_GLUE_LDOPTS='$(LIBXUL_DIST)/lib/$(LIB_PREFIX)xpcomglue.$(LIB_SUFFIX)'
 
 MOZ_COMPONENT_NSPR_LIBS='-L$(LIBXUL_DIST)/bin $(NSPR_LIBS)'
 MOZ_XPCOM_OBSOLETE_LIBS='-L$(LIBXUL_DIST)/lib -lxpcom_compat'
 
 USE_DEPENDENT_LIBS=1
@@ -2802,16 +2802,29 @@ AC_CHECK_HEADERS(mmintrin.h)
 dnl Check whether the compiler supports the new-style C++ standard
 dnl library headers (i.e. <new>) or needs the old "new.h"
 AC_LANG_CPLUSPLUS
 NEW_H=new.h
 AC_CHECK_HEADER(new, [NEW_H=new])
 AC_DEFINE_UNQUOTED(NEW_H, <$NEW_H>)
 AC_LANG_C
 
+AC_ARG_ENABLE(dtrace,
+              build with dtrace support if available (default=no),
+              [enable_dtrace="yes"],)
+if test "x$enable_dtrace" = "xyes"; then
+  AC_CHECK_HEADER(sys/sdt.h, HAVE_DTRACE=1)
+  if test -n "$HAVE_DTRACE"; then
+      AC_DEFINE(INCLUDE_MOZILLA_DTRACE)
+  else
+      AC_MSG_ERROR([dtrace enabled but sys/std.h not found]);
+  fi
+fi
+AC_SUBST(HAVE_DTRACE)
+
 case $target in
 *-aix4.3*|*-aix5*)
 	;;
 *)
 	AC_CHECK_HEADERS(sys/cdefs.h)
 	;;
 esac
 
@@ -4346,16 +4359,31 @@ minimal)
   AC_MSG_ERROR([Unrecognized value: --with-embedding-profile=$MOZ_EMBEDDING_PROFILE])
   ;;
 esac
 
 AC_SUBST(MOZ_EMBEDDING_LEVEL_DEFAULT)
 AC_SUBST(MOZ_EMBEDDING_LEVEL_BASIC)
 AC_SUBST(MOZ_EMBEDDING_LEVEL_MINIMAL)
 
+MOZ_ARG_WITH_STRING(xulrunner-stub-name,
+[  --with-xulrunner-stub-name=appname   Create the xulrunner stub with the given name],
+  XULRUNNER_STUB_NAME=$withval)
+
+if test -z "$XULRUNNER_STUB_NAME"; then
+  case "$target_os" in
+  darwin*)
+    XULRUNNER_STUB_NAME=xulrunner
+    ;;
+  *)
+    XULRUNNER_STUB_NAME=xulrunner-stub
+  esac
+fi
+AC_SUBST(XULRUNNER_STUB_NAME)
+
 if test -z "$MOZ_BUILD_APP"; then
   AC_MSG_ERROR([--enable-application=APP was not specified and is required.])
 else
   # We have a valid application only if it has a build.mk file in its top
   # directory.
   if test ! -f "${srcdir}/${MOZ_BUILD_APP}/build.mk" ; then
     AC_MSG_ERROR([--enable-application value not recognized (${MOZ_BUILD_APP}/build.mk does not exist).])
   fi
--- a/content/base/public/nsContentUtils.h
+++ b/content/base/public/nsContentUtils.h
@@ -1093,16 +1093,23 @@ public:
    * @param aIsUserTriggered whether the user triggered the link. This would be
    *                         false for loads from auto XLinks or from the
    *                         click() method if we ever implement it.
    */
   static void TriggerLink(nsIContent *aContent, nsPresContext *aPresContext,
                           nsIURI *aLinkURI, const nsString& aTargetSpec,
                           PRBool aClick, PRBool aIsUserTriggered);
 
+  /**
+   * Return true if aContent or one of its ancestors in the
+   * bindingParent chain is native anonymous.
+   */
+  static PRBool IsNativeAnonymous(nsIContent* aContent);
+
+
 private:
 
   static PRBool InitializeEventTable();
 
   static nsresult doReparentContentWrapper(nsIContent *aChild,
                                            JSContext *cx,
                                            JSObject *aOldGlobal,
                                            JSObject *aNewGlobal,
--- a/content/base/public/nsIContent.h
+++ b/content/base/public/nsIContent.h
@@ -46,17 +46,16 @@
 
 // Forward declarations
 class nsIAtom;
 class nsIDocument;
 class nsPresContext;
 class nsVoidArray;
 class nsIDOMEvent;
 class nsIContent;
-class nsISupportsArray;
 class nsIEventListenerManager;
 class nsIURI;
 class nsICSSStyleRule;
 class nsRuleWalker;
 class nsAttrValue;
 class nsAttrName;
 class nsTextFragment;
 class nsIDocShell;
--- a/content/base/public/nsIDocument.h
+++ b/content/base/public/nsIDocument.h
@@ -72,17 +72,16 @@ class nsIDOMDocumentFragment;
 class nsILineBreaker;
 class nsIWordBreaker;
 class nsISelection;
 class nsIChannel;
 class nsIPrincipal;
 class nsIDOMDocument;
 class nsIDOMDocumentType;
 class nsIObserver;
-class nsISupportsArray;
 class nsScriptLoader;
 class nsIContentSink;
 class nsIScriptEventManager;
 class nsNodeInfoManager;
 class nsICSSLoader;
 class nsHTMLStyleSheet;
 class nsIHTMLCSSStyleSheet;
 class nsILayoutHistoryState;
--- a/content/base/public/nsINode.h
+++ b/content/base/public/nsINode.h
@@ -93,18 +93,20 @@ enum {
   NODE_IS_EDITABLE =             0x00000100U,
 
   // Optimizations to quickly check whether element may have ID, class or style
   // attributes. Not all element implementations may use these!
   NODE_MAY_HAVE_ID =             0x00000200U,
   NODE_MAY_HAVE_CLASS =          0x00000400U,
   NODE_MAY_HAVE_STYLE =          0x00000800U,
 
+  NODE_IS_INSERTION_PARENT =     0x00001000U,
+
   // Four bits for the script-type ID
-  NODE_SCRIPT_TYPE_OFFSET =               12,
+  NODE_SCRIPT_TYPE_OFFSET =               13,
 
   NODE_SCRIPT_TYPE_SIZE =                  4,
 
   // Remaining bits are node type specific.
   NODE_TYPE_SPECIFIC_BITS_OFFSET =
     NODE_SCRIPT_TYPE_OFFSET + NODE_SCRIPT_TYPE_SIZE
 };
 
--- a/content/base/src/nsContentIterator.cpp
+++ b/content/base/src/nsContentIterator.cpp
@@ -37,17 +37,16 @@
  * ***** END LICENSE BLOCK ***** */
 
 #include "nsISupports.h"
 #include "nsIDOMNodeList.h"
 #include "nsIContentIterator.h"
 #include "nsRange.h"
 #include "nsIContent.h"
 #include "nsIDOMText.h"
-#include "nsISupportsArray.h"
 #include "nsCOMPtr.h"
 #include "nsPresContext.h"
 #include "nsIComponentManager.h"
 #include "nsContentCID.h"
 #include "nsLayoutCID.h"
 #include "nsVoidArray.h"
 #include "nsContentUtils.h"
 #include "nsINode.h"
--- a/content/base/src/nsContentUtils.cpp
+++ b/content/base/src/nsContentUtils.cpp
@@ -3680,8 +3680,28 @@ nsContentUtils::TriggerLink(nsIContent *
                                                   aLinkURI, flag);
   }
 
   // Only pass off the click event if the script security manager says it's ok.
   if (NS_SUCCEEDED(proceed)) {
     handler->OnLinkClick(aContent, aLinkURI, aTargetSpec.get());
   }
 }
+
+PRBool
+nsContentUtils::IsNativeAnonymous(nsIContent* aContent)
+{
+  while (aContent) {
+    nsIContent* bindingParent = aContent->GetBindingParent();
+    if (bindingParent == aContent) {
+      NS_ASSERTION(bindingParent->IsNativeAnonymous() ||
+                   bindingParent->IsNodeOfType(nsINode::eXUL),
+                   "Bogus binding parent?");
+      return PR_TRUE;
+    }
+
+    NS_ASSERTION(!aContent->IsNativeAnonymous(),
+                 "Native anonymous node with wrong binding parent");
+    aContent = bindingParent;
+  }
+
+  return PR_FALSE;
+}
--- a/content/base/src/nsDocumentEncoder.cpp
+++ b/content/base/src/nsDocumentEncoder.cpp
@@ -64,17 +64,16 @@
 #include "nsIDOMNodeList.h"
 #include "nsIDOMRange.h"
 #include "nsIDOMDocument.h"
 #include "nsICharsetConverterManager.h"
 #include "nsGkAtoms.h"
 #include "nsIContent.h"
 #include "nsIEnumerator.h"
 #include "nsISelectionPrivate.h"
-#include "nsISupportsArray.h"
 #include "nsIParserService.h"
 #include "nsIScriptContext.h"
 #include "nsIScriptGlobalObject.h"
 #include "nsIScriptSecurityManager.h"
 #include "nsContentUtils.h"
 #include "nsUnicharUtils.h"
 #include "nsReadableUtils.h"
 
--- a/content/canvas/src/nsCanvasRenderingContext2D.cpp
+++ b/content/canvas/src/nsCanvasRenderingContext2D.cpp
@@ -1151,52 +1151,67 @@ nsCanvasRenderingContext2D::GetShadowCol
 //
 
 NS_IMETHODIMP
 nsCanvasRenderingContext2D::ClearRect(float x, float y, float w, float h)
 {
     if (!FloatValidate(x,y,w,h))
         return NS_ERROR_DOM_SYNTAX_ERR;
 
+    cairo_path_t *old_path = cairo_copy_path (mCairo);
     cairo_save (mCairo);
     cairo_set_operator (mCairo, CAIRO_OPERATOR_CLEAR);
     cairo_new_path (mCairo);
     cairo_rectangle (mCairo, x, y, w, h);
     cairo_fill (mCairo);
     cairo_restore (mCairo);
+    cairo_new_path (mCairo);
+    if (old_path->status == CAIRO_STATUS_SUCCESS && old_path->num_data != 0)
+        cairo_append_path (mCairo, old_path);
+    cairo_path_destroy (old_path);
 
     return Redraw();
 }
 
 NS_IMETHODIMP
 nsCanvasRenderingContext2D::FillRect(float x, float y, float w, float h)
 {
     if (!FloatValidate(x,y,w,h))
         return NS_ERROR_DOM_SYNTAX_ERR;
 
+    cairo_path_t *old_path = cairo_copy_path (mCairo);
     cairo_new_path (mCairo);
     cairo_rectangle (mCairo, x, y, w, h);
 
     ApplyStyle(STYLE_FILL);
     cairo_fill (mCairo);
+    cairo_new_path (mCairo);
+    if (old_path->status == CAIRO_STATUS_SUCCESS && old_path->num_data != 0)
+        cairo_append_path (mCairo, old_path);
+    cairo_path_destroy (old_path);
 
     return Redraw();
 }
 
 NS_IMETHODIMP
 nsCanvasRenderingContext2D::StrokeRect(float x, float y, float w, float h)
 {
     if (!FloatValidate(x,y,w,h))
         return NS_ERROR_DOM_SYNTAX_ERR;
 
+    cairo_path_t *old_path = cairo_copy_path (mCairo);
     cairo_new_path (mCairo);
     cairo_rectangle (mCairo, x, y, w, h);
 
     ApplyStyle(STYLE_STROKE);
     cairo_stroke (mCairo);
+    cairo_new_path (mCairo);
+    if (old_path->status == CAIRO_STATUS_SUCCESS && old_path->num_data != 0)
+        cairo_append_path (mCairo, old_path);
+    cairo_path_destroy (old_path);
 
     return Redraw();
 }
 
 //
 // path bits
 //
 
@@ -1863,17 +1878,18 @@ nsCanvasRenderingContext2D::DrawImage()
     nsCOMPtr<nsIDOMElement> imgElt;
     if (!ConvertJSValToXPCObject(getter_AddRefs(imgElt),
                                  NS_GET_IID(nsIDOMElement),
                                  ctx, argv[0]))
         return NS_ERROR_DOM_TYPE_MISMATCH_ERR;
 
     cairo_surface_t *imgSurf = nsnull;
     cairo_matrix_t surfMat;
-    cairo_pattern_t* pat;
+    cairo_pattern_t *pat;
+    cairo_path_t *old_path;
     PRUint8 *imgData = nsnull;
     PRInt32 imgWidth, imgHeight;
     nsCOMPtr<nsIURI> uri;
     PRBool forceWriteOnly = PR_FALSE;
     rv = CairoSurfaceFromElement(imgElt, &imgSurf, &imgData,
                                  &imgWidth, &imgHeight, getter_AddRefs(uri), &forceWriteOnly);
     if (NS_FAILED(rv))
         return rv;
@@ -1937,16 +1953,17 @@ nsCanvasRenderingContext2D::DrawImage()
         goto FINISH;
     }
 
     cairo_matrix_init_translate(&surfMat, sx, sy);
     cairo_matrix_scale(&surfMat, sw/dw, sh/dh);
     pat = cairo_pattern_create_for_surface(imgSurf);
     cairo_pattern_set_matrix(pat, &surfMat);
 
+    old_path = cairo_copy_path(mCairo);
     cairo_save(mCairo);
     cairo_translate(mCairo, dx, dy);
     cairo_new_path(mCairo);
     cairo_rectangle(mCairo, 0, 0, dw, dh);
     cairo_set_source(mCairo, pat);
     cairo_clip(mCairo);
     cairo_paint_with_alpha(mCairo, CurrentState().globalAlpha);
     cairo_restore(mCairo);
@@ -1961,16 +1978,21 @@ nsCanvasRenderingContext2D::DrawImage()
     // away in this function earlier.
     cairo_new_path(mCairo);
     cairo_rectangle(mCairo, 0, 0, 0, 0);
     cairo_fill(mCairo);
 #endif
 
     cairo_pattern_destroy(pat);
 
+    cairo_new_path(mCairo);
+    if (old_path->status == CAIRO_STATUS_SUCCESS && old_path->num_data != 0)
+        cairo_append_path(mCairo, old_path);
+    cairo_path_destroy(old_path);
+
 FINISH:
     if (imgSurf)
         cairo_surface_destroy(imgSurf);
 
     if (NS_SUCCEEDED(rv))
         rv = Redraw();
 
     return rv;
@@ -2118,17 +2140,17 @@ nsCanvasRenderingContext2D::CairoSurface
                                      getter_AddRefs(imgRequest));
         NS_ENSURE_SUCCESS(rv, rv);
         if (!imgRequest)
             // XXX ERRMSG we need to report an error to developers here! (bug 329026)
             return NS_ERROR_NOT_AVAILABLE;
 
         PRUint32 status;
         imgRequest->GetImageStatus(&status);
-        if (status != imgIRequest::STATUS_LOAD_COMPLETE)
+        if ((status & imgIRequest::STATUS_LOAD_COMPLETE) == 0)
             return NS_ERROR_NOT_AVAILABLE;
 
         nsCOMPtr<nsIURI> uri;
         rv = imageLoader->GetCurrentURI(uriOut);
         NS_ENSURE_SUCCESS(rv, rv);
 
         *forceWriteOnlyOut = PR_FALSE;
 
@@ -2587,23 +2609,28 @@ nsCanvasRenderingContext2D::PutImageData
         for (int32 i = 0; i < y; i++) {
             memcpy(dest, imgPtr + (w*4)*i, w*4);
             dest += stride;
         }
     } else {
         imgsurf = cairo_image_surface_create_for_data (imageBuffer.get(),
                                                        CAIRO_FORMAT_ARGB32,
                                                        w, h, w*4);
+        cairo_path_t *old_path = cairo_copy_path (mCairo);
         cairo_save (mCairo);
         cairo_identity_matrix (mCairo);
         cairo_translate (mCairo, x, y);
         cairo_new_path (mCairo);
         cairo_rectangle (mCairo, 0, 0, w, h);
         cairo_set_source_surface (mCairo, imgsurf, 0, 0);
         cairo_set_operator (mCairo, CAIRO_OPERATOR_SOURCE);
         cairo_fill (mCairo);
         cairo_restore (mCairo);
+        cairo_new_path (mCairo);
+        if (old_path->status == CAIRO_STATUS_SUCCESS && old_path->num_data != 0)
+            cairo_append_path (mCairo, old_path);
+        cairo_path_destroy (old_path);
 
         cairo_surface_destroy (imgsurf);
     }
 
     return Redraw();
 }
--- a/content/html/content/public/nsIFormProcessor.h
+++ b/content/html/content/public/nsIFormProcessor.h
@@ -46,27 +46,29 @@
 #define nsIFormProcessor_h__
 
 #include "nsISupports.h"
 #include "prtypes.h"
 
 #include "nsIDOMHTMLInputElement.h"
 
 class nsString;
-class nsVoidArray;
+class nsStringArray;
 
 // {0ae53c0f-8ea2-4916-bedc-717443c3e185}
 #define NS_FORMPROCESSOR_CID \
 { 0x0ae53c0f, 0x8ea2, 0x4916, { 0xbe, 0xdc, 0x71, 0x74, 0x43, 0xc3, 0xe1, 0x85 } }
 
 #define NS_FORMPROCESSOR_CONTRACTID "@mozilla.org/layout/form-processor;1"
 
-// 4ff86376-6982-4f64-a683-a6ae4984afd7
+// 6d4ea1aa-a6b2-43bd-a19d-3f0f26750df3
 #define NS_IFORMPROCESSOR_IID      \
-{ 0x4ff86376, 0x6982, 0x4f64, { 0xa6, 0x83, 0xa6, 0xae, 0x49, 0x84, 0xaf, 0xd7 } }
+{ 0x6d4ea1aa, 0xa6b2, 0x43bd, \
+ { 0xa1, 0x9d, 0x3f, 0x0f, 0x26, 0x75, 0x0d, 0xf3 } }
+
 
 
 
 // XXX:In the future, we should examine combining this interface with nsIFormSubmitObserver.
 // nsIFormSubmitObserver could have a before, during, and after form submission methods.
 // The before and after methods would be passed a nsISupports interface. The During would
 // Have the same method signature as ProcessValue.
 
@@ -96,17 +98,17 @@ public:
    *  
    *   @param aFormType   Type of form to get content for.
    *   @param aOptions    List of nsStrings which define the contents for the form element
    *   @param aAttr       Attribute to be attached to the form element. It is used to identify
    *                      the form element contains non-standard content.
    */
 
   NS_IMETHOD ProvideContent(const nsAString& aFormType, 
-                            nsVoidArray& aContent,
+                            nsStringArray& aContent,
                             nsAString& aAttribute) = 0;
 
 };
 
 NS_DEFINE_STATIC_IID_ACCESSOR(nsIFormProcessor, NS_IFORMPROCESSOR_IID)
 
 #endif /* nsIFormProcessor_h__ */
 
--- a/content/html/content/src/nsGenericHTMLElement.h
+++ b/content/html/content/src/nsGenericHTMLElement.h
@@ -47,17 +47,16 @@
 #include "nsGkAtoms.h"
 
 class nsIDOMAttr;
 class nsIDOMEventListener;
 class nsIDOMNodeList;
 class nsIFrame;
 class nsMappedAttributes;
 class nsIStyleRule;
-class nsISupportsArray;
 class nsChildContentList;
 class nsDOMCSSDeclaration;
 class nsIDOMCSSStyleDeclaration;
 class nsIURI;
 class nsIFormControlFrame;
 class nsIForm;
 class nsPresState;
 class nsIScrollableView;
--- a/content/html/content/src/nsHTMLBodyElement.cpp
+++ b/content/html/content/src/nsHTMLBodyElement.cpp
@@ -47,17 +47,16 @@
 #include "nsIDocument.h"
 #include "nsIHTMLDocument.h"
 #include "nsHTMLStyleSheet.h"
 #include "nsIHTMLCSSStyleSheet.h"
 #include "nsICSSStyleRule.h"
 #include "nsIContentViewer.h"
 #include "nsIMarkupDocumentViewer.h"
 #include "nsMappedAttributes.h"
-#include "nsISupportsArray.h"
 #include "nsRuleData.h"
 #include "nsIFrame.h"
 #include "nsIDocShell.h"
 #include "nsIEditorDocShell.h"
 #include "nsCOMPtr.h"
 #include "nsRuleWalker.h"
 
 //----------------------------------------------------------------------
--- a/content/svg/content/src/Makefile.in
+++ b/content/svg/content/src/Makefile.in
@@ -66,17 +66,16 @@ REQUIRES	= xpcom \
 		  docshell \
 		  thebes
 
 CPPSRCS		= \
 		nsDOMSVGZoomEvent.cpp \
 		nsDOMSVGEvent.cpp \
 		nsSVGAElement.cpp \
 		nsSVGAngle.cpp \
-		nsSVGAnimatedAngle.cpp \
 		nsSVGAnimatedLengthList.cpp \
 		nsSVGAnimatedNumberList.cpp \
 		nsSVGAnimatedRect.cpp \
 		nsSVGAnimatedPreserveAspectRatio.cpp \
 		nsSVGAnimatedString.cpp \
 		nsSVGAnimatedTransformList.cpp \
 		nsSVGBoolean.cpp \
 		nsSVGCircleElement.cpp \
--- a/content/svg/content/src/nsSVGAngle.cpp
+++ b/content/svg/content/src/nsSVGAngle.cpp
@@ -31,365 +31,319 @@
  * 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 "nsSVGAngle.h"
 #include "prdtoa.h"
-#include "nsGkAtoms.h"
-#include "nsSVGValue.h"
-#include "nsReadableUtils.h"
 #include "nsTextFormatter.h"
-#include "nsCRT.h"
-#include "nsIDOMSVGNumber.h"
-#include "nsISVGValueUtils.h"
-#include "nsWeakReference.h"
-#include "nsContentUtils.h"
 #include "nsSVGUtils.h"
-#include <math.h>
-
-////////////////////////////////////////////////////////////////////////
-// nsSVGAngle class
 
-class nsSVGAngle : public nsIDOMSVGAngle,
-                   public nsSVGValue,
-                   public nsISVGValueObserver
+class DOMSVGAngle : public nsIDOMSVGAngle
 {
-protected:
-  friend nsresult NS_NewSVGAngle(nsIDOMSVGAngle** result,
-                                 float value,
-                                 PRUint16 unit);
-
-  friend nsresult NS_NewSVGAngle(nsIDOMSVGAngle** result,
-                                 const nsAString &value);
-  
-  nsSVGAngle(float value, PRUint16 unit);
-  nsSVGAngle();
-
 public:
-  // nsISupports interface:
   NS_DECL_ISUPPORTS
 
-  // nsIDOMSVGAngle interface:
-  NS_DECL_NSIDOMSVGANGLE
+  DOMSVGAngle()
+    { mVal.Init(); }
+    
+  NS_IMETHOD GetUnitType(PRUint16* aResult)
+    { *aResult = mVal.mSpecifiedUnitType; return NS_OK; }
+
+  NS_IMETHOD GetValue(float* aResult)
+    { *aResult = mVal.GetBaseValue(); return NS_OK; }
+  NS_IMETHOD SetValue(float aValue)
+    { mVal.SetBaseValue(aValue, nsnull); return NS_OK; }
+
+  NS_IMETHOD GetValueInSpecifiedUnits(float* aResult)
+    { *aResult = mVal.mBaseVal; return NS_OK; }
+  NS_IMETHOD SetValueInSpecifiedUnits(float aValue)
+    { mVal.mBaseVal = aValue; return NS_OK; }
 
-  // nsISVGValue interface:
-  NS_IMETHOD SetValueString(const nsAString& aValue);
-  NS_IMETHOD GetValueString(nsAString& aValue);
-  
-  // nsISVGValueObserver interface:
-  NS_IMETHOD WillModifySVGObservable(nsISVGValue* observable,
-                                     modificationType aModType);
-  NS_IMETHOD DidModifySVGObservable (nsISVGValue* observable,
-                                     modificationType aModType);
+  NS_IMETHOD SetValueAsString(const nsAString& aValue)
+    { return mVal.SetBaseValueString(aValue, nsnull, PR_FALSE); }
+  NS_IMETHOD GetValueAsString(nsAString& aValue)
+    { mVal.GetBaseValueString(aValue); return NS_OK; }
 
-  // nsISupportsWeakReference
-  // implementation inherited from nsSupportsWeakReference
-  
-protected:
-  // implementation helpers:
-  void  GetUnitString(nsAString& unit);
-  PRUint16 GetUnitTypeForString(const char* unitStr);
-  PRBool IsValidUnitType(PRUint16 unit);
+  NS_IMETHOD NewValueSpecifiedUnits(PRUint16 unitType,
+                                    float valueInSpecifiedUnits)
+    { mVal.NewValueSpecifiedUnits(unitType, valueInSpecifiedUnits, nsnull);
+      return NS_OK; }
 
-  float mValueInSpecifiedUnits;
-  PRUint8 mSpecifiedUnitType;
+  NS_IMETHOD ConvertToSpecifiedUnits(PRUint16 unitType)
+    { mVal.ConvertToSpecifiedUnits(unitType, nsnull); return NS_OK; }
+
+private:
+  nsSVGAngle mVal;
 };
 
+NS_IMPL_ADDREF(nsSVGAngle::DOMBaseVal)
+NS_IMPL_RELEASE(nsSVGAngle::DOMBaseVal)
 
-//----------------------------------------------------------------------
-// Implementation
+NS_IMPL_ADDREF(nsSVGAngle::DOMAnimVal)
+NS_IMPL_RELEASE(nsSVGAngle::DOMAnimVal)
+
+NS_IMPL_ADDREF(nsSVGAngle::DOMAnimatedAngle)
+NS_IMPL_RELEASE(nsSVGAngle::DOMAnimatedAngle)
+
+NS_IMPL_ADDREF(DOMSVGAngle)
+NS_IMPL_RELEASE(DOMSVGAngle)
+
+NS_INTERFACE_MAP_BEGIN(nsSVGAngle::DOMBaseVal)
+  NS_INTERFACE_MAP_ENTRY(nsIDOMSVGAngle)
+  NS_INTERFACE_MAP_ENTRY(nsISupports)
+  NS_INTERFACE_MAP_ENTRY_CONTENT_CLASSINFO(SVGAngle)
+NS_INTERFACE_MAP_END
 
-nsresult
-NS_NewSVGAngle(nsIDOMSVGAngle** result,
-               float value,
-               PRUint16 unit)
-{
-  nsSVGAngle *pl = new nsSVGAngle(value, unit);
-  NS_ENSURE_TRUE(pl, NS_ERROR_OUT_OF_MEMORY);
-  NS_ADDREF(pl);
-  *result = pl;
-  return NS_OK;
-}
+NS_INTERFACE_MAP_BEGIN(nsSVGAngle::DOMAnimVal)
+  NS_INTERFACE_MAP_ENTRY(nsIDOMSVGAngle)
+  NS_INTERFACE_MAP_ENTRY(nsISupports)
+  NS_INTERFACE_MAP_ENTRY_CONTENT_CLASSINFO(SVGAngle)
+NS_INTERFACE_MAP_END
 
-nsresult
-NS_NewSVGAngle(nsIDOMSVGAngle** result,
-               const nsAString &value)
+NS_INTERFACE_MAP_BEGIN(nsSVGAngle::DOMAnimatedAngle)
+  NS_INTERFACE_MAP_ENTRY(nsIDOMSVGAnimatedAngle)
+  NS_INTERFACE_MAP_ENTRY(nsISupports)
+  NS_INTERFACE_MAP_ENTRY_CONTENT_CLASSINFO(SVGAnimatedAngle)
+NS_INTERFACE_MAP_END
+
+NS_INTERFACE_MAP_BEGIN(DOMSVGAngle)
+  NS_INTERFACE_MAP_ENTRY(nsIDOMSVGAngle)
+  NS_INTERFACE_MAP_ENTRY(nsISupports)
+  NS_INTERFACE_MAP_ENTRY_CONTENT_CLASSINFO(SVGAngle)
+NS_INTERFACE_MAP_END
+
+static nsIAtom** const unitMap[] =
 {
-  *result = nsnull;
-  nsSVGAngle *pl = new nsSVGAngle();
-  NS_ENSURE_TRUE(pl, NS_ERROR_OUT_OF_MEMORY);
-  NS_ADDREF(pl);
-  if (NS_FAILED(pl->SetValueAsString(value))) {
-    NS_RELEASE(pl);
-    return NS_ERROR_FAILURE;
-  }
-  *result = pl;
-  return NS_OK;
-}  
+  nsnull, /* SVG_ANGLETYPE_UNKNOWN */
+  nsnull, /* SVG_ANGLETYPE_UNSPECIFIED */
+  &nsGkAtoms::deg,
+  &nsGkAtoms::rad,
+  &nsGkAtoms::grad
+};
+
+/* Helper functions */
 
-
-nsSVGAngle::nsSVGAngle(float value,
-                       PRUint16 unit)
-  : mValueInSpecifiedUnits(value)
+static PRBool
+IsValidUnitType(PRUint16 unit)
 {
-  NS_ASSERTION(unit == SVG_ANGLETYPE_UNKNOWN || IsValidUnitType(unit), "unknown unit");
-  mSpecifiedUnitType = unit;
-}
+  if (unit > nsIDOMSVGAngle::SVG_ANGLETYPE_UNKNOWN &&
+      unit <= nsIDOMSVGAngle::SVG_ANGLETYPE_GRAD)
+    return PR_TRUE;
 
-nsSVGAngle::nsSVGAngle()
-{
+  return PR_FALSE;
 }
 
-//----------------------------------------------------------------------
-// nsISupports methods:
-
-NS_IMPL_ADDREF(nsSVGAngle)
-NS_IMPL_RELEASE(nsSVGAngle)
-
-NS_INTERFACE_MAP_BEGIN(nsSVGAngle)
-  NS_INTERFACE_MAP_ENTRY(nsISVGValue)
-  NS_INTERFACE_MAP_ENTRY(nsISVGValueObserver)
-  NS_INTERFACE_MAP_ENTRY(nsIDOMSVGAngle)
-  NS_INTERFACE_MAP_ENTRY(nsISupportsWeakReference)
-  NS_INTERFACE_MAP_ENTRY_CONTENT_CLASSINFO(SVGAngle)
-  NS_INTERFACE_MAP_ENTRY_AMBIGUOUS(nsISupports, nsISVGValue)
-NS_INTERFACE_MAP_END
-
-//----------------------------------------------------------------------
-// nsISVGValue methods:
-NS_IMETHODIMP
-nsSVGAngle::SetValueString(const nsAString& aValue)
+static void 
+GetUnitString(nsAString& unit, PRUint16 unitType)
 {
-  return SetValueAsString(aValue);
-}
-
-NS_IMETHODIMP
-nsSVGAngle::GetValueString(nsAString& aValue)
-{
-  return GetValueAsString(aValue);
-}
+  if (IsValidUnitType(unitType)) {
+    if (unitMap[unitType]) {
+      (*unitMap[unitType])->ToString(unit);
+    }
+    return;
+  }
 
-//----------------------------------------------------------------------
-// nsISVGValueObserver methods
-
-NS_IMETHODIMP
-nsSVGAngle::WillModifySVGObservable(nsISVGValue* observable,
-                                    modificationType aModType)
-{
-  WillModify(aModType);
-  return NS_OK;
-}
-
-NS_IMETHODIMP
-nsSVGAngle::DidModifySVGObservable(nsISVGValue* observable,
-                                   modificationType aModType)
-{
-  DidModify(aModType);
-  return NS_OK;
-}
-
-//----------------------------------------------------------------------
-// nsIDOMSVGAngle methods:
-
-/* readonly attribute unsigned short unitType; */
-NS_IMETHODIMP
-nsSVGAngle::GetUnitType(PRUint16 *aUnitType)
-{
-  *aUnitType = mSpecifiedUnitType;
-  return NS_OK;
+  NS_NOTREACHED("Unknown unit type");
+  return;
 }
 
-/* attribute float value; */
-NS_IMETHODIMP
-nsSVGAngle::GetValue(float *aValue)
+static PRUint16
+GetUnitTypeForString(const char* unitStr)
 {
-  nsresult rv = NS_OK;
-  
-  switch (mSpecifiedUnitType) {
-  case SVG_ANGLETYPE_UNSPECIFIED:
-  case SVG_ANGLETYPE_DEG:
-    *aValue = float((mValueInSpecifiedUnits * M_PI) / 180.0);
-    break;
-  case SVG_ANGLETYPE_RAD:
-    *aValue = mValueInSpecifiedUnits;
-    break;
-  case SVG_ANGLETYPE_GRAD:
-    *aValue = float((mValueInSpecifiedUnits * M_PI) / 100.0);
-    break;
-  default:
-    rv = NS_ERROR_FAILURE;
-    break;
+  if (!unitStr || *unitStr == '\0') 
+    return nsIDOMSVGAngle::SVG_ANGLETYPE_UNSPECIFIED;
+                   
+  nsCOMPtr<nsIAtom> unitAtom = do_GetAtom(unitStr);
+
+  for (int i = 0 ; i < NS_ARRAY_LENGTH(unitMap) ; i++) {
+    if (unitMap[i] && *unitMap[i] == unitAtom) {
+      return i;
+    }
   }
-  return rv;
+
+  return nsIDOMSVGAngle::SVG_ANGLETYPE_UNKNOWN;
 }
 
-NS_IMETHODIMP
-nsSVGAngle::SetValue(float aValue)
-{
-  nsresult rv;
-  
-  switch (mSpecifiedUnitType) {
-  case SVG_ANGLETYPE_UNSPECIFIED:
-  case SVG_ANGLETYPE_DEG:
-    rv = SetValueInSpecifiedUnits(float((aValue * 180.0) / M_PI));
-    break;
-  case SVG_ANGLETYPE_RAD:
-    rv = SetValueInSpecifiedUnits(aValue);
-    break;
-  case SVG_ANGLETYPE_GRAD:
-    rv = SetValueInSpecifiedUnits(float((aValue * 100.0) / M_PI));
-    break;
-  default:
-    rv = NS_ERROR_FAILURE;
-    break;
-  }
-
-  return rv;
-}
-
-/* attribute float valueInSpecifiedUnits; */
-NS_IMETHODIMP
-nsSVGAngle::GetValueInSpecifiedUnits(float *aValueInSpecifiedUnits)
-{
-  *aValueInSpecifiedUnits = mValueInSpecifiedUnits;
-  return NS_OK;
-}
-
-NS_IMETHODIMP
-nsSVGAngle::SetValueInSpecifiedUnits(float aValueInSpecifiedUnits)
-{
-  WillModify();
-  mValueInSpecifiedUnits = aValueInSpecifiedUnits;
-  DidModify();
-  return NS_OK;
-}
-
-/* attribute DOMString valueAsString; */
-NS_IMETHODIMP
-nsSVGAngle::GetValueAsString(nsAString & aValueAsString)
+static void
+GetValueString(nsAString &aValueAsString, float aValue, PRUint16 aUnitType)
 {
   PRUnichar buf[24];
   nsTextFormatter::snprintf(buf, sizeof(buf)/sizeof(PRUnichar),
                             NS_LITERAL_STRING("%g").get(),
-                            (double)mValueInSpecifiedUnits);
+                            (double)aValue);
   aValueAsString.Assign(buf);
-  
+
   nsAutoString unitString;
-  GetUnitString(unitString);
+  GetUnitString(unitString, aUnitType);
   aValueAsString.Append(unitString);
-  
-  return NS_OK;
 }
 
-NS_IMETHODIMP
-nsSVGAngle::SetValueAsString(const nsAString & aValueAsString)
+static nsresult
+GetValueFromString(const nsAString &aValueAsString,
+                   float *aValue,
+                   PRUint16 *aUnitType)
 {
-  nsresult rv = NS_OK;
-  
   char *str = ToNewCString(aValueAsString);
-
-  char* number = str;
-  while (*number && isspace(*number))
-    ++number;
+  if (!str)
+    return NS_ERROR_OUT_OF_MEMORY;
 
-  if (*number) {
+  nsresult rv = NS_ERROR_FAILURE;
+  
+  if (*str) {
     char *rest;
-    double value = PR_strtod(number, &rest);
-    if (rest!=number) {
-      PRUint16 unitType = GetUnitTypeForString(nsCRT::strtok(rest, "\x20\x9\xD\xA", &rest));
-      rv = NewValueSpecifiedUnits(unitType, (float)value);
-    }
-    else { // parse error
-      // no number
-      rv = NS_ERROR_FAILURE;
+    *aValue = static_cast<float>(PR_strtod(str, &rest));
+    if (rest != str) {
+      *aUnitType = GetUnitTypeForString(nsCRT::strtok(rest,
+                                        "\x20\x9\xD\xA",
+                                        &rest));
+      if (IsValidUnitType(*aUnitType)) {
+        rv = NS_OK;
+      }
     }
   }
   
   nsMemory::Free(str);
     
   return rv;
 }
 
-/* void newValueSpecifiedUnits (in unsigned short unitType, in float valueInSpecifiedUnits); */
-NS_IMETHODIMP
-nsSVGAngle::NewValueSpecifiedUnits(PRUint16 unitType, float valueInSpecifiedUnits)
+float
+nsSVGAngle::GetUnitScaleFactor() const
 {
-  if (!IsValidUnitType(unitType)) return NS_ERROR_FAILURE;
+  switch (mSpecifiedUnitType) {
+  case nsIDOMSVGAngle::SVG_ANGLETYPE_UNSPECIFIED:
+  case nsIDOMSVGAngle::SVG_ANGLETYPE_DEG:
+    return static_cast<float>(180.0 / M_PI);
+  case nsIDOMSVGAngle::SVG_ANGLETYPE_RAD:
+    return 1;
+  case nsIDOMSVGAngle::SVG_ANGLETYPE_GRAD:
+    return static_cast<float>(100.0 / M_PI);
+  default:
+    NS_NOTREACHED("Unknown unit type");
+    return 0;
+  }
+}
 
-  WillModify();
-  mValueInSpecifiedUnits = valueInSpecifiedUnits;
-  mSpecifiedUnitType     = unitType;
-  DidModify();
-  
-  return NS_OK;
+void
+nsSVGAngle::SetBaseValueInSpecifiedUnits(float aValue,
+                                         nsSVGElement *aSVGElement)
+{
+  mBaseVal = aValue;
+  aSVGElement->DidChangeAngle(mAttrEnum, PR_TRUE);
 }
 
-/* void convertToSpecifiedUnits (in unsigned short unitType); */
-NS_IMETHODIMP
-nsSVGAngle::ConvertToSpecifiedUnits(PRUint16 unitType)
+void
+nsSVGAngle::ConvertToSpecifiedUnits(PRUint16 unitType,
+                                    nsSVGElement *aSVGElement)
 {
-  if (!IsValidUnitType(unitType)) return NS_ERROR_FAILURE;
+  if (!IsValidUnitType(unitType))
+    return;
+
+  float valueInUserUnits = mBaseVal / GetUnitScaleFactor();
+  mSpecifiedUnitType = PRUint8(unitType);
+  SetBaseValue(valueInUserUnits, aSVGElement);
+}
 
-  float valueInUserUnits;
-  GetValue(&valueInUserUnits);
-  mSpecifiedUnitType = unitType;
-  SetValue(valueInUserUnits);
-  
+void
+nsSVGAngle::NewValueSpecifiedUnits(PRUint16 unitType,
+                                   float valueInSpecifiedUnits,
+                                   nsSVGElement *aSVGElement)
+{
+  if (!IsValidUnitType(unitType))
+    return;
+
+  mBaseVal = mAnimVal = valueInSpecifiedUnits;
+  mSpecifiedUnitType = PRUint8(unitType);
+  if (aSVGElement) {
+    aSVGElement->DidChangeAngle(mAttrEnum, PR_TRUE);
+  }
+}
+
+nsresult
+nsSVGAngle::ToDOMBaseVal(nsIDOMSVGAngle **aResult, nsSVGElement *aSVGElement)
+{
+  *aResult = new DOMBaseVal(this, aSVGElement);
+  if (!*aResult)
+    return NS_ERROR_OUT_OF_MEMORY;
+
+  NS_ADDREF(*aResult);
   return NS_OK;
 }
 
-
-//----------------------------------------------------------------------
-// Implementation helpers:
+nsresult
+nsSVGAngle::ToDOMAnimVal(nsIDOMSVGAngle **aResult, nsSVGElement *aSVGElement)
+{
+  *aResult = new DOMAnimVal(this, aSVGElement);
+  if (!*aResult)
+    return NS_ERROR_OUT_OF_MEMORY;
 
+  NS_ADDREF(*aResult);
+  return NS_OK;
+}
 
-void nsSVGAngle::GetUnitString(nsAString& unit)
+/* Implementation */
+
+nsresult
+nsSVGAngle::SetBaseValueString(const nsAString &aValueAsString,
+                               nsSVGElement *aSVGElement,
+                               PRBool aDoSetAttr)
 {
-  nsIAtom* UnitAtom = nsnull;
+  float value;
+  PRUint16 unitType;
   
-  switch (mSpecifiedUnitType) {
-  case SVG_ANGLETYPE_UNSPECIFIED:
-    UnitAtom = nsnull;
-    break;
-  case SVG_ANGLETYPE_DEG:
-    UnitAtom = nsGkAtoms::deg;
-    break;
-  case SVG_ANGLETYPE_GRAD:
-    UnitAtom = nsGkAtoms::grad;
-    break;
-  case SVG_ANGLETYPE_RAD:
-    UnitAtom = nsGkAtoms::rad;
-    break;
-  default:
-    NS_ASSERTION(PR_FALSE, "unknown unit");
-    break;
+  nsresult rv = GetValueFromString(aValueAsString, &value, &unitType);
+  NS_ENSURE_SUCCESS(rv, rv);
+
+  mBaseVal = mAnimVal = value;
+  mSpecifiedUnitType = PRUint8(unitType);
+  if (aSVGElement) {
+    aSVGElement->DidChangeAngle(mAttrEnum, aDoSetAttr);
   }
-  if (!UnitAtom) return;
 
-  UnitAtom->ToString(unit);
+  return NS_OK;
 }
 
-PRUint16 nsSVGAngle::GetUnitTypeForString(const char* unitStr)
+void
+nsSVGAngle::GetBaseValueString(nsAString & aValueAsString)
 {
-  if (!unitStr || *unitStr=='\0') return SVG_ANGLETYPE_UNSPECIFIED;
-                   
-  nsCOMPtr<nsIAtom> unitAtom = do_GetAtom(unitStr);
+  GetValueString(aValueAsString, mBaseVal, mSpecifiedUnitType);
+}
 
-  if (unitAtom == nsGkAtoms::deg)
-    return SVG_ANGLETYPE_DEG;
-  else if (unitAtom == nsGkAtoms::grad)
-    return SVG_ANGLETYPE_GRAD;
-  else if (unitAtom == nsGkAtoms::rad)
-    return SVG_ANGLETYPE_RAD;
+void
+nsSVGAngle::GetAnimValueString(nsAString & aValueAsString)
+{
+  GetValueString(aValueAsString, mAnimVal, mSpecifiedUnitType);
+}
 
-  return SVG_ANGLETYPE_UNKNOWN;
+void
+nsSVGAngle::SetBaseValue(float aValue, nsSVGElement *aSVGElement)
+{
+  mAnimVal = mBaseVal = aValue * GetUnitScaleFactor();
+  if (aSVGElement) {
+    aSVGElement->DidChangeAngle(mAttrEnum, PR_TRUE);
+  }
 }
 
-PRBool nsSVGAngle::IsValidUnitType(PRUint16 unit)
+nsresult
+nsSVGAngle::ToDOMAnimatedAngle(nsIDOMSVGAnimatedAngle **aResult,
+                               nsSVGElement *aSVGElement)
 {
-  if (unit > SVG_ANGLETYPE_UNKNOWN && unit <= SVG_ANGLETYPE_GRAD)
-    return PR_TRUE;
+  *aResult = new DOMAnimatedAngle(this, aSVGElement);
+  if (!*aResult)
+    return NS_ERROR_OUT_OF_MEMORY;
+
+  NS_ADDREF(*aResult);
+  return NS_OK;
+}
 
-  return PR_FALSE;
+nsresult
+NS_NewDOMSVGAngle(nsIDOMSVGAngle** aResult)
+{
+  *aResult = new DOMSVGAngle;
+  if (!*aResult)
+    return NS_ERROR_OUT_OF_MEMORY;
+
+  NS_ADDREF(*aResult);
+  return NS_OK;
 }
--- a/content/svg/content/src/nsSVGAngle.h
+++ b/content/svg/content/src/nsSVGAngle.h
@@ -33,20 +33,158 @@
  * the terms of any one of the MPL, the GPL or the LGPL.
  *
  * ***** END LICENSE BLOCK ***** */
 
 #ifndef __NS_SVGANGLE_H__
 #define __NS_SVGANGLE_H__
 
 #include "nsIDOMSVGAngle.h"
-#include "nsAString.h"
+#include "nsIDOMSVGAnimatedAngle.h"
+#include "nsSVGElement.h"
+#include "nsDOMError.h"
+
+class nsSVGAngle
+{
+  friend class DOMSVGAngle;
+
+public:
+  void Init(PRUint8 aAttrEnum = 0xff,
+            float aValue = 0,
+            PRUint8 aUnitType = nsIDOMSVGAngle::SVG_ANGLETYPE_UNSPECIFIED) {
+    mAnimVal = mBaseVal = aValue;
+    mSpecifiedUnitType = aUnitType;
+    mAttrEnum = aAttrEnum;
+  }
+
+  nsresult SetBaseValueString(const nsAString& aValue,
+                              nsSVGElement *aSVGElement,
+                              PRBool aDoSetAttr);
+  void GetBaseValueString(nsAString& aValue);
+  void GetAnimValueString(nsAString& aValue);
+
+  float GetBaseValue() const
+    { return mBaseVal / GetUnitScaleFactor(); }
+  float GetAnimValue() const
+    { return mAnimVal / GetUnitScaleFactor(); }
+
+  void SetBaseValue(float aValue, nsSVGElement *aSVGElement);
+
+  PRUint8 GetSpecifiedUnitType() const { return mSpecifiedUnitType; }
+  float GetAnimValInSpecifiedUnits() const { return mAnimVal; }
+  float GetBaseValInSpecifiedUnits() const { return mBaseVal; }
+
+  static nsresult ToDOMSVGAngle(nsIDOMSVGAngle **aResult);
+  nsresult ToDOMAnimatedAngle(nsIDOMSVGAnimatedAngle **aResult,
+                              nsSVGElement* aSVGElement);
+
+private:
+  
+  float mAnimVal;
+  float mBaseVal;
+  PRUint8 mSpecifiedUnitType;
+  PRUint8 mAttrEnum; // element specified tracking for attribute
+  
+  float GetUnitScaleFactor() const;
+  void SetBaseValueInSpecifiedUnits(float aValue, nsSVGElement *aSVGElement);
+  void NewValueSpecifiedUnits(PRUint16 aUnitType, float aValue,
+                              nsSVGElement *aSVGElement);
+  void ConvertToSpecifiedUnits(PRUint16 aUnitType, nsSVGElement *aSVGElement);
+  nsresult ToDOMBaseVal(nsIDOMSVGAngle **aResult, nsSVGElement* aSVGElement);
+  nsresult ToDOMAnimVal(nsIDOMSVGAngle **aResult, nsSVGElement* aSVGElement);
+
+  struct DOMBaseVal : public nsIDOMSVGAngle
+  {
+    NS_DECL_ISUPPORTS
+
+    DOMBaseVal(nsSVGAngle* aVal, nsSVGElement *aSVGElement)
+      : mVal(aVal), mSVGElement(aSVGElement) {}
+    
+    nsSVGAngle* mVal; // kept alive because it belongs to mSVGElement
+    nsRefPtr<nsSVGElement> mSVGElement;
+    
+    NS_IMETHOD GetUnitType(PRUint16* aResult)
+      { *aResult = mVal->mSpecifiedUnitType; return NS_OK; }
+
+    NS_IMETHOD GetValue(float* aResult)
+      { *aResult = mVal->GetBaseValue(); return NS_OK; }
+    NS_IMETHOD SetValue(float aValue)
+      { mVal->SetBaseValue(aValue, mSVGElement); return NS_OK; }
+
+    NS_IMETHOD GetValueInSpecifiedUnits(float* aResult)
+      { *aResult = mVal->mBaseVal; return NS_OK; }
+    NS_IMETHOD SetValueInSpecifiedUnits(float aValue)
+      { mVal->SetBaseValueInSpecifiedUnits(aValue, mSVGElement);
+        return NS_OK; }
+
+    NS_IMETHOD SetValueAsString(const nsAString& aValue)
+      { return mVal->SetBaseValueString(aValue, mSVGElement, PR_TRUE); }
+    NS_IMETHOD GetValueAsString(nsAString& aValue)
+      { mVal->GetBaseValueString(aValue); return NS_OK; }
+
+    NS_IMETHOD NewValueSpecifiedUnits(PRUint16 unitType,
+                                      float valueInSpecifiedUnits)
+      { mVal->NewValueSpecifiedUnits(unitType, valueInSpecifiedUnits,
+                                     mSVGElement); 
+        return NS_OK; }
+
+    NS_IMETHOD ConvertToSpecifiedUnits(PRUint16 unitType)
+      { mVal->ConvertToSpecifiedUnits(unitType, mSVGElement); return NS_OK; }
+  };
+
+  struct DOMAnimVal : public nsIDOMSVGAngle
+  {
+    NS_DECL_ISUPPORTS
+
+    DOMAnimVal(nsSVGAngle* aVal, nsSVGElement *aSVGElement)
+      : mVal(aVal), mSVGElement(aSVGElement) {}
+    
+    nsSVGAngle* mVal; // kept alive because it belongs to mSVGElement
+    nsRefPtr<nsSVGElement> mSVGElement;
+    
+    NS_IMETHOD GetUnitType(PRUint16* aResult)
+      { *aResult = mVal->mSpecifiedUnitType; return NS_OK; }
+
+    NS_IMETHOD GetValue(float* aResult)
+      { *aResult = mVal->GetAnimValue(); return NS_OK; }
+    NS_IMETHOD SetValue(float aValue)
+      { return NS_ERROR_DOM_NO_MODIFICATION_ALLOWED_ERR; }
+
+    NS_IMETHOD GetValueInSpecifiedUnits(float* aResult)
+      { *aResult = mVal->mAnimVal; return NS_OK; }
+    NS_IMETHOD SetValueInSpecifiedUnits(float aValue)
+      { return NS_ERROR_DOM_NO_MODIFICATION_ALLOWED_ERR; }
+
+    NS_IMETHOD SetValueAsString(const nsAString& aValue)
+      { return NS_ERROR_DOM_NO_MODIFICATION_ALLOWED_ERR; }
+    NS_IMETHOD GetValueAsString(nsAString& aValue)
+      { mVal->GetAnimValueString(aValue); return NS_OK; }
+
+    NS_IMETHOD NewValueSpecifiedUnits(PRUint16 unitType,
+                                      float valueInSpecifiedUnits)
+      { return NS_ERROR_DOM_NO_MODIFICATION_ALLOWED_ERR; }
+
+    NS_IMETHOD ConvertToSpecifiedUnits(PRUint16 unitType)
+      { return NS_ERROR_DOM_NO_MODIFICATION_ALLOWED_ERR; }
+  };
+
+  struct DOMAnimatedAngle : public nsIDOMSVGAnimatedAngle
+  {
+    NS_DECL_ISUPPORTS
+
+    DOMAnimatedAngle(nsSVGAngle* aVal, nsSVGElement *aSVGElement)
+      : mVal(aVal), mSVGElement(aSVGElement) {}
+    
+    nsSVGAngle* mVal; // kept alive because it belongs to content
+    nsRefPtr<nsSVGElement> mSVGElement;
+
+    NS_IMETHOD GetBaseVal(nsIDOMSVGAngle **aBaseVal)
+      { return mVal->ToDOMBaseVal(aBaseVal, mSVGElement); }
+
+    NS_IMETHOD GetAnimVal(nsIDOMSVGAngle **aAnimVal)
+      { return mVal->ToDOMAnimVal(aAnimVal, mSVGElement); }
+  };
+};
 
 nsresult
-NS_NewSVGAngle(nsIDOMSVGAngle** result,
-               float value=0.0f,
-               PRUint16 unit=nsIDOMSVGAngle::SVG_ANGLETYPE_UNSPECIFIED);
-
-nsresult
-NS_NewSVGAngle(nsIDOMSVGAngle** result,
-               const nsAString &value);
+NS_NewDOMSVGAngle(nsIDOMSVGAngle** result);
 
 #endif //__NS_SVGANGLE_H__
deleted file mode 100644
--- a/content/svg/content/src/nsSVGAnimatedAngle.cpp
+++ /dev/null
@@ -1,201 +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 the Mozilla SVG project.
- *
- * The Initial Developer of the Original Code is IBM Corporation.
- * Portions created by the Initial Developer are Copyright (C) 2004
- * 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 ***** */
-
-#include "nsSVGValue.h"
-#include "nsWeakReference.h"
-#include "nsSVGAnimatedAngle.h"
-#include "nsSVGLength.h"
-#include "nsContentUtils.h"
-
-
-////////////////////////////////////////////////////////////////////////
-// nsSVGAnimatedAngle
-
-class nsSVGAnimatedAngle : public nsIDOMSVGAnimatedAngle,
-                           public nsSVGValue,
-                           public nsISVGValueObserver
-{
-protected:
-  friend nsresult NS_NewSVGAnimatedAngle(nsIDOMSVGAnimatedAngle** result,
-                                         nsIDOMSVGAngle* baseVal);
-  nsSVGAnimatedAngle();
-  ~nsSVGAnimatedAngle();
-  void Init(nsIDOMSVGAngle* baseVal);
-  
-public:
-  // nsISupports interface:
-  NS_DECL_ISUPPORTS
-
-  // nsIDOMSVGAnimatedAngle interface:
-  NS_DECL_NSIDOMSVGANIMATEDANGLE
-
-  // remainder of nsISVGValue interface:
-  NS_IMETHOD SetValueString(const nsAString& aValue);
-  NS_IMETHOD GetValueString(nsAString& aValue);
-
-  // nsISVGValueObserver
-  NS_IMETHOD WillModifySVGObservable(nsISVGValue* observable,
-                                     modificationType aModType);
-  NS_IMETHOD DidModifySVGObservable (nsISVGValue* observable,
-                                     modificationType aModType);
-  
-  // nsISupportsWeakReference
-  // implementation inherited from nsSupportsWeakReference
-  
-protected:
-  nsCOMPtr<nsIDOMSVGAngle> mBaseVal;
-};
-
-
-
-//----------------------------------------------------------------------
-// Implementation
-
-nsSVGAnimatedAngle::nsSVGAnimatedAngle()
-{
-}
-
-nsSVGAnimatedAngle::~nsSVGAnimatedAngle()
-{
-  if (!mBaseVal) return;
-  nsCOMPtr<nsISVGValue> val = do_QueryInterface(mBaseVal);
-  if (!val) return;
-  val->RemoveObserver(this);
-}
-
-void
-nsSVGAnimatedAngle::Init(nsIDOMSVGAngle* baseVal)
-{
-  mBaseVal = baseVal;
-  if (!mBaseVal) return;
-  nsCOMPtr<nsISVGValue> val = do_QueryInterface(mBaseVal);
-  NS_ASSERTION(val, "baseval needs to implement nsISVGValue interface");
-  if (!val) return;
-  val->AddObserver(this);
-}
-
-//----------------------------------------------------------------------
-// nsISupports methods:
-
-NS_IMPL_ADDREF(nsSVGAnimatedAngle)
-NS_IMPL_RELEASE(nsSVGAnimatedAngle)
-
-
-NS_INTERFACE_MAP_BEGIN(nsSVGAnimatedAngle)
-  NS_INTERFACE_MAP_ENTRY(nsISVGValue)
-  NS_INTERFACE_MAP_ENTRY(nsIDOMSVGAnimatedAngle)
-  NS_INTERFACE_MAP_ENTRY(nsISupportsWeakReference)
-  NS_INTERFACE_MAP_ENTRY(nsISVGValueObserver)
-  NS_INTERFACE_MAP_ENTRY_CONTENT_CLASSINFO(SVGAnimatedAngle)
-  NS_INTERFACE_MAP_ENTRY_AMBIGUOUS(nsISupports, nsISVGValue)
-NS_INTERFACE_MAP_END
-  
-//----------------------------------------------------------------------
-// nsISVGValue methods:
-
-NS_IMETHODIMP
-nsSVGAnimatedAngle::SetValueString(const nsAString& aValue)
-{
-  nsCOMPtr<nsISVGValue> value = do_QueryInterface(mBaseVal);
-  return value->SetValueString(aValue);
-}
-
-NS_IMETHODIMP
-nsSVGAnimatedAngle::GetValueString(nsAString& aValue)
-{
-  nsCOMPtr<nsISVGValue> value = do_QueryInterface(mBaseVal);
-  return value->GetValueString(aValue);
-}
-
-//----------------------------------------------------------------------
-// nsIDOMSVGAnimatedAngle methods:
-
-/* readonly attribute nsIDOMSVGAngle baseVal; */
-NS_IMETHODIMP
-nsSVGAnimatedAngle::GetBaseVal(nsIDOMSVGAngle * *aBaseVal)
-{
-  *aBaseVal = mBaseVal;
-  NS_ADDREF(*aBaseVal);
-  return NS_OK;
-}
-
-/* readonly attribute nsIDOMSVGAngle animVal; */
-NS_IMETHODIMP
-nsSVGAnimatedAngle::GetAnimVal(nsIDOMSVGAngle * *aAnimVal)
-{
-  *aAnimVal = mBaseVal;
-  NS_ADDREF(*aAnimVal);
-  return NS_OK;
-}
-
-//----------------------------------------------------------------------
-// nsISVGValueObserver methods
-
-NS_IMETHODIMP
-nsSVGAnimatedAngle::WillModifySVGObservable(nsISVGValue* observable,
-                                            modificationType aModType)
-{
-  WillModify(aModType);
-  return NS_OK;
-}
-
-NS_IMETHODIMP
-nsSVGAnimatedAngle::DidModifySVGObservable (nsISVGValue* observable,
-                                            modificationType aModType)
-{
-  DidModify(aModType);
-  return NS_OK;
-}
-
-////////////////////////////////////////////////////////////////////////
-// Exported creation functions
-
-nsresult
-NS_NewSVGAnimatedAngle(nsIDOMSVGAnimatedAngle** aResult,
-                       nsIDOMSVGAngle* baseVal)
-{
-  *aResult = nsnull;
-  
-  nsSVGAnimatedAngle* animatedLength = new nsSVGAnimatedAngle();
-  if(!animatedLength) return NS_ERROR_OUT_OF_MEMORY;
-  NS_ADDREF(animatedLength);
-
-  animatedLength->Init(baseVal);
-  
-  *aResult = (nsIDOMSVGAnimatedAngle*) animatedLength;
-  
-  return NS_OK;
-}
deleted file mode 100644
--- a/content/svg/content/src/nsSVGAnimatedAngle.h
+++ /dev/null
@@ -1,46 +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 the Mozilla SVG project.
- *
- * The Initial Developer of the Original Code is IBM Corporation.
- * Portions created by the Initial Developer are Copyright (C) 2004
- * 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 __NS_SVGANIMATEDANGLE_H__
-#define __NS_SVGANIMATEDANGLE_H__
-
-#include "nsIDOMSVGAnimatedAngle.h"
-#include "nsIDOMSVGAngle.h"
-
-nsresult NS_NewSVGAnimatedAngle(nsIDOMSVGAnimatedAngle** result,
-                                nsIDOMSVGAngle* baseVal);
-
-#endif //__NS_SVGANIMATEDANGLE_H__
--- a/content/svg/content/src/nsSVGElement.cpp
+++ b/content/svg/content/src/nsSVGElement.cpp
@@ -63,24 +63,20 @@
 #include "nsGenericHTMLElement.h"
 #include "nsNodeInfoManager.h"
 #include "nsIScriptGlobalObject.h"
 #include "nsIEventListenerManager.h"
 #include "nsSVGUtils.h"
 #include "nsSVGLength2.h"
 #include "nsSVGNumber2.h"
 #include "nsSVGInteger.h"
+#include "nsSVGAngle.h"
 #include "nsSVGBoolean.h"
 #include "nsSVGEnum.h"
 #include "nsIDOMSVGUnitTypes.h"
-#include "nsIDOMSVGAngle.h"
-#include "nsIDOMSVGAnimatedAngle.h"
-#include "nsIDOMSVGAnimatedBoolean.h"
-#include "nsIDOMSVGAnimatedInteger.h"
-#include "nsIDOMSVGLength.h"
 #include "nsIDOMSVGLengthList.h"
 #include "nsIDOMSVGAnimatedLengthList.h"
 #include "nsIDOMSVGNumberList.h"
 #include "nsIDOMSVGAnimatedNumberList.h"
 #include "nsIDOMSVGPointList.h"
 #include "nsIDOMSVGAnimatedPoints.h"
 #include "nsIDOMSVGPresAspectRatio.h"
 #include "nsIDOMSVGAnimPresAspRatio.h"
@@ -126,16 +122,24 @@ nsSVGElement::Init()
   }
 
   IntegerAttributesInfo integerInfo = GetIntegerInfo();
 
   for (i = 0; i < integerInfo.mIntegerCount; i++) {
     integerInfo.mIntegers[i].Init(i, integerInfo.mIntegerInfo[i].mDefaultValue);
   }
 
+  AngleAttributesInfo angleInfo = GetAngleInfo();
+
+  for (i = 0; i < angleInfo.mAngleCount; i++) {
+    angleInfo.mAngles[i].Init(i,
+                              angleInfo.mAngleInfo[i].mDefaultValue,
+                              angleInfo.mAngleInfo[i].mDefaultUnitType);
+  }
+
   BooleanAttributesInfo booleanInfo = GetBooleanInfo();
 
   for (i = 0; i < booleanInfo.mBooleanCount; i++) {
     booleanInfo.mBooleans[i].Init(i, booleanInfo.mBooleanInfo[i].mDefaultValue);
   }
 
   EnumAttributesInfo enumInfo = GetEnumInfo();
 
@@ -254,53 +258,64 @@ nsSVGElement::ParseAttribute(PRInt32 aNa
   }
 
   if (aNamespaceID == kNameSpaceID_None) {
     nsresult rv;
     PRBool foundMatch = PR_FALSE;
 
     // Check for nsSVGLength2 attribute
     LengthAttributesInfo lengthInfo = GetLengthInfo();
-    for (PRUint32 i = 0; i < lengthInfo.mLengthCount && !foundMatch; i++) {
+
+    PRUint32 i;
+    for (i = 0; i < lengthInfo.mLengthCount && !foundMatch; i++) {
       if (aAttribute == *lengthInfo.mLengthInfo[i].mName) {
         rv = lengthInfo.mLengths[i].SetBaseValueString(aValue, this, PR_FALSE);
         foundMatch = PR_TRUE;
       }
     }
 
     // Check for nsSVGNumber2 attribute
     NumberAttributesInfo numberInfo = GetNumberInfo();
-    for (PRUint32 i = 0; i < numberInfo.mNumberCount && !foundMatch; i++) {
+    for (i = 0; i < numberInfo.mNumberCount && !foundMatch; i++) {
       if (aAttribute == *numberInfo.mNumberInfo[i].mName) {
         rv = numberInfo.mNumbers[i].SetBaseValueString(aValue, this, PR_FALSE);
         foundMatch = PR_TRUE;
       }
     }
 
     // Check for nsSVGInteger attribute
     IntegerAttributesInfo integerInfo = GetIntegerInfo();
-    for (PRUint32 i = 0; i < integerInfo.mIntegerCount && !foundMatch; i++) {
+    for (i = 0; i < integerInfo.mIntegerCount && !foundMatch; i++) {
       if (aAttribute == *integerInfo.mIntegerInfo[i].mName) {
         rv = integerInfo.mIntegers[i].SetBaseValueString(aValue, this, PR_FALSE);
         foundMatch = PR_TRUE;
       }
     }
 
+    // Check for nsSVGAngle attribute
+    AngleAttributesInfo angleInfo = GetAngleInfo();
+    for (i = 0; i < angleInfo.mAngleCount && !foundMatch; i++) {
+      if (aAttribute == *angleInfo.mAngleInfo[i].mName) {
+        rv = angleInfo.mAngles[i].SetBaseValueString(aValue, this, PR_FALSE);
+        foundMatch = PR_TRUE;
+      }
+    }
+
     // Check for nsSVGBoolean attribute
     BooleanAttributesInfo booleanInfo = GetBooleanInfo();
-    for (PRUint32 i = 0; i < booleanInfo.mBooleanCount && !foundMatch; i++) {
+    for (i = 0; i < booleanInfo.mBooleanCount && !foundMatch; i++) {
       if (aAttribute == *booleanInfo.mBooleanInfo[i].mName) {
         rv = booleanInfo.mBooleans[i].SetBaseValueString(aValue, this, PR_FALSE);
         foundMatch = PR_TRUE;
       }
     }
 
     // Check for nsSVGEnum attribute
     EnumAttributesInfo enumInfo = GetEnumInfo();
-    for (PRUint32 i = 0; i < enumInfo.mEnumCount && !foundMatch; i++) {
+    for (i = 0; i < enumInfo.mEnumCount && !foundMatch; i++) {
       if (aAttribute == *enumInfo.mEnumInfo[i].mName) {
         rv = enumInfo.mEnums[i].SetBaseValueString(aValue, this, PR_FALSE);
         foundMatch = PR_TRUE;
       }
     }
 
     if (foundMatch) {
       if (NS_FAILED(rv)) {
@@ -361,16 +376,28 @@ nsSVGElement::UnsetAttr(PRInt32 aNamespa
 
       for (i = 0; i < intInfo.mIntegerCount; i++) {
         if (aName == *intInfo.mIntegerInfo[i].mName) {
           intInfo.mIntegers[i].Init(i, intInfo.mIntegerInfo[i].mDefaultValue);
           DidChangeInteger(i, PR_FALSE);
         }
       }
 
+      // Check if this is an angle attribute going away
+      AngleAttributesInfo angleInfo = GetAngleInfo();
+
+      for (i = 0; i < angleInfo.mAngleCount; i++) {
+        if (aName == *angleInfo.mAngleInfo[i].mName) {
+          angleInfo.mAngles[i].Init(i, 
+                                    angleInfo.mAngleInfo[i].mDefaultValue,
+                                    angleInfo.mAngleInfo[i].mDefaultUnitType);
+          DidChangeAngle(i, PR_FALSE);
+        }
+      }
+
       // Check if this is a boolean attribute going away
       BooleanAttributesInfo boolInfo = GetBooleanInfo();
 
       for (i = 0; i < boolInfo.mBooleanCount; i++) {
         if (aName == *boolInfo.mBooleanInfo[i].mName) {
           boolInfo.mBooleans[i].Init(i, boolInfo.mBooleanInfo[i].mDefaultValue);
           DidChangeBoolean(i, PR_FALSE);
         }
@@ -385,21 +412,16 @@ nsSVGElement::UnsetAttr(PRInt32 aNamespa
           DidChangeEnum(i, PR_FALSE);
         }
       }
 
       // Now check for one of the old style basetypes going away
       nsCOMPtr<nsISVGValue> svg_value = GetMappedAttribute(aNamespaceID, aName);
 
       if (svg_value) {
-#ifdef DEBUG_tor
-        nsCOMPtr<nsIDOMSVGAnimatedAngle> a = do_QueryInterface(svg_value);
-        NS_ASSERTION(!a, "must provide element processing for unset angle");
-#endif
-
         nsCOMPtr<nsIDOMSVGAnimatedRect> r = do_QueryInterface(svg_value);
         if (r) {
           nsCOMPtr<nsIDOMSVGRect> rect;
           r->GetBaseVal(getter_AddRefs(rect));
           static_cast<nsSVGRect*>(rect.get())->Clear();
         }
         nsCOMPtr<nsIDOMSVGAnimatedPreserveAspectRatio> ar = do_QueryInterface(svg_value);
         if (ar) {
@@ -1058,32 +1080,58 @@ nsSVGElement::GetAnimatedIntegerValues(P
 
   while (n && i < info.mIntegerCount) {
     *n = info.mIntegers[i++].GetAnimValue();
     n = va_arg(args, PRInt32*);
   }
   va_end(args);
 }
 
+nsSVGElement::AngleAttributesInfo
+nsSVGElement::GetAngleInfo()
+{
+  return AngleAttributesInfo(nsnull, nsnull, 0);
+}
+
+void
+nsSVGElement::DidChangeAngle(PRUint8 aAttrEnum, PRBool aDoSetAttr)
+{
+  if (!aDoSetAttr)
+    return;
+
+  AngleAttributesInfo info = GetAngleInfo();
+
+  NS_ASSERTION(info.mAngleCount > 0,
+               "DidChangeAngle on element with no angle attribs");
+
+  NS_ASSERTION(aAttrEnum < info.mAngleCount, "aAttrEnum out of range");
+
+  nsAutoString newStr;
+  info.mAngles[aAttrEnum].GetBaseValueString(newStr);
+
+  SetAttr(kNameSpaceID_None, *info.mAngleInfo[aAttrEnum].mName,
+          newStr, PR_TRUE);
+}
+
 nsSVGElement::BooleanAttributesInfo
 nsSVGElement::GetBooleanInfo()
 {
   return BooleanAttributesInfo(nsnull, nsnull, 0);
 }
 
 void
 nsSVGElement::DidChangeBoolean(PRUint8 aAttrEnum, PRBool aDoSetAttr)
 {
   if (!aDoSetAttr)
     return;
 
   BooleanAttributesInfo info = GetBooleanInfo();
 
   NS_ASSERTION(info.mBooleanCount > 0,
-               "DidChangeInteger on element with no boolean attribs");
+               "DidChangeBoolean on element with no boolean attribs");
 
   NS_ASSERTION(aAttrEnum < info.mBooleanCount, "aAttrEnum out of range");
 
   nsAutoString newStr;
   info.mBooleans[aAttrEnum].GetBaseValueString(newStr);
 
   SetAttr(kNameSpaceID_None, *info.mBooleanInfo[aAttrEnum].mName,
           newStr, PR_TRUE);
--- a/content/svg/content/src/nsSVGElement.h
+++ b/content/svg/content/src/nsSVGElement.h
@@ -53,16 +53,17 @@
 #include "nsISVGValueObserver.h"
 #include "nsWeakReference.h"
 #include "nsICSSStyleRule.h"
 
 class nsSVGSVGElement;
 class nsSVGLength2;
 class nsSVGNumber2;
 class nsSVGInteger;
+class nsSVGAngle;
 class nsSVGBoolean;
 class nsSVGEnum;
 struct nsSVGEnumMapping;
 
 typedef nsStyledElement nsSVGElementBase;
 
 class nsSVGElement : public nsSVGElementBase,    // nsIContent
                      public nsISVGValueObserver  // :nsISupportsWeakReference
@@ -116,16 +117,17 @@ public:
   // nsISupportsWeakReference
   // implementation inherited from nsSupportsWeakReference
 
   nsSVGSVGElement* GetCtx();
 
   virtual void DidChangeLength(PRUint8 aAttrEnum, PRBool aDoSetAttr);
   virtual void DidChangeNumber(PRUint8 aAttrEnum, PRBool aDoSetAttr);
   virtual void DidChangeInteger(PRUint8 aAttrEnum, PRBool aDoSetAttr);
+  virtual void DidChangeAngle(PRUint8 aAttrEnum, PRBool aDoSetAttr);
   virtual void DidChangeBoolean(PRUint8 aAttrEnum, PRBool aDoSetAttr);
   virtual void DidChangeEnum(PRUint8 aAttrEnum, PRBool aDoSetAttr);
 
   void GetAnimatedLengthValues(float *aFirst, ...);
   void GetAnimatedNumberValues(float *aFirst, ...);
   void GetAnimatedIntegerValues(PRInt32 *aFirst, ...);
 
   virtual void RecompileScriptEventListeners();
@@ -146,17 +148,17 @@ protected:
   nsresult AddMappedSVGValue(nsIAtom* aName, nsISupports* aValue,
                              PRInt32 aNamespaceID = kNameSpaceID_None);
   
   static nsIAtom* GetEventNameForAttr(nsIAtom* aAttr);
 
   struct LengthInfo {
     nsIAtom** mName;
     float     mDefaultValue;
-    PRUint16  mDefaultUnitType;
+    PRUint8   mDefaultUnitType;
     PRUint8   mCtxType;
   };
 
   struct LengthAttributesInfo {
     nsSVGLength2* mLengths;
     LengthInfo*   mLengthInfo;
     PRUint32      mLengthCount;
 
@@ -196,16 +198,34 @@ protected:
 
     IntegerAttributesInfo(nsSVGInteger *aIntegers,
                           IntegerInfo *aIntegerInfo,
                           PRUint32 aIntegerCount) :
       mIntegers(aIntegers), mIntegerInfo(aIntegerInfo), mIntegerCount(aIntegerCount)
       {}
   };
 
+  struct AngleInfo {
+    nsIAtom** mName;
+    float     mDefaultValue;
+    PRUint8   mDefaultUnitType;
+  };
+
+  struct AngleAttributesInfo {
+    nsSVGAngle* mAngles;
+    AngleInfo*  mAngleInfo;
+    PRUint32    mAngleCount;
+
+    AngleAttributesInfo(nsSVGAngle *aAngles,
+                        AngleInfo *aAngleInfo,
+                        PRUint32 aAngleCount) :
+      mAngles(aAngles), mAngleInfo(aAngleInfo), mAngleCount(aAngleCount)
+      {}
+  };
+
   struct BooleanInfo {
     nsIAtom**    mName;
     PRPackedBool mDefaultValue;
   };
 
   struct BooleanAttributesInfo {
     nsSVGBoolean* mBooleans;
     BooleanInfo*  mBooleanInfo;
@@ -236,25 +256,26 @@ protected:
                        PRUint32 aEnumCount) :
       mEnums(aEnums), mEnumInfo(aEnumInfo), mEnumCount(aEnumCount)
       {}
   };
 
   virtual LengthAttributesInfo GetLengthInfo();
   virtual NumberAttributesInfo GetNumberInfo();
   virtual IntegerAttributesInfo GetIntegerInfo();
+  virtual AngleAttributesInfo GetAngleInfo();
   virtual BooleanAttributesInfo GetBooleanInfo();
   virtual EnumAttributesInfo GetEnumInfo();
 
+  static nsSVGEnumMapping sSVGUnitTypesMap[];
+
   static nsresult ReportAttributeParseFailure(nsIDocument* aDocument,
                                               nsIAtom* aAttribute,
                                               const nsAString& aValue);
 
-  static nsSVGEnumMapping sSVGUnitTypesMap[];
-
   nsCOMPtr<nsICSSStyleRule> mContentStyleRule;
   nsAttrAndChildArray mMappedAttributes;
 
   PRPackedBool mSuppressNotification;
 };
 
 /**
  * A macro to implement the NS_NewSVGXXXElement() functions.
--- a/content/svg/content/src/nsSVGEnum.cpp
+++ b/content/svg/content/src/nsSVGEnum.cpp
@@ -99,17 +99,17 @@ nsresult
 nsSVGEnum::SetBaseValue(PRUint16 aValue,
                         nsSVGElement *aSVGElement,
                         PRBool aDoSetAttr)
 {
   nsSVGEnumMapping *tmp = GetMapping(aSVGElement);
 
   while (tmp && tmp->mKey) {
     if (tmp->mVal == aValue) {
-      mAnimVal = mBaseVal = static_cast<PRUint8>(aValue);
+      mAnimVal = mBaseVal = PRUint8(aValue);
       aSVGElement->DidChangeEnum(mAttrEnum, aDoSetAttr);
       return NS_OK;
     }
     tmp++;
   }
   return NS_ERROR_FAILURE;
 }
 
--- a/content/svg/content/src/nsSVGEnum.h
+++ b/content/svg/content/src/nsSVGEnum.h
@@ -45,19 +45,21 @@ typedef PRUint8 nsSVGEnumValue;
 
 struct nsSVGEnumMapping {
   nsIAtom **mKey;
   nsSVGEnumValue mVal;
 };
 
 class nsSVGEnum
 {
+friend class nsSVGMarkerElement;
+
 public:
   void Init(PRUint8 aAttrEnum, PRUint16 aValue) {
-    mAnimVal = mBaseVal = static_cast<PRUint8>(aValue);
+    mAnimVal = mBaseVal = PRUint8(aValue);
     mAttrEnum = aAttrEnum;
   }
 
   nsresult SetBaseValueString(const nsAString& aValue,
                               nsSVGElement *aSVGElement,
                               PRBool aDoSetAttr);
   void GetBaseValueString(nsAString& aValue,
                           nsSVGElement *aSVGElement);
@@ -76,16 +78,20 @@ public:
 
 private:
   nsSVGEnumValue mAnimVal;
   nsSVGEnumValue mBaseVal;
   PRUint8 mAttrEnum; // element specified tracking for attribute
 
   nsSVGEnumMapping *GetMapping(nsSVGElement *aSVGElement);
 
+  nsresult SetBaseValue(PRUint16 aValue)
+  { mAnimVal = mBaseVal = PRUint8(aValue);
+    return NS_OK; }
+
   struct DOMAnimatedEnum : public nsIDOMSVGAnimatedEnumeration
   {
     NS_DECL_ISUPPORTS
 
     DOMAnimatedEnum(nsSVGEnum* aVal, nsSVGElement *aSVGElement)
       : mVal(aVal), mSVGElement(aSVGElement) {}
 
     nsSVGEnum *mVal; // kept alive because it belongs to content
--- a/content/svg/content/src/nsSVGFilters.cpp
+++ b/content/svg/content/src/nsSVGFilters.cpp
@@ -1073,17 +1073,17 @@ nsSVGFEBlendElement::Filter(nsSVGFilterI
     }
   }
   return NS_OK;
 }
 
 NS_IMETHODIMP
 nsSVGFEBlendElement::GetRequirements(PRUint32 *aRequirements)
 {
-  *aRequirements = CheckStandardNames(mIn1);
+  *aRequirements = CheckStandardNames(mIn1) | CheckStandardNames(mIn2);
   return NS_OK;
 }
 
 nsSVGElement::EnumAttributesInfo
 nsSVGFEBlendElement::GetEnumInfo()
 {
   return EnumAttributesInfo(mEnumAttributes, sEnumInfo,
                             NS_ARRAY_LENGTH(sEnumInfo));
@@ -1338,17 +1338,17 @@ nsSVGFEColorMatrixElement::Filter(nsSVGF
     colorMatrix[2] = 0.072f - 0.072f * s;
 
     colorMatrix[5] = 0.213f - 0.213f * s;
     colorMatrix[6] = 0.715f + 0.285f * s;
     colorMatrix[7] = 0.072f - 0.072f * s;
 
     colorMatrix[10] = 0.213f - 0.213f * s;
     colorMatrix[11] = 0.715f - 0.715f * s;
-    colorMatrix[12] = 0.715f - 0.715f * s;
+    colorMatrix[12] = 0.072f + 0.928f * s;
 
     break;
 
   case nsSVGFEColorMatrixElement::SVG_FECOLORMATRIX_TYPE_HUE_ROTATE:
 
     memcpy(colorMatrix, identityMatrix, sizeof(colorMatrix));
 
     if (num != 1)
@@ -1689,17 +1689,17 @@ nsSVGFECompositeElement::Filter(nsSVGFil
   ctx.SetSource(sourceSurface);
   ctx.Paint();
   return NS_OK;
 }
 
 NS_IMETHODIMP
 nsSVGFECompositeElement::GetRequirements(PRUint32 *aRequirements)
 {
-  *aRequirements = CheckStandardNames(mIn1);
+  *aRequirements = CheckStandardNames(mIn1) | CheckStandardNames(mIn2);
   return NS_OK;
 }
 
 nsSVGElement::EnumAttributesInfo
 nsSVGFECompositeElement::GetEnumInfo()
 {
   return EnumAttributesInfo(mEnumAttributes, sEnumInfo,
                             NS_ARRAY_LENGTH(sEnumInfo));
--- a/content/svg/content/src/nsSVGMarkerElement.cpp
+++ b/content/svg/content/src/nsSVGMarkerElement.cpp
@@ -30,20 +30,17 @@
  * 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 "nsGkAtoms.h"
-#include "nsSVGAnimatedAngle.h"
 #include "nsSVGAnimatedRect.h"
-#include "nsSVGLength.h"
-#include "nsSVGAngle.h"
 #include "nsSVGRect.h"
 #include "nsCOMPtr.h"
 #include "nsISVGValueUtils.h"
 #include "nsSVGAnimatedPreserveAspectRatio.h"
 #include "nsSVGPreserveAspectRatio.h"
 #include "nsSVGMatrix.h"
 #include "nsDOMError.h"
 #include "nsSVGUtils.h"
@@ -66,16 +63,21 @@ nsSVGEnumMapping nsSVGMarkerElement::sUn
 nsSVGElement::EnumInfo nsSVGMarkerElement::sEnumInfo[1] =
 {
   { &nsGkAtoms::markerUnits,
     sUnitsMap,
     nsIDOMSVGMarkerElement::SVG_MARKERUNITS_STROKEWIDTH
   }
 };
 
+nsSVGElement::AngleInfo nsSVGMarkerElement::sAngleInfo[1] =
+{
+  { &nsGkAtoms::orient, 0, nsIDOMSVGAngle::SVG_ANGLETYPE_UNSPECIFIED }
+};
+
 NS_IMPL_NS_NEW_SVG_ELEMENT(Marker)
 
 //----------------------------------------------------------------------
 // nsISupports methods
 
 NS_IMPL_ADDREF_INHERITED(nsSVGMarkerElement,nsSVGMarkerElementBase)
 NS_IMPL_RELEASE_INHERITED(nsSVGMarkerElement,nsSVGMarkerElementBase)
 
@@ -102,25 +104,16 @@ nsSVGMarkerElement::Init()
   nsresult rv = nsSVGMarkerElementBase::Init();
   NS_ENSURE_SUCCESS(rv,rv);
 
   // derived (non-attrib) DOM properties
 
   // DOM property: orientType
   mOrientType.Init(ORIENTTYPE, SVG_MARKER_ORIENT_ANGLE);
 
-  // DOM property: orientAngle
-  {
-    nsCOMPtr<nsIDOMSVGAngle> angle;
-    rv = NS_NewSVGAngle(getter_AddRefs(angle), 0.0f);
-    NS_ENSURE_SUCCESS(rv,rv);
-    rv = NS_NewSVGAnimatedAngle(getter_AddRefs(mOrientAngle), angle);
-    NS_ENSURE_SUCCESS(rv,rv);
-  }
-
   // Create mapped properties:
 
   // DOM property: viewBox
   {
     nsCOMPtr<nsIDOMSVGRect> viewbox;
     rv = NS_NewSVGRect(getter_AddRefs(viewbox));
     NS_ENSURE_SUCCESS(rv,rv);
     rv = NS_NewSVGAnimatedRect(getter_AddRefs(mViewBox), viewbox);
@@ -208,41 +201,36 @@ NS_IMETHODIMP nsSVGMarkerElement::GetMar
 NS_IMETHODIMP nsSVGMarkerElement::GetOrientType(nsIDOMSVGAnimatedEnumeration * *aOrientType)
 {
   return mOrientType.ToDOMAnimatedEnum(aOrientType, this);
 }
 
 /* readonly attribute nsIDOMSVGAnimatedLength orientAngle; */
 NS_IMETHODIMP nsSVGMarkerElement::GetOrientAngle(nsIDOMSVGAnimatedAngle * *aOrientAngle)
 {
-  *aOrientAngle = mOrientAngle;
-  NS_IF_ADDREF(*aOrientAngle);
-  return NS_OK;
+  return mAngleAttributes[ORIENT].ToDOMAnimatedAngle(aOrientAngle, this);
 }
 
 /* void setOrientToAuto (); */
 NS_IMETHODIMP nsSVGMarkerElement::SetOrientToAuto()
 {
-  mOrientType.SetBaseValue(SVG_MARKER_ORIENT_AUTO, this, PR_TRUE);
+  SetAttr(kNameSpaceID_None, nsGkAtoms::orient, nsnull,
+          NS_LITERAL_STRING("auto"), PR_TRUE);
   return NS_OK;
 }
 
 /* void setOrientToAngle (in nsIDOMSVGAngle angle); */
 NS_IMETHODIMP nsSVGMarkerElement::SetOrientToAngle(nsIDOMSVGAngle *angle)
 {
   if (!angle)
     return NS_ERROR_DOM_SVG_WRONG_TYPE_ERR;
 
-  nsIDOMSVGAngle *a;
-  mOrientAngle->GetBaseVal(&a);
   float f;
   angle->GetValue(&f);
-  a->SetValue(f);
-
-  mOrientType.SetBaseValue(SVG_MARKER_ORIENT_ANGLE, this, PR_TRUE);
+  mAngleAttributes[ORIENT].SetBaseValue(f, this);
 
   return NS_OK;
 }
 
 //----------------------------------------------------------------------
 // nsISVGValueObserver methods:
 
 NS_IMETHODIMP
@@ -276,45 +264,34 @@ nsSVGMarkerElement::IsAttributeMapped(co
 
 //----------------------------------------------------------------------
 // nsSVGElement methods
 
 PRBool
 nsSVGMarkerElement::GetAttr(PRInt32 aNameSpaceID, nsIAtom* aName,
                             nsAString &aResult) const
 {
-  if (aNameSpaceID == kNameSpaceID_None && aName == nsGkAtoms::orient) {
-    if (mOrientType.GetBaseValue() == SVG_MARKER_ORIENT_AUTO) {
-      aResult.AssignLiteral("auto");
-    } else {
-      nsCOMPtr<nsIDOMSVGAngle> a;
-      mOrientAngle->GetBaseVal(getter_AddRefs(a));
-      nsCOMPtr<nsISVGValue> value = do_QueryInterface(a);
-      value->GetValueString(aResult);
-    }
+  if (aNameSpaceID == kNameSpaceID_None &&
+      aName == nsGkAtoms::orient &&
+      mOrientType.GetBaseValue() == SVG_MARKER_ORIENT_AUTO) {
+    aResult.AssignLiteral("auto");
     return PR_TRUE;
   }
   return nsSVGMarkerElementBase::GetAttr(aNameSpaceID, aName, aResult);
 }
 
 nsresult
 nsSVGMarkerElement::SetAttr(PRInt32 aNameSpaceID, nsIAtom* aName,
                             nsIAtom* aPrefix, const nsAString& aValue,
                             PRBool aNotify)
 {
   if (aNameSpaceID == kNameSpaceID_None && aName == nsGkAtoms::orient) {
-    if (aValue.EqualsLiteral("auto")) {
-      mOrientType.SetBaseValue(SVG_MARKER_ORIENT_AUTO, this, PR_FALSE);
-    } else {
-      mOrientType.SetBaseValue(SVG_MARKER_ORIENT_ANGLE, this, PR_FALSE);
-      nsCOMPtr<nsIDOMSVGAngle> a;
-      mOrientAngle->GetBaseVal(getter_AddRefs(a));
-      nsCOMPtr<nsISVGValue> value = do_QueryInterface(a);
-      value->SetValueString(aValue);
-    }
+    mOrientType.SetBaseValue(aValue.EqualsLiteral("auto") ?
+                               SVG_MARKER_ORIENT_AUTO :
+                               SVG_MARKER_ORIENT_ANGLE);
   }
 
   return nsSVGMarkerElementBase::SetAttr(aNameSpaceID, aName,
                                          aPrefix, aValue, aNotify);
 }
 
 nsresult
 nsSVGMarkerElement::UnsetAttr(PRInt32 aNamespaceID, nsIAtom* aName,
@@ -323,25 +300,20 @@ nsSVGMarkerElement::UnsetAttr(PRInt32 aN
   if (aNamespaceID == kNameSpaceID_None) {
     if (aName == nsGkAtoms::viewBox && mCoordCtx) {
       nsCOMPtr<nsIDOMSVGRect> vb;
       mViewBox->GetAnimVal(getter_AddRefs(vb));
       vb->SetX(0);
       vb->SetY(0);
       vb->SetWidth(mLengthAttributes[MARKERWIDTH].GetAnimValue(mCoordCtx));
       vb->SetHeight(mLengthAttributes[MARKERHEIGHT].GetAnimValue(mCoordCtx));
+      return nsGenericElement::UnsetAttr(aNamespaceID, aName, aNotify);
     } else if (aName == nsGkAtoms::orient) {
-      mOrientType.SetBaseValue(SVG_MARKER_ORIENT_ANGLE, this, PR_FALSE);
-      nsIDOMSVGAngle *angle;
-      mOrientAngle->GetBaseVal(&angle);
-      angle->NewValueSpecifiedUnits(nsIDOMSVGAngle::SVG_ANGLETYPE_UNSPECIFIED,
-                                    0.0f);
+      mOrientType.SetBaseValue(SVG_MARKER_ORIENT_ANGLE);
     }
-
-    return nsGenericElement::UnsetAttr(aNamespaceID, aName, aNotify);
   }
 
   return nsSVGMarkerElementBase::UnsetAttr(aNamespaceID, aName, aNotify);
 }
 
 //----------------------------------------------------------------------
 // nsSVGElement methods
 
@@ -356,41 +328,16 @@ nsSVGMarkerElement::DidChangeLength(PRUi
       (aAttrEnum == MARKERWIDTH || aAttrEnum == MARKERHEIGHT)) {
     nsCOMPtr<nsIDOMSVGRect> vb;
     mViewBox->GetAnimVal(getter_AddRefs(vb));
     vb->SetWidth(mLengthAttributes[MARKERWIDTH].GetAnimValue(mCoordCtx));
     vb->SetHeight(mLengthAttributes[MARKERHEIGHT].GetAnimValue(mCoordCtx));
   }
 }
 
-void
-nsSVGMarkerElement::DidChangeEnum(PRUint8 aAttrEnum, PRBool aDoSetAttr)
-{
-  if (!aDoSetAttr)
-    return;
-
-  if (aAttrEnum == ORIENTTYPE) {
-    if (mOrientType.GetBaseValue() == SVG_MARKER_ORIENT_AUTO) {
-      nsSVGMarkerElementBase::SetAttr(kNameSpaceID_None, nsGkAtoms::orient,
-                                      NS_LITERAL_STRING("auto"), PR_TRUE);
-    } else {
-      nsAutoString value;
-      GetAttr(kNameSpaceID_None, nsGkAtoms::orient, value);
-      if (value.EqualsLiteral("auto")) {
-        // type is being set to non-auto - remove an "auto" valued
-        // attribute if it's set, otherwise leave the angle specified.
-        UnsetAttr(kNameSpaceID_None, nsGkAtoms::orient, PR_TRUE);
-      }
-    }
-    return;
-  }
-
-  nsSVGMarkerElementBase::DidChangeEnum(aAttrEnum, aDoSetAttr);
-}
-
 void 
 nsSVGMarkerElement::SetParentCoordCtxProvider(nsSVGSVGElement *aContext)
 {
   mCoordCtx = aContext;
   mViewBoxToViewportTransform = nsnull;
 
   if (mCoordCtx && !HasAttr(kNameSpaceID_None, nsGkAtoms::viewBox)) {
     nsCOMPtr<nsIDOMSVGRect> vb;
@@ -402,16 +349,23 @@ nsSVGMarkerElement::SetParentCoordCtxPro
 
 nsSVGElement::LengthAttributesInfo
 nsSVGMarkerElement::GetLengthInfo()
 {
   return LengthAttributesInfo(mLengthAttributes, sLengthInfo,
                               NS_ARRAY_LENGTH(sLengthInfo));
 }
 
+nsSVGElement::AngleAttributesInfo
+nsSVGMarkerElement::GetAngleInfo()
+{
+  return AngleAttributesInfo(mAngleAttributes, sAngleInfo,
+                             NS_ARRAY_LENGTH(sAngleInfo));
+}
+
 nsSVGElement::EnumAttributesInfo
 nsSVGMarkerElement::GetEnumInfo()
 {
   return EnumAttributesInfo(mEnumAttributes, sEnumInfo,
                             NS_ARRAY_LENGTH(sEnumInfo));
 }
 
 //----------------------------------------------------------------------
@@ -422,20 +376,18 @@ nsSVGMarkerElement::GetMarkerTransform(f
                                        float aX, float aY, float aAngle,
                                        nsIDOMSVGMatrix **_retval)
 {
   float scale = 1.0;
   if (mEnumAttributes[MARKERUNITS].GetAnimValue() ==
       SVG_MARKERUNITS_STROKEWIDTH)
     scale = aStrokeWidth;
 
-  if (mOrientType.GetBaseValue() != SVG_MARKER_ORIENT_AUTO) {
-    nsCOMPtr<nsIDOMSVGAngle> a;
-    mOrientAngle->GetAnimVal(getter_AddRefs(a));
-    a->GetValue(&aAngle);
+  if (mOrientType.GetAnimValue() != SVG_MARKER_ORIENT_AUTO) {
+    aAngle = mAngleAttributes[ORIENT].GetAnimValue();
   }
 
   nsCOMPtr<nsIDOMSVGMatrix> matrix;
   NS_NewSVGMatrix(getter_AddRefs(matrix),
                   cos(aAngle) * scale,   sin(aAngle) * scale,
                   -sin(aAngle) * scale,  cos(aAngle) * scale,
                   aX,                    aY);
     
--- a/content/svg/content/src/nsSVGMarkerElement.h
+++ b/content/svg/content/src/nsSVGMarkerElement.h
@@ -37,16 +37,17 @@
 #ifndef __NS_SVGMARKERELEMENT_H__
 #define __NS_SVGMARKERELEMENT_H__
 
 #include "nsSVGGraphicElement.h"
 #include "nsIDOMSVGMarkerElement.h"
 #include "nsIDOMSVGFitToViewBox.h"
 #include "nsSVGLength2.h"
 #include "nsSVGEnum.h"
+#include "nsSVGAngle.h"
 
 typedef nsSVGGraphicElement nsSVGMarkerElementBase;
 
 class nsSVGMarkerElement : public nsSVGMarkerElementBase,
                            public nsIDOMSVGMarkerElement,
                            public nsIDOMSVGFitToViewBox
 {
   friend class nsSVGMarkerFrame;
@@ -81,45 +82,48 @@ public:
   virtual nsresult SetAttr(PRInt32 aNameSpaceID, nsIAtom* aName,
                            nsIAtom* aPrefix, const nsAString& aValue,
                            PRBool aNotify);
   virtual nsresult UnsetAttr(PRInt32 aNameSpaceID, nsIAtom* aAttribute,
                              PRBool aNotify);
 
   // nsSVGElement specializations:
   virtual void DidChangeLength(PRUint8 aAttrEnum, PRBool aDoSetAttr);
-  virtual void DidChangeEnum(PRUint8 aAttrEnum, PRBool aDoSetAttr);
 
   // public helpers
   nsresult GetMarkerTransform(float aStrokeWidth,
                               float aX, float aY, float aAngle,
                               nsIDOMSVGMatrix **_retval);
   nsresult GetViewboxToViewportTransform(nsIDOMSVGMatrix **_retval);
 
   virtual nsresult Clone(nsINodeInfo *aNodeInfo, nsINode **aResult) const;
 
 protected:
 
   void SetParentCoordCtxProvider(nsSVGSVGElement *aContext);
 
   virtual LengthAttributesInfo GetLengthInfo();
+  virtual AngleAttributesInfo GetAngleInfo();
   virtual EnumAttributesInfo GetEnumInfo();
 
   enum { REFX, REFY, MARKERWIDTH, MARKERHEIGHT };
   nsSVGLength2 mLengthAttributes[4];
   static LengthInfo sLengthInfo[4];
 
   enum { MARKERUNITS, ORIENTTYPE = 0xFF };
   nsSVGEnum mEnumAttributes[1];
   static nsSVGEnumMapping sUnitsMap[];
   static EnumInfo sEnumInfo[1];
 
+  enum { ORIENT };
+  nsSVGAngle mAngleAttributes[1];
+  static AngleInfo sAngleInfo[1];
+
   // derived properties (from 'orient') handled separately
   nsSVGEnum                              mOrientType;
-  nsCOMPtr<nsIDOMSVGAnimatedAngle>       mOrientAngle;
 
   nsSVGSVGElement                       *mCoordCtx;
   nsCOMPtr<nsIDOMSVGAnimatedRect>        mViewBox;
   nsCOMPtr<nsIDOMSVGAnimatedPreserveAspectRatio> mPreserveAspectRatio;
   nsCOMPtr<nsIDOMSVGMatrix>         mViewBoxToViewportTransform;
 };
 
 #endif
--- a/content/svg/content/src/nsSVGSVGElement.cpp
+++ b/content/svg/content/src/nsSVGSVGElement.cpp
@@ -562,17 +562,17 @@ nsSVGSVGElement::CreateSVGLength(nsIDOMS
 {
   return NS_NewSVGLength(reinterpret_cast<nsISVGLength**>(_retval));
 }
 
 /* nsIDOMSVGAngle createSVGAngle (); */
 NS_IMETHODIMP
 nsSVGSVGElement::CreateSVGAngle(nsIDOMSVGAngle **_retval)
 {
-  return NS_NewSVGAngle(_retval);
+  return NS_NewDOMSVGAngle(_retval);
 }
 
 /* nsIDOMSVGPoint createSVGPoint (); */
 NS_IMETHODIMP
 nsSVGSVGElement::CreateSVGPoint(nsIDOMSVGPoint **_retval)
 {
   return NS_NewSVGPoint(_retval);
 }
--- a/content/svg/content/src/nsSVGValue.cpp
+++ b/content/svg/content/src/nsSVGValue.cpp
@@ -103,18 +103,20 @@ nsSVGValue::AddObserver(nsISVGValueObser
   nsIWeakReference* wr = NS_GetWeakReference(observer);
   if (!wr) return NS_ERROR_FAILURE;
 
   // Prevent duplicate observers - needed because geometry can attempt
   // to add itself as an observer of a paint server for both the
   // stroke and fill.  Safe, as on a style change we remove both, as
   // the change notification isn't fine grained, and re-add as
   // appropriate.
-  if (mObservers.IndexOf((void*)wr) >= 0)
+  if (mObservers.IndexOf((void*)wr) >= 0) {
+    NS_RELEASE(wr);
     return NS_OK;
+  }
 
   mObservers.AppendElement((void*)wr);
   return NS_OK;
 }
 
 NS_IMETHODIMP
 nsSVGValue::RemoveObserver(nsISVGValueObserver* observer)
 {
--- a/content/xbl/src/nsBindingManager.cpp
+++ b/content/xbl/src/nsBindingManager.cpp
@@ -82,36 +82,43 @@
 #include "nsBindingManager.h"
 
 #include "nsThreadUtils.h"
 
 // ==================================================================
 // = nsAnonymousContentList 
 // ==================================================================
 
+#define NS_ANONYMOUS_CONTENT_LIST_IID \
+  { 0xa29df1f8, 0xaeca, 0x4356, \
+    { 0xa8, 0xc2, 0xa7, 0x24, 0xa2, 0x11, 0x73, 0xac } }
+
 class nsAnonymousContentList : public nsIDOMNodeList
 {
 public:
   nsAnonymousContentList(nsInsertionPointList* aElements);
   virtual ~nsAnonymousContentList();
 
   NS_DECL_CYCLE_COLLECTING_ISUPPORTS
   NS_DECL_CYCLE_COLLECTION_CLASS(nsAnonymousContentList)
   // nsIDOMNodeList interface
   NS_DECL_NSIDOMNODELIST
 
   PRInt32 GetInsertionPointCount() { return mElements->Length(); }
 
   nsXBLInsertionPoint* GetInsertionPointAt(PRInt32 i) { return static_cast<nsXBLInsertionPoint*>(mElements->ElementAt(i)); }
   void RemoveInsertionPointAt(PRInt32 i) { mElements->RemoveElementAt(i); }
-
+  NS_DECLARE_STATIC_IID_ACCESSOR(NS_ANONYMOUS_CONTENT_LIST_IID)
 private:
   nsInsertionPointList* mElements;
 };
 
+NS_DEFINE_STATIC_IID_ACCESSOR(nsAnonymousContentList,
+                              NS_ANONYMOUS_CONTENT_LIST_IID)
+
 nsAnonymousContentList::nsAnonymousContentList(nsInsertionPointList* aElements)
   : mElements(aElements)
 {
   MOZ_COUNT_CTOR(nsAnonymousContentList);
 
   // We don't reference count our Anonymous reference (to avoid circular
   // references). We'll be told when the Anonymous goes away.
 }
@@ -124,16 +131,17 @@ nsAnonymousContentList::~nsAnonymousCont
 
 NS_IMPL_CYCLE_COLLECTION_CLASS(nsAnonymousContentList)
 
 NS_IMPL_CYCLE_COLLECTING_ADDREF(nsAnonymousContentList)
 NS_IMPL_CYCLE_COLLECTING_RELEASE(nsAnonymousContentList)
 
 NS_INTERFACE_MAP_BEGIN(nsAnonymousContentList)
   NS_INTERFACE_MAP_ENTRY(nsIDOMNodeList)
+  NS_INTERFACE_MAP_ENTRY(nsAnonymousContentList)
   NS_INTERFACE_MAP_ENTRY(nsISupports)
   NS_INTERFACE_MAP_ENTRY_CONTENT_CLASSINFO(NodeList)
   NS_INTERFACE_MAP_ENTRIES_CYCLE_COLLECTION(nsAnonymousContentList)
 NS_INTERFACE_MAP_END
 
 NS_IMPL_CYCLE_COLLECTION_UNLINK_0(nsAnonymousContentList)
 NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN(nsAnonymousContentList)
   {
@@ -294,18 +302,27 @@ SetOrRemoveObject(PLDHashTable& table, n
       table.ops = nsnull;
       return NS_ERROR_OUT_OF_MEMORY;
     }
     aKey->SetFlags(NODE_MAY_BE_IN_BINDING_MNGR);
     return AddObjectEntry(table, aKey, aValue);
   }
 
   // no value, so remove the key from the table
-  if (table.ops)
-    RemoveObjectEntry(table, aKey);
+  if (table.ops) {
+    ObjectEntry* entry =
+      static_cast<ObjectEntry*>
+        (PL_DHashTableOperate(&table, aKey, PL_DHASH_LOOKUP));
+    if (entry && PL_DHASH_ENTRY_IS_BUSY(entry)) {
+      // Keep key and value alive while removing the entry.
+      nsCOMPtr<nsISupports> key = entry->GetKey();
+      nsCOMPtr<nsISupports> value = entry->GetValue();
+      RemoveObjectEntry(table, aKey);
+    }
+  }
   return NS_OK;
 }
 
 // Implementation /////////////////////////////////////////////////////////////////
 
 // Static member variable initialization
 
 // Implement our nsISupports methods
@@ -397,22 +414,70 @@ nsBindingManager::nsBindingManager(nsIDo
 }
 
 nsBindingManager::~nsBindingManager(void)
 {
   if (mContentListTable.ops)
     PL_DHashTableFinish(&mContentListTable);
   if (mAnonymousNodesTable.ops)
     PL_DHashTableFinish(&mAnonymousNodesTable);
+  NS_ASSERTION(!mInsertionParentTable.ops || !mInsertionParentTable.entryCount,
+               "Insertion parent table isn't empty!");
   if (mInsertionParentTable.ops)
     PL_DHashTableFinish(&mInsertionParentTable);
   if (mWrapperTable.ops)
     PL_DHashTableFinish(&mWrapperTable);
 }
 
+PLDHashOperator
+PR_CALLBACK RemoveInsertionParentCB(PLDHashTable* aTable, PLDHashEntryHdr* aEntry,
+                                  PRUint32 aNumber, void* aArg)
+{
+  return (static_cast<ObjectEntry*>(aEntry)->GetValue() ==
+          static_cast<nsISupports*>(aArg)) ? PL_DHASH_REMOVE : PL_DHASH_NEXT;
+}
+
+static void
+RemoveInsertionParentForNodeList(nsIDOMNodeList* aList, nsIContent* aParent)
+{
+  nsCOMPtr<nsAnonymousContentList> list = do_QueryInterface(aList);
+  if (list) {
+    PRInt32 count = list->GetInsertionPointCount();
+    for (PRInt32 i = 0; i < count; ++i) {
+      nsRefPtr<nsXBLInsertionPoint> currPoint = list->GetInsertionPointAt(i);
+      nsCOMPtr<nsIContent> defContent = currPoint->GetDefaultContent();
+      if (defContent) {
+        defContent->UnbindFromTree();
+      }
+#ifdef DEBUG
+      nsCOMPtr<nsIContent> parent = currPoint->GetInsertionParent();
+      NS_ASSERTION(!parent || parent == aParent, "Wrong insertion parent!");
+#endif
+      currPoint->ClearInsertionParent();
+    }
+  }
+}
+
+void
+nsBindingManager::RemoveInsertionParent(nsIContent* aParent)
+{
+  nsCOMPtr<nsIDOMNodeList> contentlist;
+  GetContentListFor(aParent, getter_AddRefs(contentlist));
+  RemoveInsertionParentForNodeList(contentlist, aParent);
+
+  nsCOMPtr<nsIDOMNodeList> anonnodes;
+  GetAnonymousNodesFor(aParent, getter_AddRefs(anonnodes));
+  RemoveInsertionParentForNodeList(anonnodes, aParent);
+
+  if (mInsertionParentTable.ops) {
+    PL_DHashTableEnumerate(&mInsertionParentTable, RemoveInsertionParentCB,
+                           static_cast<nsISupports*>(aParent));
+  }
+}
+
 nsXBLBinding*
 nsBindingManager::GetBinding(nsIContent* aContent)
 {
   if (aContent && aContent->HasFlag(NODE_MAY_BE_IN_BINDING_MNGR) &&
       mBindingTable.IsInitialized()) {
     return mBindingTable.GetWeak(aContent);
   }
 
@@ -428,18 +493,28 @@ nsBindingManager::SetBinding(nsIContent*
   }
 
   // After this point, aBinding will be the most-derived binding for aContent.
   // If we already have a binding for aContent in our table, make sure to
   // remove it from the attached stack.  Otherwise we might end up firing its
   // constructor twice (if aBinding inherits from it) or firing its constructor
   // after aContent has been deleted (if aBinding is null and the content node
   // dies before we process mAttachedStack).
-  nsXBLBinding* oldBinding = mBindingTable.GetWeak(aContent);
+  nsRefPtr<nsXBLBinding> oldBinding = GetBinding(aContent);
   if (oldBinding) {
+    if (aContent->HasFlag(NODE_IS_INSERTION_PARENT)) {
+      nsRefPtr<nsXBLBinding> parentBinding =
+        GetBinding(aContent->GetBindingParent());
+      // Clear insertion parent only if we don't have a parent binding which
+      // marked content to be an insertion parent. See also ChangeDocumentFor().
+      if (!parentBinding || !parentBinding->HasInsertionParent(aContent)) {
+        RemoveInsertionParent(aContent);
+        aContent->UnsetFlags(NODE_IS_INSERTION_PARENT);
+      }
+    }
     mAttachedStack.RemoveElement(oldBinding);
   }
   
   PRBool result = PR_TRUE;
 
   if (aBinding) {
     aContent->SetFlags(NODE_MAY_BE_IN_BINDING_MNGR);
     result = mBindingTable.Put(aContent, aBinding);
@@ -466,16 +541,18 @@ nsBindingManager::GetInsertionParent(nsI
   }
 
   return nsnull;
 }
 
 nsresult
 nsBindingManager::SetInsertionParent(nsIContent* aContent, nsIContent* aParent)
 {
+  NS_ASSERTION(!aParent || aParent->HasFlag(NODE_IS_INSERTION_PARENT),
+               "Insertion parent should have NODE_IS_INSERTION_PARENT flag!");
   return SetOrRemoveObject(mInsertionParentTable, aContent, aParent);
 }
 
 nsIXPConnectWrappedJS*
 nsBindingManager::GetWrappedJS(nsIContent* aContent)
 { 
   if (mWrapperTable.ops) {
     return static_cast<nsIXPConnectWrappedJS*>(LookupObject(mWrapperTable, aContent));
@@ -500,16 +577,29 @@ nsBindingManager::ChangeDocumentFor(nsIC
   NS_PRECONDITION(!aNewDocument,
                   "Changing to a non-null new document not supported yet");
   if (! aOldDocument)
     return NS_ERROR_NULL_POINTER;
 
   // Hold a ref to the binding so it won't die when we remove it from our
   // table.
   nsRefPtr<nsXBLBinding> binding = GetBinding(aContent);
+  if (aContent->HasFlag(NODE_IS_INSERTION_PARENT)) {
+    nsRefPtr<nsXBLBinding> parentBinding = GetBinding(aContent->GetBindingParent());
+    if (parentBinding) {
+      parentBinding->RemoveInsertionParent(aContent);
+      // Clear insertion parent only if we don't have a binding which
+      // marked content to be an insertion parent. See also SetBinding().
+      if (!binding || !binding->HasInsertionParent(aContent)) {
+        RemoveInsertionParent(aContent);
+        aContent->UnsetFlags(NODE_IS_INSERTION_PARENT);
+      }
+    }
+  }
+
   if (binding) {
     binding->ChangeDocument(aOldDocument, aNewDocument);
     SetBinding(aContent, nsnull);
     if (aNewDocument)
       aNewDocument->BindingManager()->SetBinding(aContent, binding);
   }
 
   // Clear out insertion parents and content lists.
--- a/content/xbl/src/nsBindingManager.h
+++ b/content/xbl/src/nsBindingManager.h
@@ -230,16 +230,17 @@ protected:
                                      func_, params_);
 
   // Same as ProcessAttachedQueue, but also nulls out
   // mProcessAttachedQueueEvent
   void DoProcessAttachedQueue();
 
 // MEMBER VARIABLES
 protected: 
+  void RemoveInsertionParent(nsIContent* aParent);
   // A mapping from nsIContent* to the nsXBLBinding* that is
   // installed on that element.
   nsRefPtrHashtable<nsISupportsHashKey,nsXBLBinding> mBindingTable;
 
   // A mapping from nsIContent* to an nsIDOMNodeList*
   // (nsAnonymousContentList*).  This list contains an accurate
   // reflection of our *explicit* children (once intermingled with
   // insertion points) in the altered DOM.
--- a/content/xbl/src/nsXBLBinding.cpp
+++ b/content/xbl/src/nsXBLBinding.cpp
@@ -437,16 +437,20 @@ BuildContentLists(nsISupports* aKey,
   if (!contentList) {
     data->mRv = NS_ERROR_OUT_OF_MEMORY;
     return PL_DHASH_STOP;
   }
 
   // Figure out the relevant content node.
   nsXBLInsertionPoint* currPoint = aData->ElementAt(0);
   nsCOMPtr<nsIContent> parent = currPoint->GetInsertionParent();
+  if (!parent) {
+    data->mRv = NS_ERROR_FAILURE;
+    return PL_DHASH_STOP;
+  }
   PRInt32 currIndex = currPoint->GetInsertionIndex();
 
   nsCOMPtr<nsIDOMNodeList> nodeList;
   if (parent == boundElement) {
     // We are altering anonymous nodes to accommodate insertion points.
     nodeList = binding->GetAnonymousNodes();
   }
   else {
@@ -521,16 +525,20 @@ RealizeDefaultContent(nsISupports* aKey,
     
     if (insCount == 0) {
       nsCOMPtr<nsIContent> defContent = currPoint->GetDefaultContentTemplate();
       if (defContent) {
         // We need to take this template and use it to realize the
         // actual default content (through cloning).
         // Clone this insertion point element.
         nsCOMPtr<nsIContent> insParent = currPoint->GetInsertionParent();
+        if (!insParent) {
+          data->mRv = NS_ERROR_FAILURE;
+          return PL_DHASH_STOP;
+        }
         nsIDocument *document = insParent->GetOwnerDoc();
         if (!document) {
           data->mRv = NS_ERROR_FAILURE;
           return PL_DHASH_STOP;
         }
 
         nsCOMPtr<nsIDOMNode> clonedNode;
         nsCOMArray<nsINode> nodesWithProperties;
@@ -1321,16 +1329,57 @@ nsXBLBinding::AllowScripts()
   nsCOMPtr<nsIDocument> ourDocument;
   mPrototypeBinding->XBLDocumentInfo()->GetDocument(getter_AddRefs(ourDocument));
   PRBool canExecute;
   nsresult rv =
     mgr->CanExecuteScripts(cx, ourDocument->NodePrincipal(), &canExecute);
   return NS_SUCCEEDED(rv) && canExecute;
 }
 
+void
+nsXBLBinding::RemoveInsertionParent(nsIContent* aParent)
+{
+  if (mNextBinding) {
+    mNextBinding->RemoveInsertionParent(aParent);
+  }
+  if (mInsertionPointTable) {
+    nsInsertionPointList* list = nsnull;
+    mInsertionPointTable->Get(aParent, &list);
+    if (list) {
+      PRInt32 count = list->Length();
+      for (PRInt32 i = 0; i < count; ++i) {
+        nsRefPtr<nsXBLInsertionPoint> currPoint = list->ElementAt(i);
+        nsCOMPtr<nsIContent> defContent = currPoint->GetDefaultContent();
+        if (defContent) {
+          defContent->UnbindFromTree();
+        }
+#ifdef DEBUG
+        nsCOMPtr<nsIContent> parent = currPoint->GetInsertionParent();
+        NS_ASSERTION(!parent || parent == aParent, "Wrong insertion parent!");
+#endif
+        currPoint->ClearInsertionParent();
+      }
+      mInsertionPointTable->Remove(aParent);
+    }
+  }
+}
+
+PRBool
+nsXBLBinding::HasInsertionParent(nsIContent* aParent)
+{
+  if (mInsertionPointTable) {
+    nsInsertionPointList* list = nsnull;
+    mInsertionPointTable->Get(aParent, &list);
+    if (list) {
+      return PR_TRUE;
+    }
+  }
+  return mNextBinding ? mNextBinding->HasInsertionParent(aParent) : PR_FALSE;
+}
+
 nsresult
 nsXBLBinding::GetInsertionPointsFor(nsIContent* aParent,
                                     nsInsertionPointList** aResult)
 {
   if (!mInsertionPointTable) {
     mInsertionPointTable =
       new nsClassHashtable<nsISupportsHashKey, nsInsertionPointList>;
     if (!mInsertionPointTable || !mInsertionPointTable->Init(4)) {
@@ -1344,16 +1393,19 @@ nsXBLBinding::GetInsertionPointsFor(nsIC
 
   if (!*aResult) {
     *aResult = new nsInsertionPointList;
     if (!*aResult || !mInsertionPointTable->Put(aParent, *aResult)) {
       delete *aResult;
       *aResult = nsnull;
       return NS_ERROR_OUT_OF_MEMORY;
     }
+    if (aParent) {
+      aParent->SetFlags(NODE_IS_INSERTION_PARENT);
+    }
   }
 
   return NS_OK;
 }
 
 nsInsertionPointList*
 nsXBLBinding::GetExistingInsertionPointsFor(nsIContent* aParent)
 {
--- a/content/xbl/src/nsXBLBinding.h
+++ b/content/xbl/src/nsXBLBinding.h
@@ -159,16 +159,19 @@ public:
 
   static nsresult DoInitJSClass(JSContext *cx, JSObject *global, JSObject *obj,
                                 const nsAFlatCString& aClassName,
                                 nsXBLPrototypeBinding* aProtoBinding,
                                 void **aClassObject);
 
   PRBool AllowScripts();  // XXX make const
 
+  void RemoveInsertionParent(nsIContent* aParent);
+  PRBool HasInsertionParent(nsIContent* aParent);
+
 // MEMBER VARIABLES
 protected:
   nsAutoRefCnt mRefCnt;
   nsXBLPrototypeBinding* mPrototypeBinding; // Weak, but we're holding a ref to the docinfo
   nsCOMPtr<nsIContent> mContent; // Strong. Our anonymous content stays around with us.
   nsRefPtr<nsXBLBinding> mNextBinding; // Strong. The derived binding owns the base class bindings.
   
   nsIContent* mBoundElement; // [WEAK] We have a reference, but we don't own it.
--- a/content/xbl/src/nsXBLInsertionPoint.h
+++ b/content/xbl/src/nsXBLInsertionPoint.h
@@ -58,16 +58,18 @@ public:
     return mRefCnt;
   }
 
   nsrefcnt Release();
 
   NS_DECL_CYCLE_COLLECTION_NATIVE_CLASS(nsXBLInsertionPoint)
 
   already_AddRefed<nsIContent> GetInsertionParent();
+  void ClearInsertionParent() { mParentElement = nsnull; }
+
   PRInt32 GetInsertionIndex() { return mIndex; }
 
   void SetDefaultContent(nsIContent* aDefaultContent) { mDefaultContent = aDefaultContent; }
   already_AddRefed<nsIContent> GetDefaultContent();
 
   void SetDefaultContentTemplate(nsIContent* aDefaultContent) { mDefaultContentTemplate = aDefaultContent; }
   already_AddRefed<nsIContent> GetDefaultContentTemplate();
 
--- a/content/xbl/src/nsXBLPrototypeBinding.h
+++ b/content/xbl/src/nsXBLPrototypeBinding.h
@@ -50,17 +50,16 @@
 #include "nsHashtable.h"
 #include "nsIXBLDocumentInfo.h"
 #include "nsCOMArray.h"
 #include "nsXBLProtoImpl.h"
 
 class nsIAtom;
 class nsIDocument;
 class nsIScriptContext;
-class nsISupportsArray;
 class nsSupportsHashtable;
 class nsIXBLService;
 class nsFixedSizeAllocator;
 class nsXBLProtoImplField;
 class nsXBLBinding;
 
 // *********************************************************************/
 // The XBLPrototypeBinding class
--- a/content/xbl/src/nsXBLPrototypeResources.h
+++ b/content/xbl/src/nsXBLPrototypeResources.h
@@ -36,17 +36,16 @@
  *
  * ***** END LICENSE BLOCK ***** */
 
 #ifndef nsXBLPrototypeResources_h__
 #define nsXBLPrototypeResources_h__
 
 #include "nsCOMPtr.h"
 #include "nsICSSLoaderObserver.h"
-#include "nsISupportsArray.h"
 #include "nsIStyleRuleProcessor.h"
 #include "nsCOMArray.h"
 
 class nsIContent;
 class nsIAtom;
 class nsIDocument;
 class nsIScriptContext;
 class nsSupportsHashtable;
--- a/content/xbl/test/Makefile.in
+++ b/content/xbl/test/Makefile.in
@@ -46,13 +46,14 @@ relativesrcdir  = content/xbl/test
 include $(DEPTH)/config/autoconf.mk
 include $(topsrcdir)/config/rules.mk
 
 _TEST_FILES =	\
 		test_bug296375.xul \
 		test_bug366770.html \
 		test_bug371724.xhtml \
 		test_bug372769.xhtml \
+		test_bug378866.xhtml \
 		test_bug397934.xhtml \
 		$(NULL)
 
 libs:: $(_TEST_FILES)
 	$(INSTALL) $(foreach f,$^,"$f") $(DEPTH)/_tests/testing/mochitest/tests/$(relativesrcdir)
new file mode 100644
--- /dev/null
+++ b/content/xbl/test/test_bug378866.xhtml
@@ -0,0 +1,58 @@
+<?xml version="1.0"?>
+<html xmlns="http://www.w3.org/1999/xhtml">
+<!--
+https://bugzilla.mozilla.org/show_bug.cgi?id=378866
+-->
+<head>
+  <title>Test for Bug 378866</title>
+  <script type="text/javascript" src="/MochiKit/packed.js"></script>
+  <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
+  <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
+  <bindings xmlns="http://www.mozilla.org/xbl" xmlns:html="http://www.w3.org/1999/xhtml">
+    <binding id="b1">
+      <content><html:span><html:span>
+        <children/>
+      </html:span></html:span></content>
+  </binding>
+</bindings>
+
+</head>
+<body>
+<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=378866">Mozilla Bug 378866</a>
+<p id="display"></p>
+<div id="content">
+  <span id="grandparent" style="-moz-binding: url(#b1);">
+    <span id="parent">
+      <span id="child"/>
+    </span>
+  </span>
+</div>
+<pre id="test">
+<script class="testbody" type="text/javascript">
+<![CDATA[
+
+/** Test for Bug 378866 **/
+
+function runTest() {
+  var anon = document.getAnonymousNodes(document.getElementById('grandparent'));
+  var child = document.getElementById('child');
+  var insertionPoint = anon[0].childNodes[0];
+  insertionPoint.parentNode.removeChild(insertionPoint);
+  child.appendChild(insertionPoint);
+
+  var e = document.createEvent("Event");
+  e.initEvent("foo", true, true);
+  child.dispatchEvent(e);
+  ok(true, "Moving insertion point shouldn't cause problems in event dispatching");
+  addLoadEvent(SimpleTest.finish);
+}
+
+SimpleTest.waitForExplicitFinish();
+addLoadEvent(runTest);
+
+]]>
+</script>
+</pre>
+</body>
+</html>
+
--- a/content/xtf/src/nsXMLContentBuilder.cpp
+++ b/content/xtf/src/nsXMLContentBuilder.cpp
@@ -34,17 +34,16 @@
  * 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 "nsCOMPtr.h"
 #include "nsString.h"
 #include "nsIXMLContentBuilder.h"
-#include "nsISupportsArray.h"
 #include "nsINameSpaceManager.h"
 #include "nsINodeInfo.h"
 #include "nsIContent.h"
 #include "nsIComponentManager.h"
 #include "nsIServiceManager.h"
 #include "nsIAtom.h"
 #include "nsContentCID.h"
 #include "nsIDocument.h"
--- a/content/xul/document/src/nsElementMap.cpp
+++ b/content/xul/document/src/nsElementMap.cpp
@@ -45,17 +45,16 @@
 
      NS_PR_LOG_MODULES nsElementMap:5
 
  */
 
 #include "nsCOMPtr.h"
 #include "nsCRT.h"
 #include "nsElementMap.h"
-#include "nsISupportsArray.h"
 #include "nsString.h"
 #include "nsIAtom.h"
 #include "nsReadableUtils.h"
 #include "prlog.h"
 
 #ifdef PR_LOGGING
 static PRLogModuleInfo* gMapLog;
 #endif
--- a/content/xul/document/src/nsXULControllers.h
+++ b/content/xul/document/src/nsXULControllers.h
@@ -44,17 +44,16 @@
 
 #ifndef nsXULControllers_h__
 #define nsXULControllers_h__
 
 #include "nsCOMPtr.h"
 #include "nsVoidArray.h"
 #include "nsWeakPtr.h"
 #include "nsIControllers.h"
-#include "nsISupportsArray.h"
 #include "nsISecurityCheckedComponent.h"
 #include "nsCycleCollectionParticipant.h"
 
 /* non-XPCOM class for holding controllers and their IDs */
 class nsXULControllerData
 {
 public:
                             nsXULControllerData(PRUint32 inControllerID, nsIController* inController)
--- a/content/xul/document/src/nsXULDocument.h
+++ b/content/xul/document/src/nsXULDocument.h
@@ -47,17 +47,16 @@
 
 #include "nsXMLDocument.h"
 #include "nsElementMap.h"
 #include "nsForwardReference.h"
 #include "nsIContent.h"
 #include "nsIDOMEventTarget.h"
 #include "nsIDOMXULCommandDispatcher.h"
 #include "nsIDOMXULDocument.h"
-#include "nsISupportsArray.h"
 #include "nsCOMArray.h"
 #include "nsIURI.h"
 #include "nsIXULDocument.h"
 #include "nsScriptLoader.h"
 #include "nsIStreamListener.h"
 #include "nsICSSLoaderObserver.h"
 
 class nsIRDFResource;
--- a/content/xul/templates/src/nsContentTestNode.cpp
+++ b/content/xul/templates/src/nsContentTestNode.cpp
@@ -32,17 +32,16 @@
  * 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 "nsContentTestNode.h"
-#include "nsISupportsArray.h"
 #include "nsIRDFResource.h"
 #include "nsIAtom.h"
 #include "nsIDOMElement.h"
 #include "nsXULContentUtils.h"
 #include "nsPrintfCString.h"
 #include "nsIXULTemplateResult.h"
 #include "nsIXULTemplateBuilder.h"
 #include "nsXULTemplateQueryProcessorRDF.h"
--- a/docshell/test/Makefile.in
+++ b/docshell/test/Makefile.in
@@ -45,13 +45,14 @@ DIRS += chrome \
 	browser \
 	$(NULL)
 
 include $(DEPTH)/config/autoconf.mk
 include $(topsrcdir)/config/rules.mk
 
 _TEST_FILES = \
 		test_bug344861.html \
+		test_bug384014.html \
 		test_bug387979.html \
 		$(NULL)
 
 libs:: $(_TEST_FILES)
 	$(INSTALL) $(foreach f,$^,"$f") $(DEPTH)/_tests/testing/mochitest/tests/$(relativesrcdir)
new file mode 100644
--- /dev/null
+++ b/docshell/test/test_bug384014.html
@@ -0,0 +1,42 @@
+<!DOCTYPE HTML>
+<html>
+<!--
+https://bugzilla.mozilla.org/show_bug.cgi?id=384014
+-->
+<head>
+  <title>Test for Bug 384014</title>
+  <script type="text/javascript" src="/MochiKit/MochiKit.js"></script>
+  <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
+  <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
+</head>
+<body>
+<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=384014">Mozilla Bug 384014</a>
+<p id="display">
+<iframe id="f" src="javascript:try { window.x = 'PASS'; s = 'PASS' } catch(e) { s = 'FAIL' } s;"></iframe>
+</p>
+<div id="content" style="display: none">
+  
+</div>
+<pre id="test">
+<script class="testbody" type="text/javascript">
+
+/** Test for Bug 384014 **/
+SimpleTest.waitForExplicitFinish();
+
+function runTest() {
+  $("f").onload = function () {
+    is($("f").contentDocument.documentElement.textContent, "PASS",
+      "We fail");
+    SimpleTest.finish();
+  }
+
+  $("f").contentWindow.location.reload();
+}
+
+addLoadEvent(runTest);
+
+</script>
+</pre>
+</body>
+</html>
+
--- a/dom/public/idl/base/nsIDOMWindowUtils.idl
+++ b/dom/public/idl/base/nsIDOMWindowUtils.idl
@@ -66,17 +66,18 @@ interface nsIDOMWindowUtils : nsISupport
    * @note Only images immediately in this window are affected;
    *       this is not recursive to subwindows.
    * @see imgIContainer
    */
   attribute unsigned short imageAnimationMode;
 
   /**
    * Whether the charset of the window's current document has been forced by
-   * the user
+   * the user.
+   * Cannot be accessed from unprivileged context (not content-accessible)
    */
   readonly attribute boolean docCharsetIsForced;
 
   /**
    * Function to get metadata associated with the window's current document
    * @param aName the name of the metadata.  This should be all lowercase.
    * @return the value of the metadata, or the empty string if it's not set
    *
@@ -100,16 +101,20 @@ interface nsIDOMWindowUtils : nsISupport
    * instance, typically a click event will be fired as a result of a
    * mousedown and mouseup in sequence.
    *
    * Normally at this level of events, the mouseover and mouseout events are
    * only fired when the window is entered or exited. For inter-element
    * mouseover and mouseout events, a movemove event fired on the new element
    * should be sufficient to generate the correct over and out events as well.
    *
+   * Cannot be accessed from unprivileged context (not content-accessible)
+   * Will throw a DOM security error if called without UniversalXPConnect
+   * privileges.
+   *
    * @param aType event type
    * @param aX x offset
    * @param aY y offset
    * @param aButton button to synthesize
    * @param aClickCount number of clicks that have been performed
    * @param aModifiers modifiers pressed, using constants defined in nsIDOMNSEvent
    */
   void sendMouseEvent(in AString aType,
@@ -120,27 +125,35 @@ interface nsIDOMWindowUtils : nsISupport
                       in long aModifiers);
 
   /**
    * Synthesize a key event to the window. The event types supported are:
    *   keydown, keyup, keypress
    *
    * Key events generally end up being sent to the focused node.
    *
+   * Cannot be accessed from unprivileged context (not content-accessible)
+   * Will throw a DOM security error if called without UniversalXPConnect
+   * privileges.
+   *
    * @param aType event type
    * @param aKeyCode key code
    * @param aCharCode character code
    * @param aModifiers modifiers pressed, using constants defined in nsIDOMNSEvent
    */
   void sendKeyEvent(in AString aType,
                     in long aKeyCode,
                     in long aCharCode,
                     in long aModifiers);
 
   /**
    * Focus the element aElement. The element should be in the same document
    * that the window is displaying. Pass null to blur the element, if any,
    * that currently has focus, and focus the document.
    *
+   * Cannot be accessed from unprivileged context (not content-accessible)
+   * Will throw a DOM security error if called without UniversalXPConnect
+   * privileges.
+   *
    * @param aElement the element to focus
    */
   void focus(in nsIDOMElement aElement);
 };
--- a/dom/src/base/nsDOMClassInfo.cpp
+++ b/dom/src/base/nsDOMClassInfo.cpp
@@ -1321,16 +1321,26 @@ jsval nsDOMClassInfo::sBaseURIObject_id 
 jsval nsDOMClassInfo::sNodePrincipal_id   = JSVAL_VOID;
 jsval nsDOMClassInfo::sDocumentURIObject_id=JSVAL_VOID;
 jsval nsDOMClassInfo::sOncopy_id          = JSVAL_VOID;
 jsval nsDOMClassInfo::sOncut_id           = JSVAL_VOID;
 jsval nsDOMClassInfo::sOnpaste_id         = JSVAL_VOID;
 jsval nsDOMClassInfo::sOnbeforecopy_id    = JSVAL_VOID;
 jsval nsDOMClassInfo::sOnbeforecut_id     = JSVAL_VOID;
 jsval nsDOMClassInfo::sOnbeforepaste_id   = JSVAL_VOID;
+#ifdef OJI
+jsval nsDOMClassInfo::sJava_id            = JSVAL_VOID;
+jsval nsDOMClassInfo::sPackages_id        = JSVAL_VOID;
+jsval nsDOMClassInfo::sNetscape_id        = JSVAL_VOID;
+jsval nsDOMClassInfo::sSun_id             = JSVAL_VOID;
+jsval nsDOMClassInfo::sJavaObject_id      = JSVAL_VOID;
+jsval nsDOMClassInfo::sJavaClass_id       = JSVAL_VOID;
+jsval nsDOMClassInfo::sJavaArray_id       = JSVAL_VOID;
+jsval nsDOMClassInfo::sJavaMember_id      = JSVAL_VOID;
+#endif
 
 const JSClass *nsDOMClassInfo::sObjectClass = nsnull;
 const JSClass *nsDOMClassInfo::sXPCNativeWrapperClass = nsnull;
 
 PRBool nsDOMClassInfo::sDoSecurityCheckInAddProperty = PR_TRUE;
 
 const JSClass*
 NS_DOMClassInfo_GetXPCNativeWrapperClass()
@@ -1506,16 +1516,26 @@ nsDOMClassInfo::DefineStaticJSVals(JSCon
   SET_JSVAL_TO_STRING(sNodePrincipal_id,   cx, "nodePrincipal");
   SET_JSVAL_TO_STRING(sDocumentURIObject_id,cx,"documentURIObject");
   SET_JSVAL_TO_STRING(sOncopy_id,          cx, "oncopy");
   SET_JSVAL_TO_STRING(sOncut_id,           cx, "oncut");
   SET_JSVAL_TO_STRING(sOnpaste_id,         cx, "onpaste");
   SET_JSVAL_TO_STRING(sOnbeforecopy_id,    cx, "oncopy");
   SET_JSVAL_TO_STRING(sOnbeforecut_id,     cx, "oncut");
   SET_JSVAL_TO_STRING(sOnbeforepaste_id,   cx, "onpaste");
+#ifdef OJI
+  SET_JSVAL_TO_STRING(sJava_id,            cx, "java");
+  SET_JSVAL_TO_STRING(sPackages_id,        cx, "Packages");
+  SET_JSVAL_TO_STRING(sNetscape_id,        cx, "netscape");
+  SET_JSVAL_TO_STRING(sSun_id,             cx, "sun");
+  SET_JSVAL_TO_STRING(sJavaObject_id,      cx, "JavaObject");
+  SET_JSVAL_TO_STRING(sJavaClass_id,       cx, "JavaClass");
+  SET_JSVAL_TO_STRING(sJavaArray_id,       cx, "JavaArray");
+  SET_JSVAL_TO_STRING(sJavaMember_id,      cx, "JavaMember");
+#endif
 
   return NS_OK;
 }
 
 // static
 nsresult
 nsDOMClassInfo::WrapNative(JSContext *cx, JSObject *scope, nsISupports *native,
                            const nsIID& aIID, jsval *vp,
@@ -4045,16 +4065,26 @@ nsDOMClassInfo::ShutDown()
   sNodePrincipal_id   = JSVAL_VOID;
   sDocumentURIObject_id=JSVAL_VOID;
   sOncopy_id          = JSVAL_VOID;
   sOncut_id           = JSVAL_VOID;
   sOnpaste_id         = JSVAL_VOID;
   sOnbeforecopy_id    = JSVAL_VOID;
   sOnbeforecut_id     = JSVAL_VOID;
   sOnbeforepaste_id   = JSVAL_VOID;
+#ifdef OJI
+  sJava_id            = JSVAL_VOID;
+  sPackages_id        = JSVAL_VOID;
+  sNetscape_id        = JSVAL_VOID;
+  sSun_id             = JSVAL_VOID;
+  sJavaObject_id      = JSVAL_VOID;
+  sJavaClass_id       = JSVAL_VOID;
+  sJavaArray_id       = JSVAL_VOID;
+  sJavaMember_id      = JSVAL_VOID;
+#endif
 
   NS_IF_RELEASE(sXPConnect);
   NS_IF_RELEASE(sSecMan);
   sIsInitialized = PR_FALSE;
 }
 
 // Window helper
 
@@ -5377,17 +5407,19 @@ nsWindowSH::GlobalResolve(nsGlobalWindow
                                               getter_AddRefs(proto_holder));
       NS_ENSURE_SUCCESS(rv, NS_ERROR_UNEXPECTED);
 
       rv = proto_holder->GetJSObject(&dot_prototype);
       NS_ENSURE_SUCCESS(rv, NS_ERROR_UNEXPECTED);
 
       JSObject *xpc_proto_proto = ::JS_GetPrototype(cx, dot_prototype);
 
-      if (proto && JS_GET_CLASS(cx, xpc_proto_proto) == sObjectClass) {
+      if (proto &&
+          (!xpc_proto_proto ||
+           JS_GET_CLASS(cx, xpc_proto_proto) == sObjectClass)) {
         if (!::JS_SetPrototype(cx, dot_prototype, proto)) {
           return NS_ERROR_UNEXPECTED;
         }
       }
     } else if (name_struct->mType == nsGlobalNameStruct::eTypeExternalClassInfo) {
       nsCOMPtr<nsIClassInfo> ci = GetClassInfoInstance(name_struct->mData);
       NS_ENSURE_TRUE(ci, NS_ERROR_UNEXPECTED);
 
@@ -5398,17 +5430,19 @@ nsWindowSH::GlobalResolve(nsGlobalWindow
                                               getter_AddRefs(proto_holder));
       NS_ENSURE_SUCCESS(rv, NS_ERROR_UNEXPECTED);
 
       rv = proto_holder->GetJSObject(&dot_prototype);
       NS_ENSURE_SUCCESS(rv, NS_ERROR_UNEXPECTED);
 
       JSObject *xpc_proto_proto = ::JS_GetPrototype(cx, dot_prototype);
 
-      if (proto && JS_GET_CLASS(cx, xpc_proto_proto) == sObjectClass) {
+      if (proto &&
+          (!xpc_proto_proto ||
+           JS_GET_CLASS(cx, xpc_proto_proto) == sObjectClass)) {
         if (!::JS_SetPrototype(cx, dot_prototype, proto)) {
           return NS_ERROR_UNEXPECTED;
         }
       }
     } else {
       dot_prototype = ::JS_NewObject(cx, &sDOMConstructorProtoClass, proto,
                                      obj);
       NS_ENSURE_TRUE(dot_prototype, NS_ERROR_OUT_OF_MEMORY);
@@ -6023,16 +6057,56 @@ nsWindowSH::NewResolve(nsIXPConnectWrapp
 
       if (!ok) {
         return NS_ERROR_FAILURE;
       }
       *objp = obj;
 
       return NS_OK;
     }
+
+#ifdef OJI
+    if (id == sJava_id || id == sPackages_id || id == sNetscape_id ||
+        id == sSun_id || id == sJavaObject_id || id == sJavaClass_id ||
+        id == sJavaArray_id || id == sJavaMember_id
+        ) {
+      static PRBool isResolvingJavaProperties;
+
+      if (!isResolvingJavaProperties) {
+        isResolvingJavaProperties = PR_TRUE;
+
+        PRBool oldVal = sDoSecurityCheckInAddProperty;
+        sDoSecurityCheckInAddProperty = PR_FALSE;
+
+        // Tell the window to initialize the Java properties. The
+        // window needs to do this as we need to do this only once,
+        // and detecting that reliably from here is hard.
+
+        win->InitJavaProperties(); 
+
+        sDoSecurityCheckInAddProperty = oldVal;
+
+        PRBool hasProp;
+        PRBool ok = ::JS_HasProperty(cx, obj, ::JS_GetStringBytes(str),
+                                     &hasProp);
+
+        isResolvingJavaProperties = PR_FALSE;
+
+        if (!ok) {
+          return NS_ERROR_FAILURE;
+        }
+
+        if (hasProp) {
+          *objp = obj;
+
+          return NS_OK;
+        }
+      }
+    }
+#endif
   }
 
   return nsEventReceiverSH::NewResolve(wrapper, cx, obj, id, flags, objp,
                                        _retval);
 }
 
 NS_IMETHODIMP
 nsWindowSH::NewEnumerate(nsIXPConnectWrappedNative *wrapper, JSContext *cx,
--- a/dom/src/base/nsDOMClassInfo.h
+++ b/dom/src/base/nsDOMClassInfo.h
@@ -313,16 +313,26 @@ protected:
   static jsval sNodePrincipal_id;
   static jsval sDocumentURIObject_id;
   static jsval sOncopy_id;
   static jsval sOncut_id;
   static jsval sOnpaste_id;
   static jsval sOnbeforecopy_id;
   static jsval sOnbeforecut_id;
   static jsval sOnbeforepaste_id;
+#ifdef OJI
+  static jsval sJava_id;
+  static jsval sPackages_id;
+  static jsval sNetscape_id;
+  static jsval sSun_id;
+  static jsval sJavaObject_id;
+  static jsval sJavaClass_id;
+  static jsval sJavaArray_id;
+  static jsval sJavaMember_id;
+#endif
 
   static const JSClass *sObjectClass;
   static const JSClass *sXPCNativeWrapperClass;
 
 public:
   static PRBool sDoSecurityCheckInAddProperty;
 };
 
--- a/dom/src/base/nsDOMWindowUtils.cpp
+++ b/dom/src/base/nsDOMWindowUtils.cpp
@@ -292,16 +292,21 @@ nsDOMWindowUtils::GetWidget()
   }
 
   return nsnull;
 }
 
 NS_IMETHODIMP
 nsDOMWindowUtils::Focus(nsIDOMElement* aElement)
 {
+  PRBool hasCap = PR_FALSE;
+  if (NS_FAILED(nsContentUtils::GetSecurityManager()->IsCapabilityEnabled(
+    "UniversalXPConnect", &hasCap)) || !hasCap)
+    return NS_ERROR_DOM_SECURITY_ERR;
+
   if (mWindow) {
     nsCOMPtr<nsIContent> content = do_QueryInterface(aElement);
     if (content) {
       nsCOMPtr<nsIDocument> doc(do_QueryInterface(mWindow->GetExtantDocument()));
       if (!doc || content->GetCurrentDoc() != doc)
         return NS_ERROR_FAILURE;
     }
 
--- a/dom/src/base/nsGlobalWindow.cpp
+++ b/dom/src/base/nsGlobalWindow.cpp
@@ -67,18 +67,20 @@
 #include "nsIEventListenerManager.h"
 #include "nsEscape.h"
 #include "nsStyleCoord.h"
 #include "nsMimeTypeArray.h"
 #include "nsNetUtil.h"
 #include "nsICachingChannel.h"
 #include "nsPluginArray.h"
 #include "nsIPluginHost.h"
+#include "nsPIPluginHost.h"
 #ifdef OJI
 #include "nsIJVMManager.h"
+#include "nsILiveConnectManager.h"
 #endif
 #include "nsContentCID.h"
 #include "nsLayoutStatics.h"
 #include "nsCycleCollector.h"
 #include "nsCCUncollectableMarker.h"
 
 // Interfaces Needed
 #include "nsIWidget.h"
@@ -145,16 +147,17 @@
 #include "nsPIWindowWatcher.h"
 #include "nsIContentViewer.h"
 #include "nsDOMClassInfo.h"
 #include "nsIJSNativeInitializer.h"
 #include "nsIFullScreen.h"
 #include "nsIScriptError.h"
 #include "nsIScriptEventManager.h" // For GetInterface()
 #include "nsIConsoleService.h"
+#include "nsIControllers.h"
 #include "nsIControllerContext.h"
 #include "nsGlobalWindowCommands.h"
 #include "nsAutoPtr.h"
 #include "nsContentUtils.h"
 #include "nsCSSProps.h"
 #include "nsIURIFixup.h"
 #include "nsCDefaultURIFixup.h"
 #include "nsEventDispatcher.h"
@@ -373,16 +376,163 @@ StripNullChars(const nsAString& aInStr,
 
   while (start != end) {
     if (*start != '\0')
       aOutStr.Append(*start);
     ++start;
   }
 }
 
+#ifdef OJI
+class nsDummyJavaPluginOwner : public nsIPluginInstanceOwner
+{
+public:
+  nsDummyJavaPluginOwner(nsIDocument *aDocument)
+    : mDocument(aDocument)
+  {
+  }
+
+  void Destroy();
+
+  NS_DECL_CYCLE_COLLECTING_ISUPPORTS
+  NS_DECL_NSIPLUGININSTANCEOWNER
+
+  // XXXjst: What's up with nsIPluginInstanceOwner and these functions?
+  NS_IMETHOD GetURL(const char *aURL, const char *aTarget, void *aPostData,
+                    PRUint32 aPostDataLen, void *aHeadersData,
+                    PRUint32 aHeadersDataLen, PRBool aIsFile = PR_FALSE);
+  NS_IMETHOD ShowStatus(const PRUnichar *aStatusMsg);
+
+  NS_DECL_CYCLE_COLLECTION_CLASS(nsDummyJavaPluginOwner)
+
+private:
+  nsCOMPtr<nsIPluginInstance> mInstance;
+  nsCOMPtr<nsIDocument> mDocument;
+};
+
+NS_IMPL_CYCLE_COLLECTION_2(nsDummyJavaPluginOwner, mDocument, mInstance)
+
+// QueryInterface implementation for nsDummyJavaPluginOwner
+NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(nsDummyJavaPluginOwner)
+  NS_INTERFACE_MAP_ENTRY(nsISupports)
+  NS_INTERFACE_MAP_ENTRY(nsIPluginInstanceOwner)
+NS_INTERFACE_MAP_END
+
+NS_IMPL_CYCLE_COLLECTING_ADDREF(nsDummyJavaPluginOwner)
+NS_IMPL_CYCLE_COLLECTING_RELEASE(nsDummyJavaPluginOwner)
+
+
+void
+nsDummyJavaPluginOwner::Destroy()
+{
+  // If we have a plugin instance, stop it and destroy it now.
+  if (mInstance) {
+    mInstance->Stop();
+    mInstance->Destroy();
+
+    mInstance = nsnull;
+  }
+
+  mDocument = nsnull;
+}
+
+NS_IMETHODIMP
+nsDummyJavaPluginOwner::SetInstance(nsIPluginInstance *aInstance)
+{
+  mInstance = aInstance;
+
+  return NS_OK;
+}
+
+NS_IMETHODIMP
+nsDummyJavaPluginOwner::GetInstance(nsIPluginInstance *&aInstance)
+{
+  NS_IF_ADDREF(aInstance = mInstance);
+
+  return NS_OK;
+}
+
+NS_IMETHODIMP
+nsDummyJavaPluginOwner::GetWindow(nsPluginWindow *&aWindow)
+{
+  aWindow = nsnull;
+
+  return NS_OK;
+}
+
+NS_IMETHODIMP
+nsDummyJavaPluginOwner::GetMode(nsPluginMode *aMode)
+{
+  // This is wrong, but there's no better alternative.
+  *aMode = nsPluginMode_Embedded;
+
+  return NS_ERROR_NOT_IMPLEMENTED;
+}
+
+NS_IMETHODIMP
+nsDummyJavaPluginOwner::CreateWidget(void)
+{
+  return NS_ERROR_NOT_IMPLEMENTED;
+}
+
+NS_IMETHODIMP
+nsDummyJavaPluginOwner::GetURL(const char *aURL, const char *aTarget,
+                               void *aPostData, PRUint32 aPostDataLen,
+                               void *aHeadersData, PRUint32 aHeadersDataLen,
+                               PRBool isFile)
+{
+  return NS_ERROR_NOT_IMPLEMENTED;
+}
+
+NS_IMETHODIMP
+nsDummyJavaPluginOwner::ShowStatus(const char *aStatusMsg)
+{
+  return NS_ERROR_NOT_IMPLEMENTED;
+}
+
+NS_IMETHODIMP
+nsDummyJavaPluginOwner::ShowStatus(const PRUnichar *aStatusMsg)
+{
+  return NS_ERROR_NOT_IMPLEMENTED;
+}
+
+NS_IMETHODIMP
+nsDummyJavaPluginOwner::GetDocument(nsIDocument **aDocument)
+{
+  NS_IF_ADDREF(*aDocument = mDocument);
+
+  return NS_OK;
+}
+
+NS_IMETHODIMP
+nsDummyJavaPluginOwner::InvalidateRect(nsPluginRect *invalidRect)
+{
+  return NS_ERROR_NOT_IMPLEMENTED;
+}
+
+NS_IMETHODIMP
+nsDummyJavaPluginOwner::InvalidateRegion(nsPluginRegion invalidRegion)
+{
+  return NS_ERROR_NOT_IMPLEMENTED;
+}
+
+NS_IMETHODIMP
+nsDummyJavaPluginOwner::ForceRedraw()
+{
+  return NS_ERROR_NOT_IMPLEMENTED;
+}
+
+NS_IMETHODIMP
+nsDummyJavaPluginOwner::GetValue(nsPluginInstancePeerVariable variable,
+                                 void *value)
+{
+  return NS_ERROR_NOT_IMPLEMENTED;
+}
+#endif
+
 /**
  * An indirect observer object that means we don't have to implement nsIObserver
  * on nsGlobalWindow, where any script could see it.
  */
 class nsGlobalWindowObserver : public nsIObserver {
 public:
   nsGlobalWindowObserver(nsGlobalWindow* aWindow) : mWindow(aWindow) {}
   NS_DECL_ISUPPORTS
@@ -431,16 +581,17 @@ nsTimeout::~nsTimeout()
   
 //*****************************************************************************
 //***    nsGlobalWindow: Object Management
 //*****************************************************************************
 
 nsGlobalWindow::nsGlobalWindow(nsGlobalWindow *aOuterWindow)
   : nsPIDOMWindow(aOuterWindow),
     mIsFrozen(PR_FALSE),
+    mDidInitJavaProperties(PR_FALSE),
     mFullScreen(PR_FALSE),
     mIsClosed(PR_FALSE), 
     mInClose(PR_FALSE), 
     mHavePendingClose(PR_FALSE),
     mHadOriginalOpener(PR_FALSE),
     mIsPopupSpam(PR_FALSE),
     mBlockScriptedClosingFlag(PR_FALSE),
     mFireOfflineStatusChangeEventOnThaw(PR_FALSE),
@@ -704,16 +855,29 @@ nsGlobalWindow::FreeInnerObjects(PRBool 
       // Note that scx comes from the outer window.  If this is an inner
       // window, it may not be the current inner for its outer.
       nsIScriptContext *scx = GetScriptContextInternal(lang_id);
       if (scx)
         scx->ClearScope(mScriptGlobals[NS_STID_INDEX(lang_id)], PR_TRUE);
     }
   }
 
+#ifdef OJI
+  if (mDummyJavaPluginOwner) {
+    // Tear down the dummy java plugin.
+
+    // XXXjst: On a general note, should windows with java stuff in
+    // them ever even make it into the fast-back cache?
+
+    mDummyJavaPluginOwner->Destroy();
+
+    mDummyJavaPluginOwner = nsnull;
+  }
+#endif
+
 #ifdef DEBUG
   nsCycleCollector_DEBUG_shouldBeFreed(static_cast<nsIScriptGlobalObject*>(this));
 #endif
 }
 
 //*****************************************************************************
 // nsGlobalWindow::nsISupports
 //*****************************************************************************
@@ -784,16 +948,22 @@ NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN(
     if (tmp->mDoc) {
       cb.NoteXPCOMChild(tmp->mDoc->GetReference(tmp));
     }
   }
 
   // Traverse stuff from nsPIDOMWindow
   NS_IMPL_CYCLE_COLLECTION_TRAVERSE_NSCOMPTR(mChromeEventHandler)
   NS_IMPL_CYCLE_COLLECTION_TRAVERSE_NSCOMPTR(mDocument)
+
+#ifdef OJI
+  // Traverse mDummyJavaPluginOwner
+  NS_IMPL_CYCLE_COLLECTION_TRAVERSE_NSCOMPTR(mDummyJavaPluginOwner)
+#endif
+
 NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END
 
 NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN(nsGlobalWindow)
   NS_IMPL_CYCLE_COLLECTION_UNLINK_NSCOMPTR(mContext)
 
   // See comment about traversing mOpener above.
   // NS_IMPL_CYCLE_COLLECTION_UNLINK_NSCOMPTR(mOpener)
 
@@ -820,16 +990,25 @@ NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN(ns
   if (tmp->mDoc) {
     tmp->mDoc->RemoveReference(tmp->mDoc.get());
     NS_IMPL_CYCLE_COLLECTION_UNLINK_NSCOMPTR(mDoc)
   }
 
   // Unlink stuff from nsPIDOMWindow
   NS_IMPL_CYCLE_COLLECTION_UNLINK_NSCOMPTR(mChromeEventHandler)
   NS_IMPL_CYCLE_COLLECTION_UNLINK_NSCOMPTR(mDocument)
+
+#ifdef OJI
+  // Unlink mDummyJavaPluginOwner
+  if (tmp->mDummyJavaPluginOwner) {
+    tmp->mDummyJavaPluginOwner->Destroy();
+    NS_IMPL_CYCLE_COLLECTION_UNLINK_NSCOMPTR(mDummyJavaPluginOwner)
+  }
+#endif
+
 NS_IMPL_CYCLE_COLLECTION_UNLINK_END
 
 
 //*****************************************************************************
 // nsGlobalWindow::nsIScriptGlobalObject
 //*****************************************************************************
 
 nsresult
@@ -5068,16 +5247,92 @@ nsGlobalWindow::IsInModalState()
     return PR_FALSE;
   }
 
   return static_cast<nsGlobalWindow *>
                     (static_cast<nsIDOMWindow *>
                                 (top.get()))->mModalStateDepth != 0;
 }
 
+#ifdef OJI
+void
+nsGlobalWindow::InitJavaProperties()
+{
+  nsIScriptContext *scx = GetContextInternal();
+
+  if (mDidInitJavaProperties || IsOuterWindow() || !scx || !mJSObject) {
+    return;
+  }
+
+  // Set mDidInitJavaProperties to true here even if initialization
+  // can fail. If it fails, we won't try again...
+  mDidInitJavaProperties = PR_TRUE;
+
+  // Check whether the plugin supports NPRuntime, if so, init through
+  // it, else use liveconnect.
+
+  nsCOMPtr<nsPIPluginHost> host(do_GetService("@mozilla.org/plugin/host;1"));
+  if (!host) {
+    return;
+  }
+
+  mDummyJavaPluginOwner = new nsDummyJavaPluginOwner(mDoc);
+  if (!mDummyJavaPluginOwner) {
+    return;
+  }
+
+  host->InstantiateDummyJavaPlugin(mDummyJavaPluginOwner);
+
+  nsCOMPtr<nsIPluginInstance> dummyPlugin;
+  mDummyJavaPluginOwner->GetInstance(*getter_AddRefs(dummyPlugin));
+
+  if (dummyPlugin) {
+    // A dummy plugin was instantiated. This means we have a Java
+    // plugin that supports NPRuntime. For such a plugin, the plugin
+    // instantiation code defines the Java properties for us, so we're
+    // done here.
+
+    return;
+  }
+
+  // No NPRuntime enabled Java plugin found, null out the owner we
+  // would have used in that case as it's no longer needed.
+  mDummyJavaPluginOwner = nsnull;
+
+  JSContext *cx = (JSContext *)scx->GetNativeContext();
+
+  nsCOMPtr<nsILiveConnectManager> manager =
+    do_GetService(nsIJVMManager::GetCID());
+
+  if (!manager) {
+    return;
+  }
+
+  PRBool started = PR_FALSE;
+  manager->StartupLiveConnect(::JS_GetRuntime(cx), started);
+
+  nsCOMPtr<nsIJVMManager> jvmManager(do_QueryInterface(manager));
+
+  if (!jvmManager) {
+    return;
+  }
+
+  PRBool javaEnabled = PR_FALSE;
+  if (NS_FAILED(jvmManager->GetJavaEnabled(&javaEnabled)) || !javaEnabled) {
+    return;
+  }
+
+  {
+    JSAutoRequest ar(cx);
+
+    manager->InitLiveConnectClasses(cx, mJSObject);
+  }
+}
+#endif
+
 NS_IMETHODIMP
 nsGlobalWindow::GetFrameElement(nsIDOMElement** aFrameElement)
 {
   FORWARD_TO_OUTER(GetFrameElement, (aFrameElement), NS_ERROR_NOT_INITIALIZED);
 
   *aFrameElement = nsnull;
 
   nsCOMPtr<nsIDocShellTreeItem> docShellTI(do_QueryInterface(mDocShell));
--- a/dom/src/base/nsGlobalWindow.h
+++ b/dom/src/base/nsGlobalWindow.h
@@ -51,17 +51,16 @@
 #include "nsHashtable.h"
 #include "nsDataHashtable.h"
 #include "nsCycleCollectionParticipant.h"
 
 // Interfaces Needed
 #include "nsDOMWindowList.h"
 #include "nsIBaseWindow.h"
 #include "nsIBrowserDOMWindow.h"
-#include "nsIControllers.h"
 #include "nsIDocShellTreeOwner.h"
 #include "nsIDocShellTreeItem.h"
 #include "nsIDOMClientInformation.h"
 #include "nsIDOMViewCSS.h"
 #include "nsIDOMEventTarget.h"
 #include "nsIDOM3EventTarget.h"
 #include "nsIDOMNSEventTarget.h"
 #include "nsIDOMNavigator.h"
@@ -103,26 +102,30 @@
 #define PREF_BROWSER_STARTUP_HOMEPAGE "browser.startup.homepage"
 
 class nsIDOMBarProp;
 class nsIDocument;
 class nsIContent;
 class nsPresContext;
 class nsIDOMEvent;
 class nsIScrollableView;
+class nsIControllers;
 
 class nsBarProp;
 class nsLocation;
 class nsNavigator;
 class nsScreen;
 class nsHistory;
 class nsIDocShellLoadInfo;
 class WindowStateHolder;
 class nsGlobalWindowObserver;
 class nsGlobalWindow;
+#ifdef OJI
+class nsDummyJavaPluginOwner;
+#endif
 
 class nsDOMOfflineResourceList;
 class nsDOMOfflineLoadStatusList;
 
 // permissible values for CheckOpenAllow
 enum OpenAllowValue {
   allowNot = 0,     // the window opening is denied
   allowNoAbuse,     // allowed: not a popup
@@ -414,16 +417,20 @@ public:
   static void RunPendingTimeoutsRecursive(nsGlobalWindow *aTopWindow,
                                           nsGlobalWindow *aWindow);
 
   friend class WindowStateHolder;
 
   NS_DECL_CYCLE_COLLECTION_CLASS_AMBIGUOUS(nsGlobalWindow,
                                            nsIScriptGlobalObject)
 
+#ifdef OJI
+  void InitJavaProperties();
+#endif
+
 protected:
   // Object Management
   virtual ~nsGlobalWindow();
   void CleanUp();
   void ClearControllers();
 
   void FreeInnerObjects(PRBool aClearScope);
 
@@ -621,16 +628,20 @@ protected:
   // This member is also used on both inner and outer windows, but
   // for slightly different purposes. On inner windows it means the
   // inner window is held onto by session history and should not
   // change. On outer windows it means that the window is in a state
   // where we don't want to force creation of a new inner window since
   // we're in the middle of doing just that.
   PRPackedBool                  mIsFrozen : 1;
 
+  // True if the Java properties have been initialized on this
+  // window. Only used on inner windows.
+  PRPackedBool                  mDidInitJavaProperties : 1;
+  
   // These members are only used on outer window objects. Make sure
   // you never set any of these on an inner object!
   PRPackedBool                  mFullScreen : 1;
   PRPackedBool                  mIsClosed : 1;
   PRPackedBool                  mInClose : 1;
   // mHavePendingClose means we've got a termination function set to
   // close us when the JS stops executing or that we have a close
   // event posted.  If this is set, just ignore window.close() calls.
@@ -689,16 +700,20 @@ protected:
   nsCOMPtr<nsIEventListenerManager> mListenerManager;
   PRCList                       mTimeouts;
   // If mTimeoutInsertionPoint is non-null, insertions should happen after it.
   nsTimeout*                    mTimeoutInsertionPoint;
   PRUint32                      mTimeoutPublicIdCounter;
   PRUint32                      mTimeoutFiringDepth;
   nsCOMPtr<nsIDOMStorage>       mSessionStorage;
 
+#ifdef OJI
+  nsRefPtr<nsDummyJavaPluginOwner> mDummyJavaPluginOwner;
+#endif
+
   // These member variables are used on both inner and the outer windows.
   nsCOMPtr<nsIPrincipal> mDocumentPrincipal;
   nsCOMPtr<nsIDocument> mDoc;  // For fast access to principals
   JSObject* mJSObject;
 
   nsDataHashtable<nsStringHashKey, PRBool> *mPendingStorageEvents;
 
 #ifdef DEBUG
--- a/dom/src/base/nsJSEnvironment.cpp
+++ b/dom/src/base/nsJSEnvironment.cpp
@@ -115,21 +115,16 @@
 
 #ifdef MOZ_LOGGING
 // Force PR_LOGGING so we can get JS strict warnings even in release builds
 #define FORCE_PR_LOG 1
 #endif
 #include "prlog.h"
 #include "prthread.h"
 
-#ifdef OJI
-#include "nsIJVMManager.h"
-#include "nsILiveConnectManager.h"
-#endif
-
 const size_t gStackSize = 8192;
 
 #ifdef PR_LOGGING
 static PRLogModuleInfo* gJSDiagnostics;
 #endif
 
 // Thank you Microsoft!
 #ifndef WINCE
@@ -2324,46 +2319,16 @@ nsresult
 nsJSContext::InitializeExternalClasses()
 {
   NS_ENSURE_TRUE(gNameSpaceManager, NS_ERROR_NOT_INITIALIZED);
 
   return gNameSpaceManager->InitForContext(this);
 }
 
 nsresult
-nsJSContext::InitializeLiveConnectClasses(JSObject *aGlobalObj)
-{
-  nsresult rv = NS_OK;
-
-#ifdef OJI
-  nsCOMPtr<nsIJVMManager> jvmManager =
-    do_GetService(nsIJVMManager::GetCID(), &rv);
-
-  if (NS_SUCCEEDED(rv) && jvmManager) {
-    PRBool javaEnabled = PR_FALSE;
-
-    rv = jvmManager->GetJavaEnabled(&javaEnabled);
-
-    if (NS_SUCCEEDED(rv) && javaEnabled) {
-      nsCOMPtr<nsILiveConnectManager> liveConnectManager =
-        do_QueryInterface(jvmManager);
-
-      if (liveConnectManager) {
-        JSAutoRequest ar(mContext);
-        rv = liveConnectManager->InitLiveConnectClasses(mContext, aGlobalObj);
-      }
-    }
-  }
-#endif /* OJI */
-
-  // return all is well until things are stable.
-  return NS_OK;
-}
-
-nsresult
 nsJSContext::SetProperty(void *aTarget, const char *aPropName, nsISupports *aArgs)
 {
   PRUint32  argc;
   jsval    *argv = nsnull;
   void *mark;
 
   JSAutoRequest ar(mContext);
 
@@ -3017,19 +2982,16 @@ nsJSContext::InitClasses(void *aGlobalOb
 {
   nsresult rv = NS_OK;
 
   JSObject *globalObj = static_cast<JSObject *>(aGlobalObj);
 
   rv = InitializeExternalClasses();
   NS_ENSURE_SUCCESS(rv, rv);
 
-  rv = InitializeLiveConnectClasses(globalObj);
-  NS_ENSURE_SUCCESS(rv, rv);
-
   JSAutoRequest ar(mContext);
 
   // Initialize the options object and set default options in mContext
   JSObject *optionsObj = ::JS_DefineObject(mContext, globalObj, "_options",
                                            &OptionsClass, nsnull, 0);
   if (optionsObj &&
       ::JS_DefineProperties(mContext, optionsObj, OptionsProperties)) {
     ::JS_SetOptions(mContext, mDefaultJSOptions);
@@ -3515,32 +3477,16 @@ nsJSRuntime::Init()
     ::JS_SetObjectPrincipalsFinder(sRuntime, ObjectPrincipalFinder);
   NS_ASSERTION(!oldfop, " fighting over the findObjectPrincipals callback!");
 
   // Set these global xpconnect options...
   nsIXPConnect *xpc = nsContentUtils::XPConnect();
   xpc->SetCollectGarbageOnMainThreadOnly(PR_TRUE);
   xpc->SetDeferReleasesUntilAfterGarbageCollection(PR_TRUE);
 
-#ifdef OJI
-  // Initialize LiveConnect.  XXXbe use contractid rather than GetCID
-  // NOTE: LiveConnect is optional so initialisation will still succeed
-  //       even if the service is not present.
-  nsCOMPtr<nsILiveConnectManager> manager =
-           do_GetService(nsIJVMManager::GetCID());
-
-  // Should the JVM manager perhaps define methods for starting up
-  // LiveConnect?
-  if (manager) {
-    PRBool started = PR_FALSE;
-    rv = manager->StartupLiveConnect(sRuntime, started);
-    // XXX Did somebody mean to check |rv| ?
-  }
-#endif /* OJI */
-
   nsContentUtils::RegisterPrefCallback("dom.max_script_run_time",
                                        MaxScriptRunTimePrefChangedCallback,
                                        nsnull);
   MaxScriptRunTimePrefChangedCallback("dom.max_script_run_time", nsnull);
 
   nsContentUtils::RegisterPrefCallback("dom.max_chrome_script_run_time",
                                        MaxScriptRunTimePrefChangedCallback,
                                        nsnull);
--- a/dom/src/base/nsJSEnvironment.h
+++ b/dom/src/base/nsJSEnvironment.h
@@ -167,17 +167,16 @@ public:
 
   NS_DECL_NSITIMERCALLBACK
 
   static void LoadStart();
   static void LoadEnd();
 
 protected:
   nsresult InitializeExternalClasses();
-  nsresult InitializeLiveConnectClasses(JSObject *aGlobalObj);
   // aHolder should be holding our global object
   nsresult FindXPCNativeWrapperClass(nsIXPConnectJSObjectHolder *aHolder);
 
   // Helper to convert xpcom datatypes to jsvals.
   nsresult ConvertSupportsTojsvals(nsISupports *aArgs,
                                    void *aScope,
                                    PRUint32 *aArgc, void **aArgv,
                                    void **aMarkp);
--- a/dom/src/storage/nsDOMStorage.cpp
+++ b/dom/src/storage/nsDOMStorage.cpp
@@ -48,16 +48,17 @@
 #include "nsIPrincipal.h"
 #include "nsIURI.h"
 #include "nsReadableUtils.h"
 #include "nsIObserverService.h"
 #include "nsNetUtil.h"
 #include "nsIPrefBranch.h"
 #include "nsICookiePermission.h"
 #include "nsIPermissionManager.h"
+#include "nsCycleCollectionParticipant.h"
 
 static const PRUint32 ASK_BEFORE_ACCEPT = 1;
 static const PRUint32 ACCEPT_SESSION = 2;
 static const PRUint32 BEHAVIOR_REJECT = 2;
 
 static const PRUint32 DEFAULT_QUOTA = 5 * 1024;
 
 static const char kPermissionType[] = "cookie";
@@ -250,26 +251,48 @@ nsDOMStorageEntry::nsDOMStorageEntry(con
 {
   NS_ERROR("DOMStorage horked.");
 }
 
 nsDOMStorageEntry::~nsDOMStorageEntry()
 {
 }
 
-NS_INTERFACE_MAP_BEGIN(nsDOMStorage)
+PLDHashOperator PR_CALLBACK
+SessionStorageTraverser(nsSessionStorageEntry* aEntry, void* userArg) {
+  nsCycleCollectionTraversalCallback *cb = 
+    static_cast<nsCycleCollectionTraversalCallback*>(userArg);
+
+  cb->NoteXPCOMChild((nsIDOMStorageItem *) aEntry->mItem);
+
+  return PL_DHASH_NEXT;
+}
+
+NS_IMPL_CYCLE_COLLECTION_CLASS(nsDOMStorage)
+NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN(nsDOMStorage)
+  NS_IMPL_CYCLE_COLLECTION_UNLINK_NSCOMPTR(mURI)
+NS_IMPL_CYCLE_COLLECTION_UNLINK_END
+NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN(nsDOMStorage)
+  NS_IMPL_CYCLE_COLLECTION_TRAVERSE_NSCOMPTR(mURI)
+  {
+    if (tmp->mItems.IsInitialized()) {
+      tmp->mItems.EnumerateEntries(SessionStorageTraverser, &cb);
+    }
+  }
+NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END
+
+NS_IMPL_CYCLE_COLLECTING_ADDREF_AMBIGUOUS(nsDOMStorage, nsIDOMStorage)
+NS_IMPL_CYCLE_COLLECTING_RELEASE_AMBIGUOUS(nsDOMStorage, nsIDOMStorage)
+NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(nsDOMStorage)
   NS_INTERFACE_MAP_ENTRY_AMBIGUOUS(nsISupports, nsIDOMStorage)
   NS_INTERFACE_MAP_ENTRY(nsIDOMStorage)
   NS_INTERFACE_MAP_ENTRY(nsPIDOMStorage)
   NS_DOM_INTERFACE_MAP_ENTRY_CLASSINFO(Storage)
 NS_INTERFACE_MAP_END
 
-NS_IMPL_ADDREF(nsDOMStorage)
-NS_IMPL_RELEASE(nsDOMStorage)
-
 NS_IMETHODIMP
 NS_NewDOMStorage(nsISupports* aOuter, REFNSIID aIID, void** aResult)
 {
   nsDOMStorage* storage = new nsDOMStorage();
   if (!storage)
     return NS_ERROR_OUT_OF_MEMORY;
 
   NS_ADDREF(storage);
@@ -1061,26 +1084,37 @@ NS_NewDOMStorageList(nsIDOMStorageList**
   NS_ADDREF(*aResult);
   return NS_OK;
 }
 
 //
 // nsDOMStorageItem
 //
 
-NS_INTERFACE_MAP_BEGIN(nsDOMStorageItem)
+NS_IMPL_CYCLE_COLLECTION_CLASS(nsDOMStorageItem)
+NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN(nsDOMStorageItem)
+  {
+    tmp->mStorage = nsnull;
+  }
+NS_IMPL_CYCLE_COLLECTION_UNLINK_END
+NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN(nsDOMStorageItem)
+  {
+    cb.NoteXPCOMChild((nsIDOMStorage*) tmp->mStorage);
+  }
+NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END
+
+NS_IMPL_CYCLE_COLLECTING_ADDREF_AMBIGUOUS(nsDOMStorageItem, nsIDOMStorageItem)
+NS_IMPL_CYCLE_COLLECTING_RELEASE_AMBIGUOUS(nsDOMStorageItem, nsIDOMStorageItem)
+NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(nsDOMStorageItem)
   NS_INTERFACE_MAP_ENTRY_AMBIGUOUS(nsISupports, nsIDOMStorageItem)
   NS_INTERFACE_MAP_ENTRY(nsIDOMStorageItem)
   NS_INTERFACE_MAP_ENTRY(nsIDOMToString)
   NS_DOM_INTERFACE_MAP_ENTRY_CLASSINFO(StorageItem)
 NS_INTERFACE_MAP_END
 
-NS_IMPL_ADDREF(nsDOMStorageItem)
-NS_IMPL_RELEASE(nsDOMStorageItem)
-
 nsDOMStorageItem::nsDOMStorageItem(nsDOMStorage* aStorage,
                                    const nsAString& aKey,
                                    const nsAString& aValue,
                                    PRBool aSecure)
   : mSecure(aSecure),
     mKey(aKey),
     mValue(aValue),
     mStorage(aStorage)
--- a/dom/src/storage/nsDOMStorage.h
+++ b/dom/src/storage/nsDOMStorage.h
@@ -47,16 +47,17 @@
 #include "nsIDOMStorageItem.h"
 #include "nsInterfaceHashtable.h"
 #include "nsVoidArray.h"
 #include "nsPIDOMStorage.h"
 #include "nsIDOMToString.h"
 #include "nsDOMEvent.h"
 #include "nsIDOMStorageEvent.h"
 #include "nsIDOMStorageManager.h"
+#include "nsCycleCollectionParticipant.h"
 
 #ifdef MOZ_STORAGE
 #include "nsDOMStorageDB.h"
 #endif
 
 class nsDOMStorage;
 class nsDOMStorageItem;
 
@@ -114,17 +115,18 @@ class nsDOMStorage : public nsIDOMStorag
                      public nsPIDOMStorage
 {
 public:
   nsDOMStorage();
   nsDOMStorage(nsIURI* aURI, const nsAString& aDomain, PRBool aUseDB);
   virtual ~nsDOMStorage();
 
   // nsISupports
-  NS_DECL_ISUPPORTS
+  NS_DECL_CYCLE_COLLECTING_ISUPPORTS
+  NS_DECL_CYCLE_COLLECTION_CLASS_AMBIGUOUS(nsDOMStorage, nsIDOMStorage)
 
   // nsIDOMStorage
   NS_DECL_NSIDOMSTORAGE
 
   // nsPIDOMStorage
   virtual void Init(nsIURI* aURI, const nsAString& aDomain, PRBool aUseDB);
   virtual already_AddRefed<nsIDOMStorage> Clone(nsIURI* aURI);
   virtual nsTArray<nsString> *GetKeys();
@@ -257,17 +259,18 @@ class nsDOMStorageItem : public nsIDOMSt
 public:
   nsDOMStorageItem(nsDOMStorage* aStorage,
                    const nsAString& aKey,
                    const nsAString& aValue,
                    PRBool aSecure);
   virtual ~nsDOMStorageItem();
 
   // nsISupports
-  NS_DECL_ISUPPORTS
+  NS_DECL_CYCLE_COLLECTING_ISUPPORTS
+  NS_DECL_CYCLE_COLLECTION_CLASS_AMBIGUOUS(nsDOMStorageItem, nsIDOMStorageItem)
 
   // nsIDOMStorage
   NS_DECL_NSIDOMSTORAGEITEM
 
   // nsIDOMToString
   NS_DECL_NSIDOMTOSTRING
 
   PRBool IsSecure()
--- a/editor/ui/composer/content/editor.js
+++ b/editor/ui/composer/content/editor.js
@@ -3370,17 +3370,17 @@ function GetSelectionContainer()
   // and don't select anonymous content !!! (fix for bug 190279)
   while (result.node.hasAttribute("_moz_editor_bogus_node") ||
          editor.isAnonymousElement(result.node))
     result.node = result.node.parentNode;
 
   return result;
 }
 
-function FillInHTMLTooltip(tooltip)
+function FillInHTMLTooltipEditor(tooltip)
 {
   const XLinkNS = "http://www.w3.org/1999/xlink";
   var tooltipText = null;
   var node;
   if (gEditorDisplayMode == kDisplayModePreview) {
     for (node = document.tooltipNode; node; node = node.parentNode) {
       if (node.nodeType == Node.ELEMENT_NODE) {
         tooltipText = node.getAttributeNS(XLinkNS, "title");
--- a/editor/ui/composer/content/editor.xul
+++ b/editor/ui/composer/content/editor.xul
@@ -102,17 +102,17 @@
     <commandset id="composerEditMenuItems"/>
     <commandset id="composerSaveMenuItems"/>    
     <commandset id="composerStyleMenuItems"/>
     <commandset id="composerTableMenuItems"/>
     <commandset id="composerListMenuItems"/>
     <command id="toggleSidebar"/>
   </commandset>
 
-  <tooltip id="aHTMLTooltip" onpopupshowing="return FillInHTMLTooltip(this);"/>
+  <tooltip id="aHTMLTooltip" onpopupshowing="return FillInHTMLTooltipEditor(this);"/>
 
   <broadcaster id="args" value="about:blank"/>
   <broadcaster id="canPrint"/>
   
   <!-- Interim hack to transition from nsIXULWindowCallbacks/ShowWindowWithArgs
   <broadcaster id="dialog.start" ready="false"/>
   <observes element="dialog.start" attribute="ready" onbroadcast="EditorStartup('html')"/>
 -->
deleted file mode 100644
--- a/embedding/browser/cocoa/Makefile.in
+++ /dev/null
@@ -1,65 +0,0 @@
-# ***** 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.
-# Portions created by the Initial Developer are Copyright (C) 2001
-# the Initial Developer. All Rights Reserved.
-#
-# Contributor(s):
-#   Conrad Carlen <ccarlen@netscape.com>
-#
-# Alternatively, the contents of this file may be used under the terms of
-# either the GNU General Public License Version 2 or later (the "GPL"), or
-# the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
-# in which case the provisions of the GPL or the LGPL are applicable instead
-# of those above. If you wish to allow use of your version of this file only
-# under the terms of either the GPL or the LGPL, and not to allow others to
-# use your version of this file under the terms of the MPL, indicate your
-# decision by deleting the provisions above and replace them with the notice
-# and other provisions required by the GPL or the LGPL. If you do not delete
-# the provisions above, a recipient may use your version of this file under
-# the terms of any one of the MPL, the GPL or the LGPL.
-#
-# ***** END LICENSE BLOCK *****
-
-DEPTH		= ../../../
-topsrcdir	= @top_srcdir@
-srcdir		= @srcdir@
-VPATH		= @srcdir@
-
-include $(DEPTH)/config/autoconf.mk
-
-ifdef MOZ_DEBUG
-BUILDSTYLE	= Development
-else
-BUILDSTYLE	= Deployment
-endif
-
-include $(topsrcdir)/config/rules.mk
-
-ABS_topsrcdir   := $(shell cd $(topsrcdir); pwd)
-ifneq ($(ABS_topsrcdir),$(MOZ_BUILD_ROOT))
-export::
-	rsync -a --exclude .DS_Store --exclude "CVS/" $(srcdir)/NSBrowserView.pbproj .
-	ln -fs $(srcdir)/src
-	ln -fs $(srcdir)/res
-endif
-
-libs::
-	pbxbuild -buildstyle $(BUILDSTYLE) build
-
-clean clobber::
-	rm -rf build
deleted file mode 100644
--- a/embedding/browser/cocoa/NSBrowserView.pbproj/project.pbxproj
+++ /dev/null
@@ -1,752 +0,0 @@
-// !$*UTF8*$!
-{
-	archiveVersion = 1;
-	classes = {
-	};
-	objectVersion = 38;
-	objects = {
-		014CEA440018CDF011CA2923 = {
-			buildRules = (
-			);
-			buildSettings = {
-				COPY_PHASE_STRIP = NO;
-				OTHER_CFLAGS = "\U0001 -DDEBUG -DTRACING -DMOZ_DEBUG";
-			};
-			isa = PBXBuildStyle;
-			name = Development;
-		};
-		014CEA450018CDF011CA2923 = {
-			buildRules = (
-			);
-			buildSettings = {
-				COPY_PHASE_STRIP = YES;
-				DEBUGGING_SYMBOLS = NO;
-				OPTIMIZATION_CFLAGS = "-O";
-			};
-			isa = PBXBuildStyle;
-			name = Deployment;
-		};
-//010
-//011
-//012
-//013
-//014
-//030
-//031
-//032
-//033
-//034
-		034768DFFF38A50411DB9C8B = {
-			children = (
-				034768E0FF38A50411DB9C8B,
-			);
-			isa = PBXGroup;
-			name = Products;
-			path = "";
-			refType = 2;
-		};
-		034768E0FF38A50411DB9C8B = {
-			isa = PBXFrameworkReference;
-			path = CHBrowserView.framework;
-			refType = 3;
-		};
-//030
-//031
-//032
-//033
-//034
-//080
-//081
-//082
-//083
-//084
-		0867D690FE84028FC02AAC07 = {
-			buildStyles = (
-				014CEA440018CDF011CA2923,
-				014CEA450018CDF011CA2923,
-			);
-			hasScannedForEncodings = 1;
-			isa = PBXProject;
-			mainGroup = 0867D691FE84028FC02AAC07;
-			productRefGroup = 034768DFFF38A50411DB9C8B;
-			projectDirPath = "";
-			targets = (
-				0867D69CFE84028FC02AAC07,
-			);
-		};
-		0867D691FE84028FC02AAC07 = {
-			children = (
-				F57D38AE0330DCA001026D5D,
-				08FB77AEFE84172EC02AAC07,
-				F6BA6D4C01B2EFCE01A962F7,
-				79C235890439D34800202892,
-				089C1665FE841158C02AAC07,
-				0867D69AFE84028FC02AAC07,
-				034768DFFF38A50411DB9C8B,
-			);
-			isa = PBXGroup;
-			name = NSBrowserView;
-			refType = 4;
-		};
-		0867D69AFE84028FC02AAC07 = {
-			children = (
-				1058C7B0FEA5585E11CA2CBB,
-				1058C7B2FEA5585E11CA2CBB,
-			);
-			isa = PBXGroup;
-			name = "External Frameworks and Libraries";
-			refType = 4;
-		};
-		0867D69BFE84028FC02AAC07 = {
-			isa = PBXFrameworkReference;
-			name = Foundation.framework;
-			path = /System/Library/Frameworks/Foundation.framework;
-			refType = 0;
-		};
-		0867D69CFE84028FC02AAC07 = {
-			buildPhases = (
-				0867D69DFE84028FC02AAC07,
-				0867D69EFE84028FC02AAC07,
-				0867D69FFE84028FC02AAC07,
-				0867D6A0FE84028FC02AAC07,
-				0867D6A2FE84028FC02AAC07,
-			);
-			buildSettings = {
-				DYLIB_COMPATIBILITY_VERSION = 1;
-				DYLIB_CURRENT_VERSION = 1;
-				FRAMEWORK_SEARCH_PATHS = "";
-				FRAMEWORK_VERSION = A;
-				HEADER_SEARCH_PATHS = "../../../dist/include/mimetype ../../../dist/include/find ../../../dist/include/webbrowserpersist ../../../dist/include/commandhandler ../../../dist/include/exthandler ../../../dist/include/helperAppDlg ../../../dist/include/profile ../../../dist/include/xpcom ../../../dist/include/string ../../../dist/include/docshell ../../../dist/include/webshell ../../../dist/include/necko ../../../dist/include/widget ../../../dist/include/dom ../../../dist/include/gfx ../../../dist/include/layout ../../../dist/include/content ../../../dist/include/uriloader ../../../dist/include/webbrwsr ../../../dist/include/shistory ../../../dist/include/embed_base ../../../dist/include/pref ../../../dist/include/windowwatcher ../../../dist/include ../../../dist/include/nspr";
-				LIBRARY_SEARCH_PATHS = "../../../dist/bin ../../../dist/lib ../../../dist/Embed /Users/conrad/Development/TRUNK/MachObj/obj-cocoa-debug/xpcom/build";
-				OPTIMIZATION_CFLAGS = "-O0";
-				OTHER_CFLAGS = "-fno-rtti -fno-exceptions -fpascal-strings -fshort-wchar -DOSTYPE=\\\"Darwin1.4\\\" -DOSARCH=\\\"Darwin\\\" -DIBMBIDI";
-				OTHER_LDFLAGS = "-lxpcom -lplds4 -lplc4 -lnspr4 -lpthread -lm";
-				PREFIX_HEADER = "../../../mozilla-config.h";
-				PRODUCT_NAME = CHBrowserView;
-				SECTORDER_FLAGS = "";
-				USE_GCC3_PFE_SUPPORT = NO;
-				WARNING_CFLAGS = "-Wmost -Wno-four-char-constants -Wno-unknown-pragmas -Wall -Wconversion -Wpointer-arith -Wbad-function-cast -Wcast-align -Woverloaded-virtual -Wsynth -Wno-long-long";
-				WRAPPER_EXTENSION = framework;
-			};
-			dependencies = (
-			);
-			isa = PBXFrameworkTarget;
-			name = NSBrowserView;
-			productName = NSBrowserView;
-			productReference = 034768E0FF38A50411DB9C8B;
-			productSettingsXML = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>
-<!DOCTYPE plist PUBLIC \"-//Apple Computer//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">
-<plist version=\"1.0\">
-<dict>
-	<key>CFBundleDevelopmentRegion</key>
-	<string>English</string>
-	<key>CFBundleDocumentTypes</key>
-	<array/>
-	<key>CFBundleExecutable</key>
-	<string>CHBrowserView</string>
-	<key>CFBundleIconFile</key>
-	<string></string>
-	<key>CFBundleIdentifier</key>
-	<string></string>
-	<key>CFBundleInfoDictionaryVersion</key>
-	<string>6.0</string>
-	<key>CFBundlePackageType</key>
-	<string>FMWK</string>
-	<key>CFBundleSignature</key>
-	<string>????</string>
-	<key>CFBundleVersion</key>
-	<string>0.0.1d1</string>
-	<key>NSPrincipalClass</key>
-	<string></string>
-</dict>
-</plist>
-";
-		};
-		0867D69DFE84028FC02AAC07 = {
-			buildActionMask = 2147483647;
-			files = (
-				F57D389F0330DAB701026D5D,
-				F57D38A10330DAB701026D5D,
-				F57D38A30330DAB701026D5D,
-				F57D38A50330DAB701026D5D,
-				F57D38A70330DAB701026D5D,
-				F57D38A90330DAB701026D5D,
-				F57D38AC0330DC9701026D5D,
-				F57D38B90330E3E601026D5D,
-				F57D38BA0330E3E601026D5D,
-				F57D38BB0330E3E701026D5D,
-				F52978A70371981B01026DCE,
-			);
-			isa = PBXHeadersBuildPhase;
-			runOnlyForDeploymentPostprocessing = 0;
-		};
-		0867D69EFE84028FC02AAC07 = {
-			buildActionMask = 2147483647;
-			files = (
-				089C1668FE841158C02AAC07,
-				F64C5F2901B5904701A962F7,
-			);
-			isa = PBXResourcesBuildPhase;
-			runOnlyForDeploymentPostprocessing = 0;
-		};
-		0867D69FFE84028FC02AAC07 = {
-			buildActionMask = 2147483647;
-			files = (
-				F64C5F1B01B58AC001A962F7,
-				F57D38A00330DAB701026D5D,
-				F57D38A20330DAB701026D5D,
-				F57D38A60330DAB701026D5D,
-				F57D38A80330DAB701026D5D,
-				F57D38AD0330DC9701026D5D,
-				F57D38B60330E3E101026D5D,
-				F57D38B70330E3E201026D5D,
-				F57D38B80330E3E301026D5D,
-				F52978A60371981A01026DCE,
-				79C235950439D56C00202892,
-			);
-			isa = PBXSourcesBuildPhase;
-			runOnlyForDeploymentPostprocessing = 0;
-		};
-		0867D6A0FE84028FC02AAC07 = {
-			buildActionMask = 2147483647;
-			files = (
-				F6BA6D6001B3008E01A962F7,
-				79C2358B0439D3B700202892,
-			);
-			isa = PBXFrameworksBuildPhase;
-			runOnlyForDeploymentPostprocessing = 0;
-		};
-		0867D6A2FE84028FC02AAC07 = {
-			buildActionMask = 2147483647;
-			files = (
-			);
-			isa = PBXRezBuildPhase;
-			runOnlyForDeploymentPostprocessing = 0;
-		};
-		0867D6A5FE840307C02AAC07 = {
-			isa = PBXFrameworkReference;
-			name = AppKit.framework;
-			path = /System/Library/Frameworks/AppKit.framework;
-			refType = 0;
-		};
-		089C1665FE841158C02AAC07 = {
-			children = (
-				089C1666FE841158C02AAC07,
-				F64C5F2701B5904701A962F7,
-			);
-			isa = PBXGroup;
-			name = Resources;
-			refType = 4;
-		};
-		089C1666FE841158C02AAC07 = {
-			children = (
-				089C1667FE841158C02AAC07,
-			);
-			isa = PBXVariantGroup;
-			name = InfoPlist.strings;
-			refType = 4;
-		};
-		089C1667FE841158C02AAC07 = {
-			fileEncoding = 10;
-			isa = PBXFileReference;
-			name = InfoPlist.strings;
-			path = res/English.lproj/InfoPlist.strings;
-			refType = 4;
-		};
-		089C1668FE841158C02AAC07 = {
-			fileRef = 089C1666FE841158C02AAC07;
-			isa = PBXBuildFile;
-			settings = {
-			};
-		};
-		08FB77AEFE84172EC02AAC07 = {
-			children = (
-				F57D38B30330E1D801026D5D,
-				F64C5F1A01B58AC001A962F7,
-				F57D38950330DAB701026D5D,
-				F57D38970330DAB701026D5D,
-				79C235930439D56C00202892,
-				F52978A50371981701026DCE,
-			);
-			isa = PBXGroup;
-			name = Classes;
-			refType = 4;
-		};
-//080
-//081
-//082
-//083
-//084
-//100
-//101
-//102
-//103
-//104
-		1058C7B0FEA5585E11CA2CBB = {
-			children = (
-				1058C7B1FEA5585E11CA2CBB,
-			);
-			isa = PBXGroup;
-			name = "Linked Frameworks";
-			refType = 4;
-		};
-		1058C7B1FEA5585E11CA2CBB = {
-			isa = PBXFrameworkReference;
-			name = Cocoa.framework;
-			path = /System/Library/Frameworks/Cocoa.framework;
-			refType = 0;
-		};
-		1058C7B2FEA5585E11CA2CBB = {
-			children = (
-				0867D69BFE84028FC02AAC07,
-				0867D6A5FE840307C02AAC07,
-			);
-			isa = PBXGroup;
-			name = "Other Frameworks";
-			refType = 4;
-		};
-//100
-//101
-//102
-//103
-//104
-//790
-//791
-//792
-//793
-//794
-		79C235710438E63900202892 = {
-			children = (
-				F57D389A0330DAB701026D5D,
-				F57D389C0330DAB701026D5D,
-				F57D38AF0330DFF201026D5D,
-				F57D38B10330E1D101026D5D,
-				F57D38B40330E25501026D5D,
-			);
-			isa = PBXGroup;
-			name = Download;
-			refType = 4;
-		};
-		79C235890439D34800202892 = {
-			children = (
-				79C2358A0439D3B700202892,
-			);
-			isa = PBXGroup;
-			name = "Gecko Libraries";
-			path = "";
-			refType = 4;
-		};
-		79C2358A0439D3B700202892 = {
-			isa = PBXFileReference;
-			name = libembed_base_s.a;
-			path = ../../base/libembed_base_s.a;
-			refType = 2;
-		};
-		79C2358B0439D3B700202892 = {
-			fileRef = 79C2358A0439D3B700202892;
-			isa = PBXBuildFile;
-			settings = {
-			};
-		};
-		79C235930439D56C00202892 = {
-			fileEncoding = 30;
-			isa = PBXFileReference;
-			name = CHBrowserView.mm;
-			path = src/CHBrowserView.mm;
-			refType = 4;
-		};
-		79C235950439D56C00202892 = {
-			fileRef = 79C235930439D56C00202892;
-			isa = PBXBuildFile;
-			settings = {
-			};
-		};
-//790
-//791
-//792
-//793
-//794
-//F50
-//F51
-//F52
-//F53
-//F54
-		F52978A40371981701026DCE = {
-			fileEncoding = 30;
-			isa = PBXFileReference;
-			name = CHClickListener.h;
-			path = src/CHClickListener.h;
-			refType = 2;
-		};
-		F52978A50371981701026DCE = {
-			fileEncoding = 30;
-			isa = PBXFileReference;
-			name = CHClickListener.mm;
-			path = src/CHClickListener.mm;
-			refType = 2;
-		};
-		F52978A60371981A01026DCE = {
-			fileRef = F52978A50371981701026DCE;
-			isa = PBXBuildFile;
-			settings = {
-			};
-		};
-		F52978A70371981B01026DCE = {
-			fileRef = F52978A40371981701026DCE;
-			isa = PBXBuildFile;
-			settings = {
-			};
-		};
-		F57D38940330DAB701026D5D = {
-			fileEncoding = 30;
-			isa = PBXFileReference;
-			name = CHBrowserListener.h;
-			path = src/CHBrowserListener.h;
-			refType = 2;
-		};
-		F57D38950330DAB701026D5D = {
-			fileEncoding = 30;
-			isa = PBXFileReference;
-			name = CHBrowserListener.mm;
-			path = src/CHBrowserListener.mm;
-			refType = 2;
-		};
-		F57D38960330DAB701026D5D = {
-			fileEncoding = 30;
-			isa = PBXFileReference;
-			name = CHBrowserService.h;
-			path = src/CHBrowserService.h;
-			refType = 2;
-		};
-		F57D38970330DAB701026D5D = {
-			fileEncoding = 30;
-			isa = PBXFileReference;
-			name = CHBrowserService.mm;
-			path = src/CHBrowserService.mm;
-			refType = 2;
-		};
-		F57D38980330DAB701026D5D = {
-			fileEncoding = 30;
-			isa = PBXFileReference;
-			name = CHBrowserView.h;
-			path = src/CHBrowserView.h;
-			refType = 2;
-		};
-		F57D389A0330DAB701026D5D = {
-			fileEncoding = 30;
-			isa = PBXFileReference;
-			name = CHDownloadFactories.h;
-			path = src/CHDownloadFactories.h;
-			refType = 2;
-		};
-		F57D389B0330DAB701026D5D = {
-			fileEncoding = 30;
-			isa = PBXFileReference;
-			name = CHDownloadFactories.mm;
-			path = src/CHDownloadFactories.mm;
-			refType = 2;
-		};
-		F57D389C0330DAB701026D5D = {
-			fileEncoding = 30;
-			isa = PBXFileReference;
-			name = CHDownloadProgressDisplay.h;
-			path = src/CHDownloadProgressDisplay.h;
-			refType = 2;
-		};
-		F57D389D0330DAB701026D5D = {
-			fileEncoding = 30;
-			isa = PBXFileReference;
-			name = CHDownloadProgressDisplay.mm;
-			path = src/CHDownloadProgressDisplay.mm;
-			refType = 2;
-		};
-		F57D389E0330DAB701026D5D = {
-			fileEncoding = 30;
-			isa = PBXFileReference;
-			name = nsAlertController.h;
-			path = src/nsAlertController.h;
-			refType = 2;
-		};
-		F57D389F0330DAB701026D5D = {
-			fileRef = F57D38940330DAB701026D5D;
-			isa = PBXBuildFile;
-			settings = {
-				ATTRIBUTES = (
-					Public,
-				);
-			};
-		};
-		F57D38A00330DAB701026D5D = {
-			fileRef = F57D38950330DAB701026D5D;
-			isa = PBXBuildFile;
-			settings = {
-			};
-		};
-		F57D38A10330DAB701026D5D = {
-			fileRef = F57D38960330DAB701026D5D;
-			isa = PBXBuildFile;
-			settings = {
-				ATTRIBUTES = (
-					Public,
-				);
-			};
-		};
-		F57D38A20330DAB701026D5D = {
-			fileRef = F57D38970330DAB701026D5D;
-			isa = PBXBuildFile;
-			settings = {
-			};
-		};
-		F57D38A30330DAB701026D5D = {
-			fileRef = F57D38980330DAB701026D5D;
-			isa = PBXBuildFile;
-			settings = {
-				ATTRIBUTES = (
-					Public,
-				);
-			};
-		};
-		F57D38A50330DAB701026D5D = {
-			fileRef = F57D389A0330DAB701026D5D;
-			isa = PBXBuildFile;
-			settings = {
-				ATTRIBUTES = (
-					Public,
-				);
-			};
-		};
-		F57D38A60330DAB701026D5D = {
-			fileRef = F57D389B0330DAB701026D5D;
-			isa = PBXBuildFile;
-			settings = {
-			};
-		};
-		F57D38A70330DAB701026D5D = {
-			fileRef = F57D389C0330DAB701026D5D;
-			isa = PBXBuildFile;
-			settings = {
-				ATTRIBUTES = (
-					Public,
-				);
-			};
-		};
-		F57D38A80330DAB701026D5D = {
-			fileRef = F57D389D0330DAB701026D5D;
-			isa = PBXBuildFile;
-			settings = {
-			};
-		};
-		F57D38A90330DAB701026D5D = {
-			fileRef = F57D389E0330DAB701026D5D;
-			isa = PBXBuildFile;
-			settings = {
-				ATTRIBUTES = (
-					Public,
-				);
-			};
-		};
-		F57D38AA0330DC9701026D5D = {
-			fileEncoding = 30;
-			isa = PBXFileReference;
-			name = "NSString+Utils.h";
-			path = "src/NSString+Utils.h";
-			refType = 2;
-		};
-		F57D38AB0330DC9701026D5D = {
-			fileEncoding = 30;
-			isa = PBXFileReference;
-			name = "NSString+Utils.mm";
-			path = "src/NSString+Utils.mm";
-			refType = 2;
-		};
-		F57D38AC0330DC9701026D5D = {
-			fileRef = F57D38AA0330DC9701026D5D;
-			isa = PBXBuildFile;
-			settings = {
-				ATTRIBUTES = (
-					Public,
-				);
-			};
-		};
-		F57D38AD0330DC9701026D5D = {
-			fileRef = F57D38AB0330DC9701026D5D;
-			isa = PBXBuildFile;
-			settings = {
-			};
-		};
-		F57D38AE0330DCA001026D5D = {
-			children = (
-				F57D38AA0330DC9701026D5D,
-				F57D38AB0330DC9701026D5D,
-			);
-			isa = PBXGroup;
-			name = Extensions;
-			path = "";
-			refType = 4;
-		};
-		F57D38AF0330DFF201026D5D = {
-			fileEncoding = 30;
-			isa = PBXFileReference;
-			name = SaveHeaderSniffer.h;
-			path = src/SaveHeaderSniffer.h;
-			refType = 2;
-		};
-		F57D38B00330DFF201026D5D = {
-			fileEncoding = 30;
-			isa = PBXFileReference;
-			name = SaveHeaderSniffer.mm;
-			path = src/SaveHeaderSniffer.mm;
-			refType = 2;
-		};
-		F57D38B10330E1D101026D5D = {
-			fileEncoding = 30;
-			isa = PBXFileReference;
-			name = nsDownloadListener.h;
-			path = src/nsDownloadListener.h;
-			refType = 2;
-		};
-		F57D38B20330E1D101026D5D = {
-			fileEncoding = 30;
-			isa = PBXFileReference;
-			name = nsDownloadListener.mm;
-			path = src/nsDownloadListener.mm;
-			refType = 2;
-		};
-		F57D38B30330E1D801026D5D = {
-			children = (
-				F57D389B0330DAB701026D5D,
-				F57D389D0330DAB701026D5D,
-				F57D38B00330DFF201026D5D,
-				F57D38B20330E1D101026D5D,
-				F57D38B50330E25501026D5D,
-			);
-			isa = PBXGroup;
-			name = Download;
-			refType = 4;
-		};
-		F57D38B40330E25501026D5D = {
-			fileEncoding = 30;
-			isa = PBXFileReference;
-			name = ProgressDlgController.h;
-			path = src/ProgressDlgController.h;
-			refType = 2;
-		};
-		F57D38B50330E25501026D5D = {
-			fileEncoding = 30;
-			isa = PBXFileReference;
-			name = ProgressDlgController.mm;
-			path = src/ProgressDlgController.mm;
-			refType = 2;
-		};
-		F57D38B60330E3E101026D5D = {
-			fileRef = F57D38B00330DFF201026D5D;
-			isa = PBXBuildFile;
-			settings = {
-			};
-		};
-		F57D38B70330E3E201026D5D = {
-			fileRef = F57D38B20330E1D101026D5D;
-			isa = PBXBuildFile;
-			settings = {
-			};
-		};
-		F57D38B80330E3E301026D5D = {
-			fileRef = F57D38B50330E25501026D5D;
-			isa = PBXBuildFile;
-			settings = {
-			};
-		};
-		F57D38B90330E3E601026D5D = {
-			fileRef = F57D38AF0330DFF201026D5D;
-			isa = PBXBuildFile;
-			settings = {
-				ATTRIBUTES = (
-					Public,
-				);
-			};
-		};
-		F57D38BA0330E3E601026D5D = {
-			fileRef = F57D38B10330E1D101026D5D;
-			isa = PBXBuildFile;
-			settings = {
-				ATTRIBUTES = (
-					Public,
-				);
-			};
-		};
-		F57D38BB0330E3E701026D5D = {
-			fileRef = F57D38B40330E25501026D5D;
-			isa = PBXBuildFile;
-			settings = {
-				ATTRIBUTES = (
-					Public,
-				);
-			};
-		};
-//F50
-//F51
-//F52
-//F53
-//F54
-//F60
-//F61
-//F62
-//F63
-//F64
-		F64C5F1A01B58AC001A962F7 = {
-			fileEncoding = 30;
-			isa = PBXFileReference;
-			name = nsAlertController.mm;
-			path = src/nsAlertController.mm;
-			refType = 2;
-		};
-		F64C5F1B01B58AC001A962F7 = {
-			fileRef = F64C5F1A01B58AC001A962F7;
-			isa = PBXBuildFile;
-			settings = {
-			};
-		};
-		F64C5F2701B5904701A962F7 = {
-			children = (
-				F64C5F2801B5904701A962F7,
-			);
-			isa = PBXVariantGroup;
-			name = alert.nib;
-			path = "";
-			refType = 2;
-		};
-		F64C5F2801B5904701A962F7 = {
-			isa = PBXFileReference;
-			name = alert.nib;
-			path = res/English.lproj/alert.nib;
-			refType = 4;
-		};
-		F64C5F2901B5904701A962F7 = {
-			fileRef = F64C5F2701B5904701A962F7;
-			isa = PBXBuildFile;
-			settings = {
-			};
-		};
-		F6BA6D4C01B2EFCE01A962F7 = {
-			children = (
-				79C235710438E63900202892,
-				F57D389E0330DAB701026D5D,
-				F57D38940330DAB701026D5D,
-				F57D38960330DAB701026D5D,
-				F57D38980330DAB701026D5D,
-				F52978A40371981701026DCE,
-			);
-			isa = PBXGroup;
-			name = Headers;
-			path = "";
-			refType = 4;
-		};
-		F6BA6D6001B3008E01A962F7 = {
-			fileRef = 1058C7B1FEA5585E11CA2CBB;
-			isa = PBXBuildFile;
-			settings = {
-			};
-		};
-	};
-	rootObject = 0867D690FE84028FC02AAC07;
-}
deleted file mode 100644
index ec220a6f7004d68f2f6c8239b055160fcd80a876..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
GIT binary patch
literal 0
Hc$@<O00001
deleted file mode 100644
--- a/embedding/browser/cocoa/res/English.lproj/alert.nib/classes.nib
+++ /dev/null
@@ -1,39 +0,0 @@
-{
-    IBClasses = (
-        {CLASS = FirstResponder; LANGUAGE = ObjC; SUPERCLASS = NSObject; }, 
-        {CLASS = "java.lang.Object"; LANGUAGE = Java; }, 
-        {
-            ACTIONS = {hitButton1 = id; hitButton2 = id; hitButton3 = id; }; 
-            CLASS = nsAlertController; 
-            LANGUAGE = ObjC; 
-            OUTLETS = {
-                alertCheckPanel = id; 
-                alertCheckPanelCheck = id; 
-                alertCheckPanelText = id; 
-                alertPanel = id; 
-                alertPanelText = id; 
-                confirmCheckPanel = id; 
-                confirmCheckPanelCheck = id; 
-                confirmCheckPanelText = id; 
-                confirmPanel = id; 
-                confirmPanelText = id; 
-                owner = id; 
-                passwordPanel = id; 
-                passwordPanelCheck = id; 
-                passwordPanelInput = id; 
-                passwordPanelText = id; 
-                promptPanel = id; 
-                promptPanelCheck = id; 
-                promptPanelInput = id; 
-                promptPanelText = id; 
-                usernamePanel = id; 
-                usernamePanelCheck = id; 
-                usernamePanelPassword = id; 
-                usernamePanelText = id; 
-                usernamePanelUserName = id; 
-            }; 
-            SUPERCLASS = NSObject; 
-        }
-    ); 
-    IBVersion = 1; 
-}
\ No newline at end of file
deleted file mode 100644
--- a/embedding/browser/cocoa/res/English.lproj/alert.nib/info.nib
+++ /dev/null
@@ -1,12 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
-<plist version="1.0">
-<dict>
-	<key>IBDocumentLocation</key>
-	<string>19 95 356 240 0 0 1152 848 </string>
-	<key>IBFramework Version</key>
-	<string>291.0</string>
-	<key>IBSystem Version</key>
-	<string>6I32</string>
-</dict>
-</plist>
deleted file mode 100644
index 012991aadd6f6f1c19dd64f5c1e62d892e41e93e..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
GIT binary patch
literal 0
Hc$@<O00001
deleted file mode 100644
--- a/embedding/browser/cocoa/src/CHBrowserListener.h
+++ /dev/null
@@ -1,90 +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 Chimera.
- *
- * The Initial Developer of the Original Code is
- * Simon Fraser.
- * Portions created by the Initial Developer are Copyright (C) 2002
- * 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 ***** */
-
-#ifndef __nsCocoaBrowserListener_h__
-#define __nsCocoaBrowserListener_h__
-
-#include "nsWeakReference.h"
-#include "nsIInterfaceRequestor.h"
-#include "nsIWebBrowser.h"
-#include "nsIWebBrowserChrome.h"
-#include "nsIWebProgressListener.h"
-#include "nsIEmbeddingSiteWindow2.h"
-#include "nsIWindowCreator.h"
-
-#include "nsIContextMenuListener.h"
-#include "nsITooltipListener.h"
-
-@class CHBrowserView;
-
-class CHBrowserListener : public nsSupportsWeakReference,
-                               public nsIInterfaceRequestor,
-                               public nsIWebBrowserChrome,
-                               public nsIWindowCreator,
-                               public nsIEmbeddingSiteWindow2,
-                               public nsIWebProgressListener,
-                               public nsIContextMenuListener,
-                               public nsITooltipListener
-{
-public:
-  CHBrowserListener(CHBrowserView* aView);
-  virtual ~CHBrowserListener();
-
-  NS_DECL_ISUPPORTS
-  NS_DECL_NSIINTERFACEREQUESTOR
-  NS_DECL_NSIWEBBROWSERCHROME
-  NS_DECL_NSIWINDOWCREATOR
-  NS_DECL_NSIEMBEDDINGSITEWINDOW
-  NS_DECL_NSIEMBEDDINGSITEWINDOW2
-  NS_DECL_NSIWEBPROGRESSLISTENER
-  NS_DECL_NSICONTEXTMENULISTENER
-  NS_DECL_NSITOOLTIPLISTENER
-    
-  void AddListener(id <CHBrowserListener> aListener);
-  void RemoveListener(id <CHBrowserListener> aListener);
-  void SetContainer(id <CHBrowserContainer> aContainer);
-
-private:
-  CHBrowserView*          mView;     // WEAK - it owns us
-  NSMutableArray*         mListeners;
-  id <CHBrowserContainer> mContainer;
-  PRBool                  mIsModal;
-  PRUint32                mChromeFlags;
-};
-
-
-#endif // __nsCocoaBrowserListener_h__
deleted file mode 100644
--- a/embedding/browser/cocoa/src/CHBrowserListener.mm
+++ /dev/null
@@ -1,608 +0,0 @@
-/* ***** 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 Chimera code.
- *
- * The Initial Developer of the Original Code is
- * Netscape Communications Corporation.
- * Portions created by the Initial Developer are Copyright (C) 2002
- * the Initial Developer. All Rights Reserved.
- *
- * Contributor(s):
- *   Simon Fraser <sfraser@netscape.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 ***** */
-
-#import <Cocoa/Cocoa.h>
-
-#import "NSString+Utils.h"
-
-// Embedding includes
-#include "nsIWebBrowser.h"
-#include "nsIWebNavigation.h"
-#include "nsIURI.h"
-#include "nsIDOMWindow.h"
-//#include "nsIWidget.h"
-
-// XPCOM and String includes
-#include "nsCRT.h"
-#include "nsString.h"
-#include "nsCOMPtr.h"
-
-#import "CHBrowserView.h"
-
-#include "CHBrowserListener.h"
-
-
-CHBrowserListener::CHBrowserListener(CHBrowserView* aView)
-  : mView(aView), mContainer(nsnull), mIsModal(PR_FALSE), mChromeFlags(0)
-{
-  mListeners = [[NSMutableArray alloc] init];
-}
-
-CHBrowserListener::~CHBrowserListener()
-{
-  [mListeners release];
-  mView = nsnull;
-  if (mContainer) {
-    [mContainer release];
-  }
-}
-
-NS_IMPL_ISUPPORTS9(CHBrowserListener,
-                   nsIInterfaceRequestor,
-                   nsIWebBrowserChrome,
-                   nsIWindowCreator,
-                   nsIEmbeddingSiteWindow,
-                   nsIEmbeddingSiteWindow2,
-                   nsIWebProgressListener,
-                   nsISupportsWeakReference,
-                   nsIContextMenuListener,
-                   nsITooltipListener)
-
-// Implementation of nsIInterfaceRequestor
-NS_IMETHODIMP 
-CHBrowserListener::GetInterface(const nsIID &aIID, void** aInstancePtr)
-{
-  if (aIID.Equals(NS_GET_IID(nsIDOMWindow))) {
-    nsCOMPtr<nsIWebBrowser> browser = dont_AddRef([mView getWebBrowser]);
-    if (browser)
-      return browser->GetContentDOMWindow((nsIDOMWindow **) aInstancePtr);
-  }
-  
-  return QueryInterface(aIID, aInstancePtr);
-}
-
-// Implementation of nsIWindowCreator.  The CocoaBrowserService forwards requests
-// for a new window that have a parent to us, and we take over from there.  
-/* nsIWebBrowserChrome createChromeWindow (in nsIWebBrowserChrome parent, in PRUint32 chromeFlags); */
-NS_IMETHODIMP 
-CHBrowserListener::CreateChromeWindow(nsIWebBrowserChrome *parent, 
-                                           PRUint32 chromeFlags, 
-                                           nsIWebBrowserChrome **_retval)
-{
-  if (parent != this) {
-#if DEBUG
-    NSLog(@"Mismatch in CHBrowserListener::CreateChromeWindow.  We should be the owning parent.");
-#endif
-    return NS_ERROR_FAILURE;
-  }
-  
-  CHBrowserView* childView = [mContainer createBrowserWindow: chromeFlags];
-  if (!childView) {
-#if DEBUG
-    NSLog(@"No CHBrowserView hooked up for a newly created window yet.");
-#endif
-    return NS_ERROR_FAILURE;
-  }
-  
-  CHBrowserListener* listener = [childView getCocoaBrowserListener];
-  if (!listener) {
-#if DEBUG
-    NSLog(@"Uh-oh! No listener yet for a newly created window (nsCocoaBrowserlistener)");
-    return NS_ERROR_FAILURE;
-#endif
-  }
-  
-#if DEBUG
-  NSLog(@"Made a chrome window.");
-#endif
-  
-  *_retval = listener;
-  NS_IF_ADDREF(*_retval);
-  return NS_OK;
-}
-
-// Implementation of nsIContextMenuListener
-NS_IMETHODIMP
-CHBrowserListener::OnShowContextMenu(PRUint32 aContextFlags, nsIDOMEvent* aEvent, nsIDOMNode* aNode)
-{
-  [mContainer onShowContextMenu: aContextFlags domEvent: aEvent domNode: aNode];
-  return NS_OK;
-}
-
-// Implementation of nsITooltipListener
-NS_IMETHODIMP
-CHBrowserListener::OnShowTooltip(PRInt32 aXCoords, PRInt32 aYCoords, const PRUnichar *aTipText)
-{
-  NSPoint where;
-  where.x = aXCoords; where.y = aYCoords;
-  [mContainer onShowTooltip:where withText:[NSString stringWithPRUnichars:aTipText]];
-  return NS_OK;
-}
-
-NS_IMETHODIMP
-CHBrowserListener::OnHideTooltip()
-{
-  [mContainer onHideTooltip];
-  return NS_OK;
-}
-
-// Implementation of nsIWebBrowserChrome
-/* void setStatus (in unsigned long statusType, in wstring status); */
-NS_IMETHODIMP 
-CHBrowserListener::SetStatus(PRUint32 statusType, const PRUnichar *status)
-{
-  if (!mContainer) {
-    return NS_ERROR_FAILURE;
-  }
-
-  NSString* str = nsnull;
-  if (status && (*status != PRUnichar(0))) {
-    str = [NSString stringWithPRUnichars:status];
-  }
-
-  [mContainer setStatus:str ofType:(NSStatusType)statusType];
-
-  return NS_OK;
-}
-
-/* attribute nsIWebBrowser webBrowser; */
-NS_IMETHODIMP 
-CHBrowserListener::GetWebBrowser(nsIWebBrowser * *aWebBrowser)
-{
-  NS_ENSURE_ARG_POINTER(aWebBrowser);
-  if (!mView) {
-    return NS_ERROR_FAILURE;
-  }
-  *aWebBrowser = [mView getWebBrowser];
-
-  return NS_OK;
-}
-NS_IMETHODIMP 
-CHBrowserListener::SetWebBrowser(nsIWebBrowser * aWebBrowser)
-{
-  if (!mView) {
-    return NS_ERROR_FAILURE;
-  }
-
-  [mView setWebBrowser:aWebBrowser];
-
-  return NS_OK;
-}
-
-/* attribute unsigned long chromeFlags; */
-NS_IMETHODIMP 
-CHBrowserListener::GetChromeFlags(PRUint32 *aChromeFlags)
-{
-  NS_ENSURE_ARG_POINTER(aChromeFlags);
-  *aChromeFlags = mChromeFlags;
-  return NS_OK;
-}
-NS_IMETHODIMP 
-CHBrowserListener::SetChromeFlags(PRUint32 aChromeFlags)
-{
-  // XXX Do nothing with them for now
-  mChromeFlags = aChromeFlags;
-  return NS_OK;
-}
-
-/* void destroyBrowserWindow (); */
-NS_IMETHODIMP 
-CHBrowserListener::DestroyBrowserWindow()
-{
-  // XXX Could send this up to the container, but for now,
-  // we just destroy the enclosing window.
-  NSWindow* window = [mView window];
-
-  if (window) {
-    [window close];
-  }
-
-  return NS_OK;
-}
-
-/* void sizeBrowserTo (in long aCX, in long aCY); */
-NS_IMETHODIMP 
-CHBrowserListener::SizeBrowserTo(PRInt32 aCX, PRInt32 aCY)
-{
-  if (mContainer) {
-    NSSize size;
-    
-    size.width = (float)aCX;
-    size.height = (float)aCY;
-
-    [mContainer sizeBrowserTo:size];
-  }
-  
-  return NS_OK;
-}
-
-/* void showAsModal (); */
-NS_IMETHODIMP 
-CHBrowserListener::ShowAsModal()
-{
-  if (!mView) {
-    return NS_ERROR_FAILURE;
-  }
-
-  NSWindow* window = [mView window];
-
-  if (!window) {
-    return NS_ERROR_FAILURE;
-  }
-
-  mIsModal = PR_TRUE;
-  //int result = [NSApp runModalForWindow:window];
-  mIsModal = PR_FALSE;
-
-  return NS_OK;
-}
-
-/* boolean isWindowModal (); */
-NS_IMETHODIMP 
-CHBrowserListener::IsWindowModal(PRBool *_retval)
-{
-  NS_ENSURE_ARG_POINTER(_retval);
-
-  *_retval = mIsModal;
-
-  return NS_OK;
-}
-
-/* void exitModalEventLoop (in nsresult aStatus); */
-NS_IMETHODIMP 
-CHBrowserListener::ExitModalEventLoop(nsresult aStatus)
-{
-//  [NSApp stopModalWithCode:(int)aStatus];
-
-  return NS_OK;
-}
-
-// Implementation of nsIEmbeddingSiteWindow2
-NS_IMETHODIMP
-CHBrowserListener::Blur()
-{
-  return NS_OK;
-}
-
-// Implementation of nsIEmbeddingSiteWindow
-/* void setDimensions (in unsigned long flags, in long x, in long y, in long cx, in long cy); */
-NS_IMETHODIMP 
-CHBrowserListener::SetDimensions(PRUint32 flags, PRInt32 x, PRInt32 y, PRInt32 cx, PRInt32 cy)
-{
-  if (!mView)
-    return NS_ERROR_FAILURE;
-
-  NSWindow* window = [mView window];
-  if (!window)
-    return NS_ERROR_FAILURE;
-
-  if (flags & nsIEmbeddingSiteWindow::DIM_FLAGS_POSITION) {
-    NSPoint origin;
-    origin.x = (float)x;
-    origin.y = (float)y;
-    
-    // websites assume the origin is the topleft of the window and that the screen origin
-    // is "topleft" (quickdraw coordinates). As a result, we have to convert it.
-    GDHandle screenDevice = ::GetMainDevice();
-    Rect screenRect = (**screenDevice).gdRect;
-    short screenHeight = screenRect.bottom - screenRect.top;
-    origin.y = screenHeight - origin.y;
-    
-    [window setFrameTopLeftPoint:origin];
-  }
-
-  if (flags & nsIEmbeddingSiteWindow::DIM_FLAGS_SIZE_OUTER) {
-    NSRect frame = [window frame];
-    frame.size.width = (float)cx;
-    frame.size.height = (float)cy;
-    [window setFrame:frame display:YES];
-  }
-  else if (flags & nsIEmbeddingSiteWindow::DIM_FLAGS_SIZE_INNER) {
-    NSSize size;
-    size.width = (float)cx;
-    size.height = (float)cy;
-    [window setContentSize:size];
-  }
-
-  return NS_OK;
-}
-
-/* void getDimensions (in unsigned long flags, out long x, out long y, out long cx, out long cy); */
-NS_IMETHODIMP 
-CHBrowserListener::GetDimensions(PRUint32 flags,  PRInt32 *x,  PRInt32 *y, PRInt32 *cx, PRInt32 *cy)
-{
-  if (!mView)
-    return NS_ERROR_FAILURE;
-
-  NSWindow* window = [mView window];
-  if (!window)
-    return NS_ERROR_FAILURE;
-
-  NSRect frame = [window frame];
-  if (flags & nsIEmbeddingSiteWindow::DIM_FLAGS_POSITION) {
-    if ( x )
-      *x = (PRInt32)frame.origin.x;
-    if ( y )
-      *y = (PRInt32)frame.origin.y;
-  }
-  if (flags & nsIEmbeddingSiteWindow::DIM_FLAGS_SIZE_OUTER) {
-    if ( cx )
-      *cx = (PRInt32)frame.size.width;
-    if ( cy )
-      *cy = (PRInt32)frame.size.height;
-  }
-  else if (flags & nsIEmbeddingSiteWindow::DIM_FLAGS_SIZE_INNER) {
-    NSView* contentView = [window contentView];
-    NSRect contentFrame = [contentView frame];
-    if ( cx )
-      *cx = (PRInt32)contentFrame.size.width;
-    if ( cy )
-      *cy = (PRInt32)contentFrame.size.height;    
-  }
-
-  return NS_OK;
-}
-
-/* void setFocus (); */
-NS_IMETHODIMP 
-CHBrowserListener::SetFocus()
-{
-  if (!mView) {
-    return NS_ERROR_FAILURE;
-  }
-
-  NSWindow* window = [mView window];
-  if (!window) {
-    return NS_ERROR_FAILURE;
-  }
-
-  [window makeKeyAndOrderFront:window];
-
-  return NS_OK;
-}
-
-/* attribute boolean visibility; */
-NS_IMETHODIMP 
-CHBrowserListener::GetVisibility(PRBool *aVisibility)
-{
-  NS_ENSURE_ARG_POINTER(aVisibility);
-
-  if (!mView) {
-    return NS_ERROR_FAILURE;
-  }
-
-  NSWindow* window = [mView window];
-  if (!window) {
-    return NS_ERROR_FAILURE;
-  }
-
-  *aVisibility = [window isMiniaturized];
-
-  return NS_OK;
-}
-NS_IMETHODIMP 
-CHBrowserListener::SetVisibility(PRBool aVisibility)
-{
-  if (!mView) {
-    return NS_ERROR_FAILURE;
-  }
-
-  NSWindow* window = [mView window];
-  if (!window) {
-    return NS_ERROR_FAILURE;
-  }
-
-  if (aVisibility) {
-    [window deminiaturize:window];
-  }
-  else {
-    [window miniaturize:window];
-  }
-
-  return NS_OK;
-}
-
-/* attribute wstring title; */
-NS_IMETHODIMP 
-CHBrowserListener::GetTitle(PRUnichar * *aTitle)
-{
-  NS_ENSURE_ARG_POINTER(aTitle);
-
-  if (!mContainer) {
-    return NS_ERROR_FAILURE;
-  }
-
-  NSString* title = [mContainer title];
-  unsigned int length = [title length];
-  if (length) {
-    *aTitle = (PRUnichar*)nsMemory::Alloc((length+1)*sizeof(PRUnichar));
-    if (!*aTitle) {
-      return NS_ERROR_OUT_OF_MEMORY;
-    }
-    [title getCharacters:*aTitle];
-  }
-  else {
-    *aTitle = nsnull;
-  }
-  
-  return NS_OK;
-}
-NS_IMETHODIMP 
-CHBrowserListener::SetTitle(const PRUnichar * aTitle)
-{
-  NS_ENSURE_ARG(aTitle);
-
-  if (!mContainer) {
-    return NS_ERROR_FAILURE;
-  }
-
-  NSString* str = [NSString stringWithPRUnichars:aTitle];
-  [mContainer setTitle:str];
-
-  return NS_OK;
-}
-
-/* [noscript] readonly attribute voidPtr siteWindow; */
-NS_IMETHODIMP 
-CHBrowserListener::GetSiteWindow(void * *aSiteWindow)
-{
-  NS_ENSURE_ARG_POINTER(aSiteWindow);
-  *aSiteWindow = nsnull;
-  if (!mView) {
-    return NS_ERROR_FAILURE;
-  }
-
-  NSWindow* window = [mView window];
-  if (!window) {
-    return NS_ERROR_FAILURE;
-  }
-
-  *aSiteWindow = (void*)window;
-
-  return NS_OK;
-}
-
-
-//
-// Implementation of nsIWebProgressListener
-//
-
-/* void onStateChange (in nsIWebProgress aWebProgress, in nsIRequest aRequest, in unsigned long aStateFlags, in unsigned long aStatus); */
-NS_IMETHODIMP 
-CHBrowserListener::OnStateChange(nsIWebProgress *aWebProgress, nsIRequest *aRequest, 
-                                        PRUint32 aStateFlags, PRUint32 aStatus)
-{
-  NSEnumerator* enumerator = [mListeners objectEnumerator];
-  id<CHBrowserListener> obj;
-  
-  if (aStateFlags & nsIWebProgressListener::STATE_IS_NETWORK) {
-    if (aStateFlags & nsIWebProgressListener::STATE_START) {
-      while ((obj = [enumerator nextObject]))
-        [obj onLoadingStarted];
-    }
-    else if (aStateFlags & nsIWebProgressListener::STATE_STOP) {
-      while ((obj = [enumerator nextObject]))
-        [obj onLoadingCompleted:(NS_SUCCEEDED(aStatus))];
-    }
-  }
-
-  return NS_OK;
-}
-
-/* void onProgressChange (in nsIWebProgress aWebProgress, in nsIRequest aRequest, in long aCurSelfProgress, in long aMaxSelfProgress, in long aCurTotalProgress, in long aMaxTotalProgress); */
-NS_IMETHODIMP 
-CHBrowserListener::OnProgressChange(nsIWebProgress *aWebProgress, nsIRequest *aRequest, 
-                                          PRInt32 aCurSelfProgress, PRInt32 aMaxSelfProgress, 
-                                          PRInt32 aCurTotalProgress, PRInt32 aMaxTotalProgress)
-{
-  NSEnumerator* enumerator = [mListeners objectEnumerator];
-  id<CHBrowserListener> obj;
-  while ((obj = [enumerator nextObject]))
-    [obj onProgressChange:aCurTotalProgress outOf:aMaxTotalProgress];
-  
-  return NS_OK;
-}
-
-/* void onLocationChange (in nsIWebProgress aWebProgress, in nsIRequest aRequest, in nsIURI location); */
-NS_IMETHODIMP 
-CHBrowserListener::OnLocationChange(nsIWebProgress *aWebProgress, nsIRequest *aRequest, 
-                                          nsIURI *location)
-{
-  if (!location)
-    return NS_ERROR_FAILURE;
-    
-  nsCAutoString spec;
-  location->GetSpec(spec);
-  NSString* str = [NSString stringWithCString:spec.get()];
-