Merge cvs-trunk-mirror to mozilla-central. No manual conflict resolution was necessary.
authorBenjamin Smedberg <benjamin@smedbergs.us>
Wed, 30 Apr 2008 12:35:19 -0400
changeset 14805 5fd5f0514bfc11d34c7baeecce76e7ac23c216f8
parent 14760 78e482f2d4be1b7560448e20fd385c26339f12c9 (current diff)
parent 14804 9c59e083c903b279e009b145133c179bb8e7de87 (diff)
child 14817 ecaa377001c24379ec6c4c5b010c06ba06429d11
push idunknown
push userunknown
push dateunknown
milestone2.0a1pre
Merge cvs-trunk-mirror to mozilla-central. No manual conflict resolution was necessary.
browser/themes/winstripe/browser/places/pageStarred-aero.png
browser/themes/winstripe/browser/places/pageStarred.png
browser/themes/winstripe/browser/places/starPage-aero.png
browser/themes/winstripe/browser/places/starPage.png
config/rules.mk
configure.in
js/src/jsdbgapi.cpp
js/src/jsfun.cpp
js/src/jsinterp.cpp
js/src/jsopcode.cpp
toolkit/themes/winstripe/global/dirListing/local-aero.png
uriloader/exthandler/tests/unit/test_handlerService.js
--- a/accessible/src/base/nsAccessibilityAtomList.h
+++ b/accessible/src/base/nsAccessibilityAtomList.h
@@ -226,17 +226,17 @@ ACCESSIBILITY_ATOM(aria_valuemax, "aria-
 ACCESSIBILITY_ATOM(aria_valuetext, "aria-valuetext")
 
   // misc atoms
 // a form property used to obtain the default label
 // of an HTML button from the button frame
 ACCESSIBILITY_ATOM(defaultLabel, "defaultLabel")
 
 // Object attributes
-ACCESSIBILITY_ATOM(cellIndex, "cell-index")
+ACCESSIBILITY_ATOM(tableCellIndex, "table-cell-index")
 ACCESSIBILITY_ATOM(containerAtomic, "container-atomic")
 ACCESSIBILITY_ATOM(containerBusy, "container-busy")
 ACCESSIBILITY_ATOM(containerChannel, "container-channel")
 ACCESSIBILITY_ATOM(containerLive, "container-live")
 ACCESSIBILITY_ATOM(containerRelevant, "container-relevant")
 ACCESSIBILITY_ATOM(level, "level")
 ACCESSIBILITY_ATOM(lineNumber, "line-number")
 ACCESSIBILITY_ATOM(posinset, "posinset") 
--- a/accessible/src/html/nsHTMLTableAccessible.cpp
+++ b/accessible/src/html/nsHTMLTableAccessible.cpp
@@ -119,17 +119,17 @@ nsHTMLTableCellAccessible::GetAttributes
         return NS_OK;
 
       PRInt32 idx = -1;
       rv = tableAcc->GetIndexAt(rowIdx, cellIdx, &idx);
       NS_ENSURE_SUCCESS(rv, rv);
 
       nsAutoString stringIdx;
       stringIdx.AppendInt(idx);
-      nsAccUtils::SetAccAttr(aAttributes, nsAccessibilityAtoms::cellIndex,
+      nsAccUtils::SetAccAttr(aAttributes, nsAccessibilityAtoms::tableCellIndex,
                              stringIdx);
       return NS_OK;
     }
 
     parentAcc.swap(childAcc);
     rv = childAcc->GetParent(getter_AddRefs(parentAcc));
     NS_ENSURE_SUCCESS(rv, rv);
   }
--- a/accessible/tests/mochitest/test_table_indexes.html
+++ b/accessible/tests/mochitest/test_table_indexes.html
@@ -84,17 +84,17 @@ https://bugzilla.mozilla.org/show_bug.cg
           cellAcc = tableAcc.cellRefAt(row, column);
         } catch (e) { }
 
         ok(cellAcc,
            aId + ": Can't get cell accessible at row = " + row + ", column = " + column);
 
         if (cellAcc) {
           var attrs = cellAcc.attributes;
-          is (parseInt(attrs.getStringProperty("cell-index")), index,
+          is (parseInt(attrs.getStringProperty("table-cell-index")), index,
               aId + ": cell index from object attributes of cell accessible isn't corrent.");
         }
       }
     }
 
     SimpleTest.waitForExplicitFinish();
     addLoadEvent(doTest);
   </script>
--- a/browser/app/Makefile.in
+++ b/browser/app/Makefile.in
@@ -71,16 +71,19 @@ GRE_MILESTONE = $(shell $(PYTHON) $(tops
 GRE_BUILDID = $(shell $(PYTHON) $(topsrcdir)/config/printconfigsetting.py $(LIBXUL_DIST)/bin/platform.ini Build BuildID)
 
 DEFINES += -DGRE_MILESTONE=$(GRE_MILESTONE) -DGRE_BUILDID=$(GRE_BUILDID)
 
 ifdef MOZ_MEMORY
 ifeq ($(OS_ARCH),Darwin)
 LIBS += -ljemalloc
 endif
+ifeq ($(OS_ARCH),SunOS)
+SOLARIS_JEMALLOC_LDFLAGS = -L$(LIBXUL_DIST)/bin -lxul
+endif
 endif
 
 ifdef LIBXUL_SDK
 include $(topsrcdir)/config/rules.mk
 else
 # Build a binary bootstrapping with XRE_main
 
 ifeq ($(USE_SHORT_LIBNAME), 1)
--- a/browser/base/content/overrides/app-license.html
+++ b/browser/base/content/overrides/app-license.html
@@ -1,5 +1,5 @@
     <p>Official <b>binaries</b> of this product released by the 
     <a href="http://www.mozilla.com/">Mozilla Corporation</a> 
     are made available under 
     <a href="http://www.mozilla.org/foundation/EULA/">the corresponding 
-    EULA</a>.
+    EULA</a>.</p>
--- a/browser/base/content/test/Makefile.in
+++ b/browser/base/content/test/Makefile.in
@@ -55,16 +55,21 @@ include $(topsrcdir)/config/rules.mk
                  browser_bug409481.js \
                  browser_autodiscovery.js \
                  browser_bug420160.js \
                  autodiscovery.html \
                  moz.png \
                  browser_getshortcutoruri.js \
     $(NULL)
 
+ifneq (,$(filter mac cocoa,$(MOZ_WIDGET_TOOLKIT)))
+_BROWSER_FILES += browser_customize.js \
+    $(NULL)
+endif
+
 # disable tests on linux for now..
 ifneq ($(OS_ARCH),Linux)
 _BROWSER_FILES += \
                  browser_bug427559.js \
     $(NULL)
 endif
 
 libs:: $(_TEST_FILES)
new file mode 100644
--- /dev/null
+++ b/browser/base/content/test/browser_customize.js
@@ -0,0 +1,38 @@
+function test()
+{
+  waitForExplicitFinish();
+  var panel = document.getElementById("customizeToolbarSheetPopup");
+  panel.addEventListener("popupshown", testCustomizePopupShown, false);
+  document.getElementById("cmd_CustomizeToolbars").doCommand();
+}
+
+function testCustomizePopupShown()
+{
+  var panel = document.getElementById("customizeToolbarSheetPopup");
+  panel.removeEventListener("popupshown", testCustomizePopupShown, false);
+  panel.addEventListener("popuphidden", testCustomizePopupHidden, false);
+
+  var frame = document.getElementById("customizeToolbarSheetIFrame").contentDocument;
+  frame.addEventListener("load", testCustomizeFrameLoaded, true);
+}
+
+function testCustomizeFrameLoaded()
+{
+  var frame = document.getElementById("customizeToolbarSheetIFrame");
+  frame.removeEventListener("load", testCustomizeFrameLoaded, true);
+
+  var menu = document.getElementById("bookmarksMenuPopup");
+  ok("getResult" in menu, "menu has binding");
+
+  var framedoc = document.getElementById("customizeToolbarSheetIFrame").contentDocument;
+  var b = framedoc.getElementById("donebutton");
+
+  framedoc.getElementById("donebutton").doCommand();
+}
+  
+function testCustomizePopupHidden()
+{
+  var panel = document.getElementById("customizeToolbarSheetPopup");
+  panel.removeEventListener("popuphidden", testCustomizePopupHidden, false);
+  finish();
+}
--- a/browser/components/places/content/bookmarkProperties.js
+++ b/browser/components/places/content/bookmarkProperties.js
@@ -466,18 +466,17 @@ var BookmarkPropertiesPanel = {
       hiddenRows.indexOf("title") != -1;
     this._element("locationRow").hidden =
       hiddenRows.indexOf("location") != -1 || isQuery || !isBookmark;
     this._element("keywordRow").hidden =
       hiddenRows.indexOf("location") != -1 || isQuery || !isBookmark;
     this._element("descriptionRow").hidden =
       hiddenRows.indexOf("description")!= -1
     this._element("folderRow").hidden =
-      hiddenRows.indexOf("folder picker") != -1 || isQuery ||
-      isLivemark || this._action == ACTION_EDIT;
+      hiddenRows.indexOf("folder picker") != -1 || this._action == ACTION_EDIT;
     this._element("livemarkFeedLocationRow").hidden =
       hiddenRows.indexOf("feedURI") != -1 || !isLivemark;
     this._element("livemarkSiteLocationRow").hidden =
       hiddenRows.indexOf("siteURI") != -1 || !isLivemark;
     this._element("loadInSidebarCheckbox").hidden =
       hiddenRows.indexOf("loadInSidebar") != -1 || isQuery || !isBookmark;
   },
 
--- a/browser/components/places/content/controller.js
+++ b/browser/components/places/content/controller.js
@@ -1453,17 +1453,17 @@ var PlacesControllerDragHelper = {
 
       // if dragging over a tag container we should tag the item
       if (insertionPoint.isTag) {
         var uri = PlacesUtils._uri(unwrapped.uri);
         var tagItemId = insertionPoint.itemId;
         transactions.push(PlacesUIUtils.ptm.tagURI(uri,[tagItemId]));
       }
       else {
-        if (!this.canMoveContainer(unwrapped.id, null))
+        if (unwrapped.id && !this.canMoveContainer(unwrapped.id, null))
           copy = true;
         else if (unwrapped.concreteId &&
                  !this.canMoveContainer(unwrapped.concreteId, null))
           copy = true;
 
         transactions.push(PlacesUIUtils.makeTransaction(unwrapped,
                           flavor.value, insertionPoint.itemId,
                           index, copy));
--- a/browser/components/places/content/places.js
+++ b/browser/components/places/content/places.js
@@ -210,22 +210,22 @@ var PlacesOrganizer = {
     // Items are only excluded on the left pane
     var options = node.queryOptions.clone();
     options.excludeItems = false;
     var placeURI = PlacesUtils.history.queriesToQueryString(queries, queries.length, options);
 
     // Update the right-pane contents.
     // We must update also if the user clears the search box, in that case
     // we are called with resetSearchBox == false.
-    if (this._content.place != placeURI || !resetSearchBox)
+    if (this._content.place != placeURI || !resetSearchBox) {
       this._content.place = placeURI;
 
-    // This just updates the back/forward buttons, it doesn't call us back
-    // because node.uri is our current selection.
-    this.location = node.uri;
+      // Update the back/forward buttons.
+      this.location = node.uri;
+    }
 
     // Make sure the search UI is hidden.
     PlacesSearchBox.hideSearchUI();
     if (resetSearchBox) {
       var searchFilter = document.getElementById("searchFilter");
       searchFilter.reset();
     }
 
--- a/browser/themes/pinstripe/browser/browser.css
+++ b/browser/themes/pinstripe/browser/browser.css
@@ -479,16 +479,27 @@ toolbar[mode="icons"] #back-forward-drop
   -moz-image-region: rect(66px, 582px, 99px, 566px);
 }
 
 #back-forward-dropmarker[chromedir="rtl"]:hover:active:not([disabled]),
 #back-forward-dropmarker[open="true"][chromedir="rtl"] {
   -moz-image-region: rect(66px, 519px, 99px, 504px);
 }
 
+.unified-nav-back[_moz-menuactive],
+menupopup[chromedir="rtl"] > .unified-nav-forward[_moz-menuactive] {
+  list-style-image: url("chrome://browser/skin/menu-back.png") !important;
+}
+
+.unified-nav-forward[_moz-menuactive],
+menupopup[chromedir="rtl"] > .unified-nav-back[_moz-menuactive] {
+  list-style-image: url("chrome://browser/skin/menu-forward.png") !important;
+}
+
+
 /* ----- SMALL BACK BUTTON, PAIRED----- */	
 
 toolbar[mode="icons"][iconsize="small"] #unified-back-forward-button > #back-button {
   -moz-image-region: rect(0px, 616px, 23px, 582px);
   -moz-margin-end: 0;
   -moz-padding-end: 0;
   border-left: none;
   border-right: none;
--- a/browser/themes/pinstripe/browser/jar.mn
+++ b/browser/themes/pinstripe/browser/jar.mn
@@ -23,16 +23,18 @@ classic.jar:
   skin/classic/browser/hud-style-expander-open.png
   skin/classic/browser/hud-style-new-folder-bar-background-active.png
   skin/classic/browser/hud-style-new-folder-bar-background.gif
   skin/classic/browser/hud-style-new-folder-bar-background.png
   skin/classic/browser/hud-style-new-folder-plus-sign.png
   skin/classic/browser/hud-style-twisties.png
   skin/classic/browser/identity.png
   skin/classic/browser/Info.png
+  skin/classic/browser/menu-back.png
+  skin/classic/browser/menu-forward.png
   skin/classic/browser/page-livemarks.png
   skin/classic/browser/livemark-item.png
   skin/classic/browser/pageInfo.css
   skin/classic/browser/pageInfo.png
   skin/classic/browser/Popup-blocked.png
   skin/classic/browser/searchbar.css
   skin/classic/browser/Search.png
   skin/classic/browser/Search-addengines.png
new file mode 100644
index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..82a74c7b811e16f90329edaafdf220d9cb138330
GIT binary patch
literal 231
zc%17D@N?(olHy`uVBq!ia0vp^0wB!61|;P_|4#%`Ea{HEjtmUfZd~z?Faq)=OI#yL
zg7ec#$`gxH85~pclTsBta}(23gHjVyDhp4h+5i<*db&7<RNPAX^Z&m+vuZ<Uqm#pl
zhO#ELhCL0e#>^kj{1-UTz@IFf!u&||zhHw3vqfXY_4*KpEsRbMHE--cG8}G*{qM;v
z!FGc2W3CquLt>zUooAlJ0Rw)4{N+a&B0}_(jxmVIynHP#aGddDwiD;X!VBqYO$-VL
Z7~~XRym%~Amkx9UgQu&X%Q~loCIC8lO{D+;
new file mode 100644
index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..b3b40e394dbfa412189a8a452c73f72d227fc4a4
GIT binary patch
literal 213
zc%17D@N?(olHy`uVBq!ia0vp^0wB!61|;P_|4#%`Ea{HEjtmUfZd~z?Faq)=OI#yL
zg7ec#$`gxH85~pclTsBta}(23gHjVyDhp4h+5i=$d%8G=RNPAX^Z&m+vuZ<Uqmx4q
z<J*c<$2f%s#{@M2<K)Te*BAsM7?0#kkzioj-7rIVI^&V1WCtCWPDX?26LJsaDoj&0
z=ka6OsIjwghipgXiQZP%8;d4HFjsv%Y0TGorbV2AMS@{>q&V+uEfp1@l?<M)elF{r
G5}E)FzC>XF
--- a/browser/themes/winstripe/browser/browser-aero.css
+++ b/browser/themes/winstripe/browser/browser-aero.css
@@ -40,19 +40,19 @@
 }
 #identity-box.verifiedIdentity[chromedir="ltr"]:-moz-system-metric(windows-default-theme) > hbox {
   background-position: 0 -237px;
 }
 #identity-box.verifiedIdentity:hover[chromedir="ltr"]:-moz-system-metric(windows-default-theme) > hbox {
   background-position: 0 -297px;
 }
 
-/* Bug 413060, comment 14: Match #identity-box's -moz-margin-start, less 1px */
+/* Match #identity-box[chromedir="ltr"]'s -moz-margin-start */
 #identity-popup[chromedir="ltr"]:-moz-system-metric(windows-default-theme) {
-  -moz-margin-start: 5px;
+  -moz-margin-start: 6px;
 }
 
 /* Bug 413060, comment 16: Vista Aero is a special case where we use a
    tooltip appearance for the address bar popup panels */
 #identity-popup:-moz-system-metric(windows-default-theme),
 #editBookmarkPanel:-moz-system-metric(windows-default-theme) {
   -moz-appearance: tooltip;
   color: InfoText;
--- a/browser/themes/winstripe/browser/browser.css
+++ b/browser/themes/winstripe/browser/browser.css
@@ -1149,17 +1149,18 @@ statusbarpanel#statusbar-display {
 /* ::::: autocomplete ::::: */
 
 #treecolAutoCompleteImage {
   max-width: 36px;
 }
 
 .ac-result-type-bookmark,
 .autocomplete-treebody::-moz-tree-image(bookmark, treecolAutoCompleteImage) {
-  list-style-image: url("chrome://browser/skin/places/pageStarred.png");
+  list-style-image: url("chrome://browser/skin/places/editBookmark.png");
+  -moz-image-region: rect(0px 16px 16px 0px);
   width: 16px; 
   height: 16px;
 }
 
 .ac-result-type-tag,
 .autocomplete-treebody::-moz-tree-image(tag, treecolAutoCompleteImage) {
   list-style-image: url("chrome://browser/skin/places/tag.png");
   width: 16px; 
@@ -1199,37 +1200,46 @@ statusbarpanel#statusbar-display {
 
 .autocomplete-treebody::-moz-tree-cell(suggesthint) {
   border-top: 1px solid GrayText;
 }
 
 /* ::::: go button ::::: */
 
 #go-button {
-  padding: 3px 2px 2px 2px;
+  padding: 0 2px;
   list-style-image: url("chrome://browser/skin/Go-arrow.png");
   -moz-image-region: rect(0px 16px 16px 0px);
 }
 
 #go-button[chromedir="rtl"] {
   list-style-image: url("chrome://browser/skin/Go-arrow-rtl.png");
 }
 
 #go-button:hover {
   -moz-image-region: rect(16px 16px 32px 0px);
 }
 
 /* star button */
 #star-button {
-  padding: 1px;
-  list-style-image: url("chrome://browser/skin/places/starPage.png");
+  padding: 0 2px;
+  list-style-image: url("chrome://browser/skin/places/bookmark.png");
+  -moz-image-region: rect(0px 16px 16px 0px);
+}
+
+#star-button:hover {
+  -moz-image-region: rect(0px 32px 16px 16px);
+}
+
+#star-button:hover:active {
+  -moz-image-region: rect(0px 48px 16px 32px);
 }
 
 #star-button[starred="true"] {
-  list-style-image: url("chrome://browser/skin/places/pageStarred.png");
+  list-style-image: url("chrome://browser/skin/places/editBookmark.png");
 }
 
 /* bookmarking panel */
 #editBookmarkPanel {
   -moz-appearance: menupopup;
   color: MenuText;
   padding: 4px;
 }
@@ -1710,21 +1720,35 @@ toolbar[mode="text"] > #window-controls 
 #feed-button > hbox > .button-text {
   display: none;
 }
 
 #feed-button {
   -moz-binding: url("chrome://global/content/bindings/button.xml#menu");
   -moz-appearance: none; 
   min-width: 0px; 
-  margin-right: 1px !important;
+  padding: 0 2px !important;
 }
 
 #feed-button[feeds] {
-  list-style-image: url("chrome://browser/skin/feeds/feedIcon16.png");
+  list-style-image: url("chrome://browser/skin/feeds/feed-icons-16.png");
+  -moz-image-region: rect(0px 16px 16px 0px);
+}
+
+#feed-button[feeds]:hover {
+  -moz-image-region: rect(0px 32px 16px 16px);
+}
+
+#feed-button[feeds][open="true"],
+#feed-button[feeds]:hover:active {
+  -moz-image-region: rect(0px 48px 16px 32px);
+}
+
+#feed-button:not([feeds]) {
+  visibility: collapse;
 }
 
 /* ::::: About Popup Blocking dialog ::::: */
 #pageReportFirstTime statusbarpanel.statusbar-resizerpanel {
   visibility: collapse;
 }
 
 #checkForUpdates[loading="true"] {
@@ -1961,17 +1985,16 @@ toolbarbutton.bookmark-item[dragover="tr
 
 #identity-popup-more-info-button {
   margin-top: 6px;
   -moz-margin-end: 1px;
 }
 
 /* Popup Bounding Box */
 #identity-popup {
-  margin-top: 1px;
   -moz-appearance: menupopup;
   color: MenuText;
 }
 
 /* Bug 413060, comment 14: Match #identity-box's -moz-margin-start, less 1px */
 #identity-popup[chromedir="ltr"]:-moz-system-metric(windows-default-theme) {
   -moz-margin-start: 3px;
 }
--- a/browser/themes/winstripe/browser/jar.mn
+++ b/browser/themes/winstripe/browser/jar.mn
@@ -50,18 +50,16 @@ classic.jar:
         skin/classic/browser/places/query.png                        (places/query.png)
         skin/classic/browser/places/bookmarksMenu.png                (places/bookmarksMenu.png)
         skin/classic/browser/places/bookmarksToolbar.png             (places/bookmarksToolbar.png)
         skin/classic/browser/places/calendar.png                     (places/calendar.png)
         skin/classic/browser/places/toolbarDropMarker.png            (places/toolbarDropMarker.png)
         skin/classic/browser/places/editBookmarkOverlay.css          (places/editBookmarkOverlay.css)
         skin/classic/browser/places/libraryNavigation.png            (places/libraryNavigation.png)
         skin/classic/browser/places/libraryToolbar.png               (places/libraryToolbar.png)
-        skin/classic/browser/places/starPage.png                     (places/starPage.png)
-        skin/classic/browser/places/pageStarred.png                  (places/pageStarred.png)
         skin/classic/browser/places/starred48.png                    (places/starred48.png)
         skin/classic/browser/places/unstarred48.png                  (places/unstarred48.png)
         skin/classic/browser/places/tag.png                          (places/tag.png)
         skin/classic/browser/places/history.png                      (places/history.png)
         skin/classic/browser/places/allBookmarks.png                 (places/allBookmarks.png)
         skin/classic/browser/places/unsortedBookmarks.png            (places/unsortedBookmarks.png)
         skin/classic/browser/places/importAndBackup.png              (places/importAndBackup.png)
         skin/classic/browser/places/organize.png                     (places/organize.png)
@@ -140,18 +138,16 @@ classic.jar:
         skin/classic/aero/browser/places/bookmarksMenu.png           (places/bookmarksMenu-aero.png)
         skin/classic/aero/browser/places/bookmarksToolbar.png        (places/bookmarksToolbar-aero.png)
         skin/classic/aero/browser/places/calendar.png                (places/calendar-aero.png)
         skin/classic/aero/browser/places/dropDown.png                (places/dropDown-aero.png)
         skin/classic/aero/browser/places/toolbarDropMarker.png       (places/toolbarDropMarker-aero.png)
         skin/classic/aero/browser/places/editBookmarkOverlay.css     (places/editBookmarkOverlay.css)
         skin/classic/aero/browser/places/libraryNavigation.png       (places/libraryNavigation-aero.png)
         skin/classic/aero/browser/places/libraryToolbar.png          (places/libraryToolbar-aero.png)
-        skin/classic/aero/browser/places/starPage.png                (places/starPage-aero.png)
-        skin/classic/aero/browser/places/pageStarred.png             (places/pageStarred-aero.png)
         skin/classic/aero/browser/places/starred48.png               (places/starred48-aero.png)
         skin/classic/aero/browser/places/unstarred48.png             (places/unstarred48.png)
         skin/classic/aero/browser/places/tag.png                     (places/tag-aero.png)
         skin/classic/aero/browser/places/history.png                 (places/history-aero.png)
         skin/classic/aero/browser/places/allBookmarks.png            (places/allBookmarks-aero.png)
         skin/classic/aero/browser/places/unsortedBookmarks.png       (places/unsortedBookmarks-aero.png)
         skin/classic/aero/browser/places/importAndBackup.png         (places/importAndBackup-aero.png)
         skin/classic/aero/browser/places/view.png                    (places/view-aero.png)
deleted file mode 100644
index efc863368c335baddeb3a85521dd2eb25c46e62f..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
GIT binary patch
literal 0
Hc$@<O00001
deleted file mode 100644
index 90e7bb72e2c3fba5e5545b9a13a73648729309d1..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
GIT binary patch
literal 0
Hc$@<O00001
deleted file mode 100644
index f7732541510bba79a92307a7f008c751e7cdf0bf..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
GIT binary patch
literal 0
Hc$@<O00001
deleted file mode 100644
index 744a0780b83c9cc4d43f8a4ae7c016bd1d86bc5e..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
GIT binary patch
literal 0
Hc$@<O00001
--- a/config/rules.mk
+++ b/config/rules.mk
@@ -867,19 +867,19 @@ ifdef MSMANIFEST_TOOL
 		else \
 			mt.exe -NOLOGO -MANIFEST $@.manifest -OUTPUTRESOURCE:$@\;1; \
 		fi; \
 		rm -f $@.manifest; \
 	fi
 endif	# MSVC with manifest tool
 else
 ifeq ($(CPP_PROG_LINK),1)
-	$(CCC) -o $@ $(CXXFLAGS) $(WRAP_MALLOC_CFLAGS) $(PROGOBJS) $(RESFILE) $(WIN32_EXE_LDFLAGS) $(LDFLAGS) $(LIBS_DIR) $(LIBS) $(OS_LIBS) $(EXTRA_LIBS) $(BIN_FLAGS) $(WRAP_MALLOC_LIB) $(PROFILER_LIBS) $(EXE_DEF_FILE)
+	$(CCC) -o $@ $(CXXFLAGS) $(WRAP_MALLOC_CFLAGS) $(PROGOBJS) $(RESFILE) $(WIN32_EXE_LDFLAGS) $(SOLARIS_JEMALLOC_LDFLAGS) $(LDFLAGS) $(LIBS_DIR) $(LIBS) $(OS_LIBS) $(EXTRA_LIBS) $(BIN_FLAGS) $(WRAP_MALLOC_LIB) $(PROFILER_LIBS) $(EXE_DEF_FILE)
 else # ! CPP_PROG_LINK
-	$(CC) -o $@ $(CFLAGS) $(PROGOBJS) $(RESFILE) $(WIN32_EXE_LDFLAGS) $(LDFLAGS) $(LIBS_DIR) $(LIBS) $(OS_LIBS) $(EXTRA_LIBS) $(BIN_FLAGS) $(EXE_DEF_FILE)
+	$(CC) -o $@ $(CFLAGS) $(PROGOBJS) $(RESFILE) $(WIN32_EXE_LDFLAGS) $(SOLARIS_JEMALLOC_LDFLAGS) $(LDFLAGS) $(LIBS_DIR) $(LIBS) $(OS_LIBS) $(EXTRA_LIBS) $(BIN_FLAGS) $(EXE_DEF_FILE)
 endif # CPP_PROG_LINK
 endif # WINNT && !GNU_CC
 endif # OS2
 endif # WINCE
 
 ifdef ENABLE_STRIP
 	$(STRIP) $@
 endif
@@ -938,19 +938,19 @@ ifeq (_WINNT,$(GNU_CC)_$(OS_ARCH))
 ifdef MSMANIFEST_TOOL
 	@if test -f $@.manifest; then \
 		mt.exe -NOLOGO -MANIFEST $@.manifest -OUTPUTRESOURCE:$@\;1; \
 		rm -f $@.manifest; \
 	fi
 endif	# MSVC with manifest tool
 else
 ifeq ($(CPP_PROG_LINK),1)
-	$(CCC) $(WRAP_MALLOC_CFLAGS) $(CXXFLAGS) -o $@ $< $(WIN32_EXE_LDFLAGS) $(LDFLAGS) $(LIBS_DIR) $(LIBS) $(OS_LIBS) $(EXTRA_LIBS) $(WRAP_MALLOC_LIB) $(PROFILER_LIBS) $(BIN_FLAGS)
+	$(CCC) $(WRAP_MALLOC_CFLAGS) $(CXXFLAGS) -o $@ $< $(WIN32_EXE_LDFLAGS) $(SOLARIS_JEMALLOC_LDFLAGS) $(LDFLAGS) $(LIBS_DIR) $(LIBS) $(OS_LIBS) $(EXTRA_LIBS) $(WRAP_MALLOC_LIB) $(PROFILER_LIBS) $(BIN_FLAGS)
 else
-	$(CC) $(WRAP_MALLOC_CFLAGS) $(CFLAGS) $(OUTOPTION)$@ $< $(WIN32_EXE_LDFLAGS) $(LDFLAGS) $(LIBS_DIR) $(LIBS) $(OS_LIBS) $(EXTRA_LIBS) $(WRAP_MALLOC_LIB) $(PROFILER_LIBS) $(BIN_FLAGS)
+	$(CC) $(WRAP_MALLOC_CFLAGS) $(CFLAGS) $(OUTOPTION)$@ $< $(WIN32_EXE_LDFLAGS) $(SOLARIS_JEMALLOC_LDFLAGS) $(LDFLAGS) $(LIBS_DIR) $(LIBS) $(OS_LIBS) $(EXTRA_LIBS) $(WRAP_MALLOC_LIB) $(PROFILER_LIBS) $(BIN_FLAGS)
 endif # CPP_PROG_LINK
 endif # WINNT && !GNU_CC
 endif # OS/2 VACPP
 endif # WINCE
 
 ifdef ENABLE_STRIP
 	$(STRIP) $@
 endif
--- a/configure.in
+++ b/configure.in
@@ -1443,22 +1443,23 @@ if test "$result" = "yes"; then
     AC_DEFINE(HAVE_64BIT_OS)
     HAVE_64BIT_OS=1
 fi
 AC_SUBST(HAVE_64BIT_OS)
 AC_LANG_RESTORE
 fi # COMPILE_ENVIRONMENT
 
 dnl ========================================================
-dnl Enable high-memory support on OS/2, disabled by default
-dnl ========================================================
-MOZ_ARG_ENABLE_BOOL(os2-high-mem,
-[  --enable-os2-high-mem Enable high-memory support on OS/2],
-    MOZ_OS2_HIGH_MEMORY=1,
-    MOZ_OS2_HIGH_MEMORY= )
+dnl Enable high-memory support on OS/2 by default.
+dnl ========================================================
+MOZ_OS2_HIGH_MEMORY=1
+MOZ_ARG_DISABLE_BOOL(os2-high-mem,
+[  --disable-os2-high-mem  Disable high-memory support on OS/2],
+    MOZ_OS2_HIGH_MEMORY=,
+    MOZ_OS2_HIGH_MEMORY=1 )
 AC_SUBST(MOZ_OS2_HIGH_MEMORY)
 
 dnl ========================================================
 dnl System overrides of the defaults for host
 dnl ========================================================
 case "$host" in
 *-beos*)
     HOST_CFLAGS="$HOST_CFLAGS -DXP_BEOS -DBeOS -DBEOS -D_POSIX_SOURCE -DNO_X11"
@@ -2397,16 +2398,17 @@ alpha*-*-osf*)
 dnl the qsort routine under solaris is faulty
 *-solaris*) 
     AC_DEFINE(SOLARIS)
     TARGET_NSPR_MDCPUCFG='\"md/_solaris.cfg\"'
     SYSTEM_MAKEDEPEND=
     # $ORIGIN/.. is for shared libraries under components/ to locate shared
     # libraries one level up (e.g. libnspr4.so)
     LDFLAGS="$LDFLAGS -z ignore -R '\$\$ORIGIN:\$\$ORIGIN/..'"
+    MOZ_MEMORY=1
     if test -z "$GNU_CC"; then
        NS_USE_NATIVE=1
        MOZ_FIX_LINK_PATHS='-R $(LIBXUL_DIST)/bin'
        AC_DEFINE(NSCAP_DISABLE_DEBUG_PTR_TYPES)
 
        if test "$CPU_ARCH" != "sparc"; then
           CFLAGS="$CFLAGS -xstrconst -xbuiltin=%all"
           CXXFLAGS="$CXXFLAGS -xbuiltin=%all -features=tmplife -norunpath"
--- a/content/canvas/public/nsICanvasElement.h
+++ b/content/canvas/public/nsICanvasElement.h
@@ -45,18 +45,16 @@ class gfxContext;
 class nsIFrame;
 
 // {C234660C-BD06-493e-8583-939A5A158B37}
 #define NS_ICANVASELEMENT_IID \
     { 0xc234660c, 0xbd06, 0x493e, { 0x85, 0x83, 0x93, 0x9a, 0x5a, 0x15, 0x8b, 0x37 } }
 
 class nsIRenderingContext;
 
-class nsICanvasRenderingContextInternal;
-
 struct _cairo_surface;
 
 class nsICanvasElement : public nsISupports {
 public:
   NS_DECLARE_STATIC_IID_ACCESSOR(NS_ICANVASELEMENT_IID)
 
   /**
    * Ask the canvas Element to return the primary frame, if any
@@ -89,20 +87,13 @@ public:
    */
   NS_IMETHOD InvalidateFrame () = 0;
 
   /*
    * Ask the canvas frame to invalidate a portion of the frame; damageRect
    * is relative to the origin of the canvas frame.
    */
   NS_IMETHOD InvalidateFrameSubrect (const nsRect& damageRect) = 0;
-
-  /*
-   * Get the number of contexts in this canvas, and request a context at
-   * an index.
-   */
-  virtual PRInt32 CountContexts () = 0;
-  virtual nsICanvasRenderingContextInternal *GetContextAtIndex (PRInt32 index) = 0;
 };
 
 NS_DEFINE_STATIC_IID_ACCESSOR(nsICanvasElement, NS_ICANVASELEMENT_IID)
 
 #endif /* nsICanvasElement_h___ */
--- a/content/canvas/public/nsICanvasRenderingContextInternal.h
+++ b/content/canvas/public/nsICanvasRenderingContextInternal.h
@@ -42,17 +42,16 @@
 #include "nsICanvasElement.h"
 #include "nsIInputStream.h"
 
 // {eab854fd-aa5e-44bb-8cc5-8d02f84b0216}
 #define NS_ICANVASRENDERINGCONTEXTINTERNAL_IID \
   { 0xeab854fd, 0xaa5e, 0x44bb, { 0x8c, 0xc5, 0x8d, 0x02, 0xf8, 0x4b, 0x02, 0x16 } }
 
 class gfxContext;
-class gfxASurface;
 
 class nsICanvasRenderingContextInternal : public nsISupports {
 public:
   NS_DECLARE_STATIC_IID_ACCESSOR(NS_ICANVASRENDERINGCONTEXTINTERNAL_IID)
 
   // This method should NOT hold a ref to aParentCanvas; it will be called
   // with nsnull when the element is going away.
   NS_IMETHOD SetCanvasElement(nsICanvasElement* aParentCanvas) = 0;
@@ -68,18 +67,14 @@ public:
   // The format is given in aMimeTime, for example "image/png".
   //
   // If the image format does not support transparency or aIncludeTransparency
   // is false, alpha will be discarded and the result will be the image
   // composited on black.
   NS_IMETHOD GetInputStream(const char *aMimeType,
                             const PRUnichar *aEncoderOptions,
                             nsIInputStream **aStream) = 0;
-
-  // If this canvas context can be represented with a simple Thebes surface,
-  // return the surface.  Otherwise returns an error.
-  NS_IMETHOD GetThebesSurface(gfxASurface **surface) = 0;
 };
 
 NS_DEFINE_STATIC_IID_ACCESSOR(nsICanvasRenderingContextInternal,
                               NS_ICANVASRENDERINGCONTEXTINTERNAL_IID)
 
 #endif /* nsICanvasRenderingContextInternal_h___ */
--- a/content/canvas/src/nsCanvasRenderingContext2D.cpp
+++ b/content/canvas/src/nsCanvasRenderingContext2D.cpp
@@ -290,17 +290,16 @@ public:
 
     // nsICanvasRenderingContextInternal
     NS_IMETHOD SetCanvasElement(nsICanvasElement* aParentCanvas);
     NS_IMETHOD SetDimensions(PRInt32 width, PRInt32 height);
     NS_IMETHOD Render(gfxContext *ctx);
     NS_IMETHOD GetInputStream(const char* aMimeType,
                               const PRUnichar* aEncoderOptions,
                               nsIInputStream **aStream);
-    NS_IMETHOD GetThebesSurface(gfxASurface **surface);
 
     // nsISupports interface
     NS_DECL_ISUPPORTS
 
     // nsIDOMCanvasRenderingContext2D interface
     NS_DECL_NSIDOMCANVASRENDERINGCONTEXT2D
 
 protected:
@@ -407,18 +406,18 @@ protected:
                                        jsval aValue);
     static PRBool ConvertJSValToXPCObject(nsISupports** aSupports, REFNSIID aIID,
                                           JSContext* aContext, jsval aValue);
     static PRBool ConvertJSValToDouble(double* aProp, JSContext* aContext,
                                        jsval aValue);
 
     // cairo helpers
     nsresult CairoSurfaceFromElement(nsIDOMElement *imgElt,
-                                     PRBool forceCopy,
                                      cairo_surface_t **aCairoSurface,
+                                     PRUint8 **imgDataOut,
                                      PRInt32 *widthOut, PRInt32 *heightOut,
                                      nsIPrincipal **prinOut,
                                      PRBool *forceWriteOnlyOut);
 
     // other helpers
     void GetAppUnitsValues(PRUint32 *perDevPixel, PRUint32 *perCSSPixel) {
         // If we don't have a canvas element, we just return something generic.
         PRUint32 devPixel = 60;
@@ -1085,21 +1084,22 @@ nsCanvasRenderingContext2D::CreatePatter
     } else if (repeat.EqualsLiteral("no-repeat")) {
         extend = CAIRO_EXTEND_NONE;
     } else {
         // XXX ERRMSG we need to report an error to developers here! (bug 329026)
         return NS_ERROR_DOM_SYNTAX_ERR;
     }
 
     cairo_surface_t *imgSurf = nsnull;
+    PRUint8 *imgData = nsnull;
     PRInt32 imgWidth, imgHeight;
     nsCOMPtr<nsIPrincipal> principal;
     PRBool forceWriteOnly = PR_FALSE;
-    rv = CairoSurfaceFromElement(image, PR_TRUE,
-                                 &imgSurf, &imgWidth, &imgHeight,
+    rv = CairoSurfaceFromElement(image, &imgSurf, &imgData,
+                                 &imgWidth, &imgHeight,
                                  getter_AddRefs(principal), &forceWriteOnly);
     if (NS_FAILED(rv))
         return rv;
 
     cairo_pattern_t *cairopat = cairo_pattern_create_for_surface(imgSurf);
     cairo_surface_destroy(imgSurf);
 
     cairo_pattern_set_extend (cairopat, extend);
@@ -1913,21 +1913,22 @@ nsCanvasRenderingContext2D::DrawImage()
                                  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_path_t *old_path;
+    PRUint8 *imgData = nsnull;
     PRInt32 imgWidth, imgHeight;
     nsCOMPtr<nsIPrincipal> principal;
     PRBool forceWriteOnly = PR_FALSE;
-    rv = CairoSurfaceFromElement(imgElt, PR_FALSE,
-                                 &imgSurf, &imgWidth, &imgHeight,
+    rv = CairoSurfaceFromElement(imgElt, &imgSurf, &imgData,
+                                 &imgWidth, &imgHeight,
                                  getter_AddRefs(principal), &forceWriteOnly);
     if (NS_FAILED(rv))
         return rv;
     DoDrawImageSecurityCheck(principal, forceWriteOnly);
 
 #define GET_ARG(dest,whicharg) \
     do { if (!ConvertJSValToDouble(dest, ctx, whicharg)) { rv = NS_ERROR_INVALID_ARG; goto FINISH; } } while (0)
 
@@ -2148,25 +2149,22 @@ nsCanvasRenderingContext2D::ConvertJSVal
   }
 
   return JS_FALSE;
 }
 
 /* cairo ARGB32 surfaces are ARGB stored as a packed 32-bit integer; on little-endian
  * platforms, they appear as BGRA bytes in the surface data.  The color values are also
  * stored with premultiplied alpha.
- *
- * If forceCopy is FALSE, a surface may be returned that's only valid during the current
- * operation.  If it's TRUE, a copy will always be made that can safely be retained.
  */
 
 nsresult
 nsCanvasRenderingContext2D::CairoSurfaceFromElement(nsIDOMElement *imgElt,
-                                                    PRBool forceCopy,
                                                     cairo_surface_t **aCairoSurface,
+                                                    PRUint8 **imgData,
                                                     PRInt32 *widthOut,
                                                     PRInt32 *heightOut,
                                                     nsIPrincipal **prinOut,
                                                     PRBool *forceWriteOnlyOut)
 {
     nsresult rv;
 
     nsCOMPtr<imgIContainer> imgContainer;
@@ -2199,40 +2197,30 @@ nsCanvasRenderingContext2D::CairoSurface
         // maybe a canvas
         nsCOMPtr<nsICanvasElement> canvas = do_QueryInterface(imgElt);
         nsCOMPtr<nsINode> node = do_QueryInterface(imgElt);
         if (canvas && node) {
             PRUint32 w, h;
             rv = canvas->GetSize(&w, &h);
             NS_ENSURE_SUCCESS(rv, rv);
 
-            nsRefPtr<gfxASurface> sourceSurface;
-
-            if (!forceCopy && canvas->CountContexts() == 1) {
-                nsICanvasRenderingContextInternal *srcCanvas = canvas->GetContextAtIndex(0);
-                rv = srcCanvas->GetThebesSurface(getter_AddRefs(sourceSurface));
-                if (NS_FAILED(rv))
-                    sourceSurface = nsnull;
-            }
-
-            if (sourceSurface == nsnull) {
-                nsRefPtr<gfxASurface> surf =
-                    gfxPlatform::GetPlatform()->CreateOffscreenSurface
-                    (gfxIntSize(w, h), gfxASurface::ImageFormatARGB32);
-                nsRefPtr<gfxContext> ctx = new gfxContext(surf);
-                ctx->SetOperator(gfxContext::OPERATOR_OVER);
-
-                rv = canvas->RenderContexts(ctx);
-                if (NS_FAILED(rv))
-                    return rv;
-                sourceSurface = surf;
-            }
-
-            *aCairoSurface = sourceSurface->CairoSurface();
+            nsRefPtr<gfxImageSurface> surf =
+                new gfxImageSurface (gfxIntSize(w, h), gfxASurface::ImageFormatARGB32);
+            nsRefPtr<gfxContext> ctx = new gfxContext(surf);
+            ctx->SetOperator(gfxContext::OPERATOR_CLEAR);
+            ctx->Paint();
+            ctx->SetOperator(gfxContext::OPERATOR_OVER);
+
+            rv = canvas->RenderContexts(ctx);
+            if (NS_FAILED(rv))
+                return rv;
+
+            *aCairoSurface = surf->CairoSurface();
             cairo_surface_reference(*aCairoSurface);
+            *imgData = surf->Data();
             *widthOut = w;
             *heightOut = h;
 
             NS_ADDREF(*prinOut = node->NodePrincipal());
             *forceWriteOnlyOut = canvas->IsWriteOnly();
 
             return NS_OK;
         } else {
@@ -2271,16 +2259,17 @@ nsCanvasRenderingContext2D::CairoSurface
 
         ctx->SetOperator(gfxContext::OPERATOR_SOURCE);
         ctx->SetPattern(gfxpattern);
         ctx->Paint();
     }
 
     *aCairoSurface = gfxsurf->CairoSurface();
     cairo_surface_reference (*aCairoSurface);
+    *imgData = nsnull;
 
     return NS_OK;
 }
 
 /* Check that the rect [x,y,w,h] is a valid subrect of [0,0,realWidth,realHeight]
  * without overflowing any integers and the like.
  */
 PRBool
@@ -2653,23 +2642,8 @@ nsCanvasRenderingContext2D::PutImageData
     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();
 }
-
-NS_IMETHODIMP
-nsCanvasRenderingContext2D::GetThebesSurface(gfxASurface **surface)
-{
-    if (!mThebesSurface) {
-        *surface = nsnull;
-        return NS_ERROR_NOT_AVAILABLE;
-    }
-
-    *surface = mThebesSurface.get();
-    NS_ADDREF(*surface);
-
-    return NS_OK;
-}
-
--- a/content/html/content/src/nsGenericHTMLElement.h
+++ b/content/html/content/src/nsGenericHTMLElement.h
@@ -209,17 +209,17 @@ public:
                            nsIAtom* aPrefix, const nsAString& aValue,
                            PRBool aNotify);
   virtual nsresult UnsetAttr(PRInt32 aNameSpaceID, nsIAtom* aName,
                              PRBool aNotify);
   virtual PRBool IsNodeOfType(PRUint32 aFlags) const;
   virtual void RemoveFocus(nsPresContext *aPresContext);
   virtual PRBool IsFocusable(PRInt32 *aTabIndex = nsnull)
   {
-    PRBool isFocusable;
+    PRBool isFocusable = PR_FALSE;
     IsHTMLFocusable(&isFocusable, aTabIndex);
     return isFocusable;
   }
   /**
    * Returns PR_TRUE if a subclass is not allowed to override the value returned
    * in aIsFocusable.
    */
   virtual PRBool IsHTMLFocusable(PRBool *aIsFocusable, PRInt32 *aTabIndex);
--- a/content/html/content/src/nsHTMLCanvasElement.cpp
+++ b/content/html/content/src/nsHTMLCanvasElement.cpp
@@ -88,18 +88,16 @@ public:
   // nsICanvasElement
   NS_IMETHOD GetPrimaryCanvasFrame(nsIFrame **aFrame);
   NS_IMETHOD GetSize(PRUint32 *width, PRUint32 *height);
   NS_IMETHOD RenderContexts(gfxContext *ctx);
   virtual PRBool IsWriteOnly();
   virtual void SetWriteOnly();
   NS_IMETHOD InvalidateFrame ();
   NS_IMETHOD InvalidateFrameSubrect (const nsRect& damageRect);
-  virtual PRInt32 CountContexts();
-  virtual nsICanvasRenderingContextInternal *GetContextAtIndex (PRInt32 index);
 
   NS_IMETHOD_(PRBool) IsAttributeMapped(const nsIAtom* aAttribute) const;
   nsMapRuleToAttributesFunc GetAttributeMappingFunction() const;
   virtual PRBool ParseAttribute(PRInt32 aNamespaceID,
                                 nsIAtom* aAttribute,
                                 const nsAString& aValue,
                                 nsAttrValue& aResult);
   nsChangeHint GetAttributeChangeHint(const nsIAtom* aAttribute, PRInt32 aModType) const;
@@ -550,26 +548,8 @@ nsHTMLCanvasElement::InvalidateFrameSubr
 {
   nsIFrame *frame = GetPrimaryFrame(Flush_Frames);
   if (frame) {
     frame->Invalidate(damageRect, PR_FALSE);
   }
 
   return NS_OK;
 }
-
-PRInt32
-nsHTMLCanvasElement::CountContexts()
-{
-  if (mCurrentContext)
-    return 1;
-
-  return 0;
-}
-
-nsICanvasRenderingContextInternal *
-nsHTMLCanvasElement::GetContextAtIndex (PRInt32 index)
-{
-  if (mCurrentContext && index == 0)
-    return mCurrentContext.get();
-
-  return NULL;
-}
--- a/content/html/content/src/nsHTMLImageElement.cpp
+++ b/content/html/content/src/nsHTMLImageElement.cpp
@@ -451,16 +451,18 @@ nsHTMLImageElement::IsHTMLFocusable(PRBo
     if (imageMap) {
       if (aTabIndex) {
         // Use tab index on individual map areas
         *aTabIndex = (sTabFocusModel & eTabFocus_linksMask)? 0 : -1;
       }
       // Image map is not focusable itself, but flag as tabbable
       // so that image map areas get walked into.
       *aIsFocusable = PR_FALSE;
+
+      return PR_FALSE;
     }
   }
 
   if (aTabIndex) {
     // Can be in tab order if tabindex >=0 and form controls are tabbable.
     *aTabIndex = (sTabFocusModel & eTabFocus_formElementsMask)? tabIndex : -1;
   }
 
--- a/content/html/content/src/nsHTMLSharedObjectElement.cpp
+++ b/content/html/content/src/nsHTMLSharedObjectElement.cpp
@@ -296,17 +296,20 @@ nsHTMLSharedObjectElement::IsHTMLFocusab
                                            PRInt32 *aTabIndex)
 {
   if (mNodeInfo->Equals(nsGkAtoms::embed) || Type() == eType_Plugin) {
     // Has plugin content: let the plugin decide what to do in terms of
     // internal focus from mouse clicks
     if (aTabIndex) {
       GetTabIndex(aTabIndex);
     }
-  
+
+    *aIsFocusable = PR_TRUE;
+
+    // Let the plugin decide, so override.
     return PR_TRUE;
   }
 
   return nsGenericHTMLElement::IsHTMLFocusable(aIsFocusable, aTabIndex);
 }
 
 PRUint32
 nsHTMLSharedObjectElement::GetDesiredIMEState()
--- a/content/html/content/test/Makefile.in
+++ b/content/html/content/test/Makefile.in
@@ -107,12 +107,13 @@ include $(topsrcdir)/config/rules.mk
 		test_bug395107.html \
 		test_bug401160.xhtml \
 		test_bug408231.html \
 		test_bug417760.html \
 		file_bug417760.png \
 		test_bug428135.xhtml \
 		test_bug406596.html \
 		test_bug421640.html \
+		test_bug430351.html \
 		$(NULL)
 
 libs:: $(_TEST_FILES)
 	$(INSTALL) $(foreach f,$^,"$f") $(DEPTH)/_tests/testing/mochitest/tests/$(relativesrcdir)
new file mode 100644
--- /dev/null
+++ b/content/html/content/test/test_bug430351.html
@@ -0,0 +1,468 @@
+<!DOCTYPE HTML>
+<html>
+<!--
+https://bugzilla.mozilla.org/show_bug.cgi?id=430351
+-->
+<head>
+  <title>Test for Bug 430351</title>
+  <script type="text/javascript" src="/MochiKit/MochiKit.js"></script>
+  <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
+  <script type="text/javascript" src="/tests/SimpleTest/EventUtils.js"></script>
+  <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
+</head>
+<body>
+<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=430351">Mozilla Bug 430351</a>
+<p id="display"></p>
+<div id="content">
+  <div id="parent"></div>
+  <div id="editableParent" contenteditable="true"></div>
+  <iframe id="frame"></iframe>
+  <map name="map"><area></map>
+</div>
+<pre id="test">
+<script class="testbody" type="text/javascript">
+
+/** Test for Bug 430351 **/
+
+var focusableElements = [
+    "<a tabindex=\"-1\"></a>",
+    "<a tabindex=\"0\"></a>",
+    "<a tabindex=\"0\" disabled></a>",
+    "<a tabindex=\"1\"></a>",
+    "<a contenteditable=\"true\"></a>",
+
+    "<a href=\"#\"></a>",
+    "<a href=\"#\" tabindex=\"-1\"></a>",
+    "<a href=\"#\" tabindex=\"0\"></a>",
+    "<a href=\"#\" tabindex=\"0\" disabled></a>",
+    "<a href=\"#\" tabindex=\"1\"></a>",
+    "<a href=\"#\" contenteditable=\"true\"></a>",
+    "<a href=\"#\" disabled></a>",
+
+    "<button></button>",
+    "<button tabindex=\"-1\"></button>",
+    "<button tabindex=\"0\"></button>",
+    "<button tabindex=\"1\"></button>",
+    "<button contenteditable=\"true\"></button>",
+
+    "<button type=\"reset\"></button>",
+    "<button type=\"reset\" tabindex=\"-1\"></button>",
+    "<button type=\"reset\" tabindex=\"0\"></button>",
+    "<button type=\"reset\" tabindex=\"1\"></button>",
+    "<button type=\"reset\" contenteditable=\"true\"></button>",
+
+    "<button type=\"submit\"></button>",
+    "<button type=\"submit\" tabindex=\"-1\"></button>",
+    "<button type=\"submit\" tabindex=\"0\"></button>",
+    "<button type=\"submit\" tabindex=\"1\"></button>",
+    "<button type=\"submit\" contenteditable=\"true\"></button>",
+
+    "<div tabindex=\"-1\"></div>",
+    "<div tabindex=\"0\"></div>",
+    "<div tabindex=\"1\"></div>",
+    "<div contenteditable=\"true\"></div>",
+
+    "<embed>",
+    "<embed tabindex=\"-1\">",
+    "<embed tabindex=\"0\">",
+    "<embed tabindex=\"0\" disabled>",
+    "<embed tabindex=\"1\">",
+    "<embed disabled>",
+    "<embed contenteditable=\"true\">",
+
+    "<iframe contenteditable=\"true\"></iframe>",
+
+    "<iframe src=\"about:blank\"></iframe>",
+    "<iframe src=\"about:blank\" disabled></iframe>",
+    "<iframe src=\"about:blank\" tabindex=\"-1\"></iframe>",
+    "<iframe src=\"about:blank\" tabindex=\"0\"></iframe>",
+    "<iframe src=\"about:blank\" tabindex=\"0\" disabled></iframe>",
+    "<iframe src=\"about:blank\" tabindex=\"1\"></iframe>",
+    "<iframe src=\"about:blank\" contenteditable=\"true\"></iframe>",
+
+    "<img tabindex=\"-1\">",
+    "<img tabindex=\"0\">",
+    "<img tabindex=\"0\" disabled>",
+    "<img tabindex=\"1\">",
+
+    "<input>",
+    "<input tabindex=\"-1\">",
+    "<input tabindex=\"0\">",
+    "<input tabindex=\"1\">",
+    "<input contenteditable=\"true\">",
+
+    "<input type=\"button\">",
+    "<input type=\"button\" tabindex=\"-1\">",
+    "<input type=\"button\" tabindex=\"0\">",
+    "<input type=\"button\" tabindex=\"1\">",
+    "<input type=\"button\" contenteditable=\"true\">",
+
+    "<input type=\"checkbox\">",
+    "<input type=\"checkbox\" tabindex=\"-1\">",
+    "<input type=\"checkbox\" tabindex=\"0\">",
+    "<input type=\"checkbox\" tabindex=\"1\">",
+    "<input type=\"checkbox\" contenteditable=\"true\">",
+
+    "<input type=\"image\">",
+    "<input type=\"image\" tabindex=\"-1\">",
+    "<input type=\"image\" tabindex=\"0\">",
+    "<input type=\"image\" tabindex=\"1\">",
+    "<input type=\"image\" contenteditable=\"true\">",
+
+    "<input type=\"password\">",
+    "<input type=\"password\" tabindex=\"-1\">",
+    "<input type=\"password\" tabindex=\"0\">",
+    "<input type=\"password\" tabindex=\"1\">",
+    "<input type=\"password\" contenteditable=\"true\">",
+
+    "<input type=\"radio\">",
+    "<input type=\"radio\" tabindex=\"-1\">",
+    "<input type=\"radio\" tabindex=\"0\">",
+    "<input type=\"radio\" tabindex=\"1\">",
+    "<input type=\"radio\" contenteditable=\"true\">",
+    "<input type=\"radio\" checked>",
+    "<form><input type=\"radio\" name=\"foo\"></form>",
+
+    "<input type=\"reset\">",
+    "<input type=\"reset\" tabindex=\"-1\">",
+    "<input type=\"reset\" tabindex=\"0\">",
+    "<input type=\"reset\" tabindex=\"1\">",
+    "<input type=\"reset\" contenteditable=\"true\">",
+
+    "<input type=\"submit\">",
+    "<input type=\"submit\" tabindex=\"-1\">",
+    "<input type=\"submit\" tabindex=\"0\">",
+    "<input type=\"submit\" tabindex=\"1\">",
+    "<input type=\"submit\" contenteditable=\"true\">",
+
+    "<input type=\"text\">",
+    "<input type=\"text\" tabindex=\"-1\">",
+    "<input type=\"text\" tabindex=\"0\">",
+    "<input type=\"text\" tabindex=\"1\">",
+    "<input type=\"text\" contenteditable=\"true\">",
+
+    "<object tabindex=\"-1\"></object>",
+    "<object tabindex=\"0\"></object>",
+    "<object tabindex=\"1\"></object>",
+    "<object contenteditable=\"true\"></object>",
+
+    "<object classid=\"java:a\"></object>",
+    "<object classid=\"java:a\" tabindex=\"-1\"></object>",
+    "<object classid=\"java:a\" tabindex=\"0\"></object>",
+    "<object classid=\"java:a\" tabindex=\"0\" disabled></object>",
+    "<object classid=\"java:a\" tabindex=\"1\"></object>",
+    "<object classid=\"java:a\" disabled></object>",
+    "<object classid=\"java:a\" contenteditable=\"true\"></object>",
+
+    "<select></select>",
+    "<select tabindex=\"-1\"></select>",
+    "<select tabindex=\"0\"></select>",
+    "<select tabindex=\"1\"></select>",
+    "<select contenteditable=\"true\"></select>"
+];
+
+var nonFocusableElements = [
+    "<a></a>",
+    "<a disabled></a>",
+
+    "<button tabindex=\"0\" disabled></button>",
+    "<button disabled></button>",
+
+    "<button type=\"reset\" tabindex=\"0\" disabled></button>",
+    "<button type=\"reset\" disabled></button>",
+
+    "<button type=\"submit\" tabindex=\"0\" disabled></button>",
+    "<button type=\"submit\" disabled></button>",
+
+    "<div></div>",
+    "<div tabindex=\"0\" disabled></div>",
+    "<div disabled></div>",
+
+    "<iframe></iframe>",
+    "<iframe tabindex=\"-1\"></iframe>",
+    "<iframe tabindex=\"0\"></iframe>",
+    "<iframe tabindex=\"0\" disabled></iframe>",
+    "<iframe tabindex=\"1\"></iframe>",
+    "<iframe disabled></iframe>",
+
+    "<img>",
+    "<img disabled>",
+    "<img contenteditable=\"true\">",
+
+    "<img usemap=\"#map\">",
+    "<img usemap=\"#map\" tabindex=\"-1\">",
+    "<img usemap=\"#map\" tabindex=\"0\">",
+    "<img usemap=\"#map\" tabindex=\"0\" disabled>",
+    "<img usemap=\"#map\" tabindex=\"1\">",
+    "<img usemap=\"#map\" disabled>",
+    "<img usemap=\"#map\" contenteditable=\"true\">",
+
+    "<input tabindex=\"0\" disabled>",
+    "<input disabled>",
+
+    "<input type=\"button\" tabindex=\"0\" disabled>",
+    "<input type=\"button\" disabled>",
+
+    "<input type=\"checkbox\" tabindex=\"0\" disabled>",
+    "<input type=\"checkbox\" disabled>",
+
+    "<input type=\"file\">",
+    "<input type=\"file\" tabindex=\"-1\">",
+    "<input type=\"file\" tabindex=\"0\">",
+    "<input type=\"file\" tabindex=\"0\" disabled>",
+    "<input type=\"file\" tabindex=\"1\">",
+    "<input type=\"file\" disabled>",
+    "<input type=\"file\" contenteditable=\"true\">",
+
+    "<input type=\"hidden\">",
+    "<input type=\"hidden\" tabindex=\"-1\">",
+    "<input type=\"hidden\" tabindex=\"0\">",
+    "<input type=\"hidden\" tabindex=\"0\" disabled>",
+    "<input type=\"hidden\" tabindex=\"1\">",
+    "<input type=\"hidden\" disabled>",
+    "<input type=\"hidden\" contenteditable=\"true\">",
+
+    "<input type=\"image\" tabindex=\"0\" disabled>",
+    "<input type=\"image\" disabled>",
+
+    "<input type=\"password\" tabindex=\"0\" disabled>",
+    "<input type=\"password\" disabled>",
+
+    "<input type=\"radio\" tabindex=\"0\" disabled>",
+    "<input type=\"radio\" disabled>",
+
+    "<input type=\"reset\" tabindex=\"0\" disabled>",
+    "<input type=\"reset\" disabled>",
+
+    "<input type=\"submit\" tabindex=\"0\" disabled>",
+    "<input type=\"submit\" disabled>",
+
+    "<input type=\"text\" tabindex=\"0\" disabled>",
+    "<input type=\"text\" disabled>",
+
+    "<object></object>",
+    "<object tabindex=\"0\" disabled></object>",
+    "<object disabled></object>",
+
+    "<select tabindex=\"0\" disabled></select>",
+    "<select disabled></select>"
+];
+
+var focusableInContentEditable = [
+    "<button></button>",
+    "<button tabindex=\"-1\"></button>",
+    "<button tabindex=\"0\"></button>",
+    "<button tabindex=\"1\"></button>",
+    "<button contenteditable=\"true\"></button>",
+
+    "<button type=\"reset\"></button>",
+    "<button type=\"reset\" tabindex=\"-1\"></button>",
+    "<button type=\"reset\" tabindex=\"0\"></button>",
+    "<button type=\"reset\" tabindex=\"1\"></button>",
+    "<button type=\"reset\" contenteditable=\"true\"></button>",
+
+    "<button type=\"submit\"></button>",
+    "<button type=\"submit\" tabindex=\"-1\"></button>",
+    "<button type=\"submit\" tabindex=\"0\"></button>",
+    "<button type=\"submit\" tabindex=\"1\"></button>",
+    "<button type=\"submit\" contenteditable=\"true\"></button>",
+
+    "<div tabindex=\"-1\"></div>",
+    "<div tabindex=\"0\"></div>",
+    "<div tabindex=\"1\"></div>",
+
+    "<embed>",
+    "<embed tabindex=\"-1\">",
+    "<embed tabindex=\"0\">",
+    "<embed tabindex=\"0\" disabled>",
+    "<embed tabindex=\"1\">",
+    "<embed disabled>",
+    "<embed contenteditable=\"true\">",
+
+    "<iframe src=\"about:blank\"></iframe>",
+    "<iframe src=\"about:blank\" disabled></iframe>",
+    "<iframe src=\"about:blank\" tabindex=\"-1\"></iframe>",
+    "<iframe src=\"about:blank\" tabindex=\"0\"></iframe>",
+    "<iframe src=\"about:blank\" tabindex=\"0\" disabled></iframe>",
+    "<iframe src=\"about:blank\" tabindex=\"1\"></iframe>",
+    "<iframe src=\"about:blank\" contenteditable=\"true\"></iframe>",
+
+    "<img tabindex=\"-1\">",
+    "<img tabindex=\"0\">",
+    "<img tabindex=\"0\" disabled>",
+    "<img tabindex=\"1\">",
+
+    "<input>",
+    "<input tabindex=\"-1\">",
+    "<input tabindex=\"0\">",
+    "<input tabindex=\"1\">",
+    "<input contenteditable=\"true\">",
+
+    "<input type=\"button\">",
+    "<input type=\"button\" tabindex=\"-1\">",
+    "<input type=\"button\" tabindex=\"0\">",
+    "<input type=\"button\" tabindex=\"1\">",
+    "<input type=\"button\" contenteditable=\"true\">",
+
+    "<input type=\"checkbox\">",
+    "<input type=\"checkbox\" tabindex=\"-1\">",
+    "<input type=\"checkbox\" tabindex=\"0\">",
+    "<input type=\"checkbox\" tabindex=\"1\">",
+    "<input type=\"checkbox\" contenteditable=\"true\">",
+
+    "<input type=\"image\">",
+    "<input type=\"image\" tabindex=\"-1\">",
+    "<input type=\"image\" tabindex=\"0\">",
+    "<input type=\"image\" tabindex=\"1\">",
+    "<input type=\"image\" contenteditable=\"true\">",
+
+    "<input type=\"password\">",
+    "<input type=\"password\" tabindex=\"-1\">",
+    "<input type=\"password\" tabindex=\"0\">",
+    "<input type=\"password\" tabindex=\"1\">",
+    "<input type=\"password\" contenteditable=\"true\">",
+
+    "<input type=\"radio\">",
+    "<input type=\"radio\" tabindex=\"-1\">",
+    "<input type=\"radio\" tabindex=\"0\">",
+    "<input type=\"radio\" tabindex=\"1\">",
+    "<input type=\"radio\" contenteditable=\"true\">",
+    "<input type=\"radio\" checked>",
+    "<form><input type=\"radio\" name=\"foo\"></form>",
+
+    "<input type=\"reset\">",
+    "<input type=\"reset\" tabindex=\"-1\">",
+    "<input type=\"reset\" tabindex=\"0\">",
+    "<input type=\"reset\" tabindex=\"1\">",
+    "<input type=\"reset\" contenteditable=\"true\">",
+
+    "<input type=\"submit\">",
+    "<input type=\"submit\" tabindex=\"-1\">",
+    "<input type=\"submit\" tabindex=\"0\">",
+    "<input type=\"submit\" tabindex=\"1\">",
+    "<input type=\"submit\" contenteditable=\"true\">",
+
+    "<input type=\"text\">",
+    "<input type=\"text\" tabindex=\"-1\">",
+    "<input type=\"text\" tabindex=\"0\">",
+    "<input type=\"text\" tabindex=\"1\">",
+    "<input type=\"text\" contenteditable=\"true\">",
+
+    "<object tabindex=\"-1\"></object>",
+    "<object tabindex=\"0\"></object>",
+    "<object tabindex=\"1\"></object>",
+    "<select></select>",
+    "<select tabindex=\"-1\"></select>",
+    "<select tabindex=\"0\"></select>",
+    "<select tabindex=\"1\"></select>",
+    "<select contenteditable=\"true\"></select>"
+];
+
+var focusableInDesignMode = [
+    "<embed>",
+    "<embed tabindex=\"-1\">",
+    "<embed tabindex=\"0\">",
+    "<embed tabindex=\"0\" disabled>",
+    "<embed tabindex=\"1\">",
+    "<embed disabled>",
+    "<embed contenteditable=\"true\">",
+
+    "<img tabindex=\"-1\">",
+    "<img tabindex=\"0\">",
+    "<img tabindex=\"0\" disabled>",
+    "<img tabindex=\"1\">",
+];
+
+// Can't currently test these, need a plugin.
+var focusableElementsTODO = [
+    "<object classid=\"java:a\"></object>",
+    "<object classid=\"java:a\" tabindex=\"-1\"></object>",
+    "<object classid=\"java:a\" tabindex=\"0\"></object>",
+    "<object classid=\"java:a\" tabindex=\"0\" disabled></object>",
+    "<object classid=\"java:a\" tabindex=\"1\"></object>",
+    "<object classid=\"java:a\" disabled></object>",
+    "<object classid=\"java:a\" contenteditable=\"true\"></object>",
+];
+
+var serializer = new XMLSerializer();
+
+function testElements(parent, tags, shouldBeFocusable)
+{
+    var focusable, errorSuffix = "";
+    if (parent.ownerDocument.designMode == "on") {
+        focusable = focusableInDesignMode;
+        errorSuffix = " in a document with designMode=on";
+    }
+    else if (parent.contentEditable == "true") {
+        focusable = focusableInContentEditable;
+    }
+
+    for each (var tag in tags) {
+        parent.ownerDocument.body.focus();
+
+        if (focusableElementsTODO.indexOf(tag) > -1) {
+            todo_is(parent.ownerDocument.activeElement, parent.firstChild,
+                    tag + " should be focusable" + errorSuffix);
+            continue;
+        }
+
+        parent.innerHTML = tag;
+
+        // Focus the deepest descendant.
+        var descendant = parent;
+        while ((descendant = descendant.firstChild))
+            element = descendant;
+
+        if (element.nodeName == "IFRAME" && element.hasAttribute("src"))
+            var foo = element.contentDocument;
+
+        element.focus();
+
+        var errorPrefix = serializer.serializeToString(element) + " in " +
+                          serializer.serializeToString(parent);
+
+        if (focusable ? focusable.indexOf(tag) > -1 : shouldBeFocusable) {
+            is(parent.ownerDocument.activeElement, element,
+               errorPrefix + " should be focusable" + errorSuffix);
+        }
+        else {
+            isnot(parent.ownerDocument.activeElement, element,
+                  errorPrefix + " should not be focusable" + errorSuffix);
+        }
+
+        parent.innerHTML = "";
+    }
+}
+
+function test()
+{
+    var parent = document.getElementById("parent");
+    var editableParent = document.getElementById("editableParent");
+
+    testElements(parent, focusableElements, true);
+    testElements(parent, nonFocusableElements, false);
+
+    testElements(editableParent, focusableElements, true);
+    testElements(editableParent, nonFocusableElements, false);
+
+    var frame = document.getElementById("frame");
+    frame.contentDocument.body.innerHTML = document.getElementById("content").innerHTML;
+    frame.contentDocument.designMode = "on";
+    parent = frame.contentDocument.getElementById("parent");
+    editableParent = frame.contentDocument.getElementById("editableParent");
+
+    testElements(parent, focusableElements, false);
+    testElements(parent, nonFocusableElements, false);
+
+    testElements(editableParent, focusableElements, false);
+    testElements(editableParent, nonFocusableElements, false);
+}
+
+SimpleTest.waitForExplicitFinish();
+addLoadEvent(test);
+addLoadEvent(SimpleTest.finish);
+
+</script>
+</pre>
+</body>
+</html>
--- a/dom/src/base/nsDOMClassInfo.cpp
+++ b/dom/src/base/nsDOMClassInfo.cpp
@@ -4780,20 +4780,29 @@ BaseStubConstructor(nsIWeakReference* aW
   }
   if (NS_FAILED(rv)) {
     NS_ERROR("Failed to create the object");
     return rv;
   }
 
   nsCOMPtr<nsIJSNativeInitializer> initializer(do_QueryInterface(native));
   if (initializer) {
+    // Initialize object using the current inner window, but only if
+    // the caller can access it.
     nsCOMPtr<nsPIDOMWindow> owner = do_QueryReferent(aWeakOwner);
-    NS_ENSURE_STATE(owner && owner->GetOuterWindow() &&
-                    owner->GetOuterWindow()->GetCurrentInnerWindow() == owner);
-    rv = initializer->Initialize(owner, cx, obj, argc, argv);
+    nsPIDOMWindow* outerWindow = owner ? owner->GetOuterWindow() : nsnull;
+    nsPIDOMWindow* currentInner =
+      outerWindow ? outerWindow->GetCurrentInnerWindow() : nsnull;
+    if (!currentInner ||
+        (owner != currentInner &&
+         !nsContentUtils::CanCallerAccess(currentInner))) {
+      return NS_ERROR_DOM_SECURITY_ERR;
+    }
+
+    rv = initializer->Initialize(currentInner, cx, obj, argc, argv);
     if (NS_FAILED(rv)) {
       return NS_ERROR_NOT_INITIALIZED;
     }
   }
 
   nsCOMPtr<nsIScriptObjectOwner> owner(do_QueryInterface(native));
   if (owner) {
     nsIScriptContext *context = nsJSUtils::GetStaticScriptContext(cx, obj);
--- a/dom/tests/mochitest/bugs/Makefile.in
+++ b/dom/tests/mochitest/bugs/Makefile.in
@@ -71,12 +71,13 @@ include $(topsrcdir)/config/rules.mk
 		test_bug424093.html \
 		iframe_bug424093.html \
 		test_bug409349.html \
 		iframe_bug409349.html \
 		test_bug411103.html \
 		test_bug414291.html \
 		test_bug430276.html \
 		iframe_bug430276.html \
+		iframe_bug430276-2.html \
 		$(NULL)
 
 libs:: 	$(_TEST_FILES)
 	$(INSTALL) $(foreach f,$^,"$f") $(DEPTH)/_tests/testing/mochitest/tests/$(relativesrcdir)
new file mode 100644
--- /dev/null
+++ b/dom/tests/mochitest/bugs/iframe_bug430276-2.html
@@ -0,0 +1,23 @@
+<!DOCTYPE html>
+<html>
+<head>
+  <title></title>
+  <script type="application/javascript">
+  new XMLHttpRequest();
+  function runTest() {
+    document.open();
+    var succeeded = true;
+    try {
+      new XMLHttpRequest();
+    } catch(e) {
+      succeeded = false;
+    }
+    window.parent.ok(succeeded, "Creating XMLHttpRequest failed!");
+    window.parent.SimpleTest.finish();
+    document.close();
+  }
+  </script>
+</head>
+<body onload="runTest()">
+</body>
+</html>
--- a/dom/tests/mochitest/bugs/iframe_bug430276.html
+++ b/dom/tests/mochitest/bugs/iframe_bug430276.html
@@ -7,15 +7,15 @@
     document.write("<body>");
     var succeeded = true;
     try {
       new XMLHttpRequest();
     } catch(e) {
       succeeded = false;
     }
     window.parent.ok(succeeded, "Creating XMLHttpRequest failed!");
-    window.parent.SimpleTest.finish();
+    window.parent.nextTest();
   }
   </script>
 </head>
 <body onload="runTest()">
 </body>
 </html>
--- a/dom/tests/mochitest/bugs/test_bug430276.html
+++ b/dom/tests/mochitest/bugs/test_bug430276.html
@@ -20,16 +20,21 @@ https://bugzilla.mozilla.org/show_bug.cg
 
 /** Test for Bug 430276 **/
 
 function startTest() {
   document.getElementById("testFrame")
     .setAttribute("src", "iframe_bug430276.html");
 }
 
+function nextTest() {
+  document.getElementById("testFrame")
+    .setAttribute("src", "iframe_bug430276-2.html");
+}
+
 SimpleTest.waitForExplicitFinish();
 addLoadEvent(startTest);
 
 
 </script>
 </pre>
 <iframe id="testFrame">
 </body>
--- a/gfx/thebes/public/gfxWindowsFonts.h
+++ b/gfx/thebes/public/gfxWindowsFonts.h
@@ -260,18 +260,22 @@ public:
                       gfxContext *aContext, PRBool aDrawToPath, gfxPoint *aBaselineOrigin,
                       Spacing *aSpacing);
 
     virtual PRUint32 GetSpaceGlyph() {
         GetMetrics(); // ensure that the metrics are computed but don't recompute them
         return mSpaceGlyph;
     };
 
+    PRBool IsValid() { GetMetrics(); return mIsValid; }
     FontEntry *GetFontEntry() { return mFontEntry; }
 
+    static already_AddRefed<gfxWindowsFont>
+    GetOrMakeFont(FontEntry *aFontEntry, const gfxFontStyle *aStyle);
+
 protected:
     HFONT MakeHFONT();
     void FillLogFont(gfxFloat aSize);
 
     HFONT    mFont;
     gfxFloat mAdjustedSize;
     PRUint32 mSpaceGlyph;
 
@@ -283,16 +287,17 @@ private:
     cairo_font_face_t *mFontFace;
     cairo_scaled_font_t *mScaledFont;
 
     gfxFont::Metrics *mMetrics;
 
     LOGFONTW mLogFont;
 
     nsRefPtr<FontEntry> mFontEntry;
+    PRPackedBool mIsValid;
     
     virtual PRBool SetupCairoFont(gfxContext *aContext);
 };
 
 /**********************************************************************
  *
  * class gfxWindowsFontGroup
  *
--- a/gfx/thebes/public/gfxWindowsPlatform.h
+++ b/gfx/thebes/public/gfxWindowsPlatform.h
@@ -79,17 +79,17 @@ public:
 
     /* Given a string and a font we already have find the font that
      * supports the most code points and most closely resembles aFont
      *
      * this involves looking at the fonts on your machine and seeing which
      * code points they support as well as looking at things like the font
      * family, style, weight, etc.
      */
-    FontEntry *FindFontForChar(PRUint32 aCh, gfxWindowsFont *aFont);
+    already_AddRefed<gfxWindowsFont> FindFontForChar(PRUint32 aCh, gfxWindowsFont *aFont);
 
     /* Find a FontFamily/FontEntry object that represents a font on your system given a name */
     FontFamily *FindFontFamily(const nsAString& aName);
     FontEntry *FindFontEntry(const nsAString& aName, const gfxFontStyle& aFontStyle);
 
     PRBool GetPrefFontEntries(const nsCString& aLangGroup, nsTArray<nsRefPtr<FontEntry> > *array);
     void SetPrefFontEntries(const nsCString& aLangGroup, nsTArray<nsRefPtr<FontEntry> >& array);
 
--- a/gfx/thebes/src/gfxWindowsFonts.cpp
+++ b/gfx/thebes/src/gfxWindowsFonts.cpp
@@ -381,17 +381,17 @@ FontFamily::FindFontEntry(const gfxFontS
  * class gfxWindowsFont
  *
  **********************************************************************/
 
 gfxWindowsFont::gfxWindowsFont(const nsAString& aName, const gfxFontStyle *aFontStyle, FontEntry *aFontEntry)
     : gfxFont(aName, aFontStyle),
       mFont(nsnull), mAdjustedSize(0.0), mScriptCache(nsnull),
       mFontFace(nsnull), mScaledFont(nsnull),
-      mMetrics(nsnull), mFontEntry(aFontEntry)
+      mMetrics(nsnull), mFontEntry(aFontEntry), mIsValid(PR_TRUE)
 {
     NS_ASSERTION(mFontEntry, "Unable to find font entry for font.  Something is whack.");
 
     mFont = MakeHFONT(); // create the HFONT, compute metrics, etc
     NS_ASSERTION(mFont, "Failed to make HFONT");
 }
 
 gfxWindowsFont::~gfxWindowsFont()
@@ -523,17 +523,28 @@ gfxWindowsFont::ComputeMetrics()
         }
         mMetrics->emHeight = metrics.tmHeight - metrics.tmInternalLeading;
         gfxFloat typEmHeight = (double)oMetrics.otmAscent - (double)oMetrics.otmDescent;
         mMetrics->emAscent = ROUND(mMetrics->emHeight * (double)oMetrics.otmAscent / typEmHeight);
         mMetrics->emDescent = mMetrics->emHeight - mMetrics->emAscent;
     } else {
         // Make a best-effort guess at extended metrics
         // this is based on general typographic guidelines
-        GetTextMetrics(dc, &metrics);
+        
+        // GetTextMetrics can fail if the font file has been removed
+        // or corrupted recently.
+        BOOL result = GetTextMetrics(dc, &metrics);
+        if (!result) {
+            NS_WARNING("Missing or corrupt font data, fasten your seatbelt");
+            mIsValid = PR_FALSE;
+            memset(mMetrics, 0, sizeof(*mMetrics));
+            SelectObject(dc, oldFont);
+            ReleaseDC((HWND)nsnull, dc);
+            return;
+        }
 
         mMetrics->xHeight = ROUND((float)metrics.tmAscent * 0.56f); // 56% of ascent, best guess for non-true type
         mMetrics->superscriptOffset = mMetrics->xHeight;
         mMetrics->subscriptOffset = mMetrics->xHeight;
         mMetrics->strikeoutSize = 1;
         mMetrics->strikeoutOffset = ROUND(mMetrics->xHeight / 2.0f); // 50% of xHeight
         mMetrics->underlineSize = 1;
         mMetrics->underlineOffset = -ROUND((float)metrics.tmDescent * 0.30f); // 30% of descent
@@ -671,18 +682,18 @@ gfxWindowsFont::SetupCairoFont(gfxContex
  *
  **********************************************************************/
 
 /**
  * Look up the font in the gfxFont cache. If we don't find it, create one.
  * In either case, add a ref, append it to the aFonts array, and return it ---
  * except for OOM in which case we do nothing and return null.
  */
-static already_AddRefed<gfxWindowsFont>
-GetOrMakeFont(FontEntry *aFontEntry, const gfxFontStyle *aStyle)
+already_AddRefed<gfxWindowsFont>
+gfxWindowsFont::GetOrMakeFont(FontEntry *aFontEntry, const gfxFontStyle *aStyle)
 {
     // because we know the FontEntry has the weight we really want, use it for matching
     // things in the cache so we don't end up with things like 402 in there.
     gfxFontStyle style(*aStyle);
     style.weight = aFontEntry->mWeight;
     // also pre-round the size if there is no size adjust
     if (style.sizeAdjust == 0.0)
         style.size = ROUND(style.size);
@@ -743,31 +754,53 @@ gfxWindowsFontGroup::FamilyListToArrayLi
     }
 }
 
 gfxWindowsFontGroup::gfxWindowsFontGroup(const nsAString& aFamilies, const gfxFontStyle *aStyle)
     : gfxFontGroup(aFamilies, aStyle)
 {
     GroupFamilyListToArrayList(&mFontEntries);
 
+    mFonts.AppendElements(mFontEntries.Length());
+
+    // Ensure that the first font is usable. Precompute its metrics since
+    // we'll surely need them anyway.
+    while (mFontEntries.Length() > 0) {
+        nsRefPtr<gfxWindowsFont> font =
+            gfxWindowsFont::GetOrMakeFont(mFontEntries[0], &mStyle);
+        if (!font->IsValid()) {
+            mFontEntries.RemoveElementAt(0);
+            mFonts.RemoveElementAt(0);
+            continue;
+        }
+        mFonts[0] = font;
+        break;
+    }
+
     if (mFontEntries.Length() == 0) {
         // Should append default GUI font if there are no available fonts.
         HGDIOBJ hGDI = ::GetStockObject(DEFAULT_GUI_FONT);
         LOGFONTW logFont;
         if (!hGDI ||
             !::GetObjectW(hGDI, sizeof(logFont), &logFont)) {
             NS_ERROR("Failed to create font group");
             return;
         }
         nsRefPtr<FontEntry> fe = gfxWindowsPlatform::GetPlatform()->FindFontEntry(nsDependentString(logFont.lfFaceName), *aStyle);
         mFontEntries.AppendElement(fe);
+        // Keep length of mFonts in sync with length of mFontEntries.
+        // Maybe we should eagerly set up mFonts[0] like we do above,
+        // but if the resulting gfxWindowsFont is invalid then we can't
+        // do much anyway. In that case the font will return zero metrics,
+        // its mUnknownCMAP will be set to true, and HasCharacter will
+        // just report false for all characters, so the fact that the font
+        // is bogus should not cause problems.
+        mFonts.AppendElements(1);
     }
 
-    mFonts.AppendElements(mFontEntries.Length());
-
     if (!mStyle.systemFont) {
         for (PRUint32 i = 0; i < mFontEntries.Length(); ++i) {
             if (mFontEntries[i]->IsBadUnderlineFont()) {
                 gfxFloat first = GetFontAt(0)->GetMetrics().underlineOffset;
                 gfxFloat bad = GetFontAt(i)->GetMetrics().underlineOffset;
                 mUnderlineOffset = PR_MIN(first, bad);
                 break;
             }
@@ -778,17 +811,18 @@ gfxWindowsFontGroup::gfxWindowsFontGroup
 gfxWindowsFontGroup::~gfxWindowsFontGroup()
 {
 }
 
 gfxWindowsFont *
 gfxWindowsFontGroup::GetFontAt(PRInt32 i)
 {
     if (!mFonts[i]) {
-        nsRefPtr<gfxWindowsFont> font = GetOrMakeFont(mFontEntries[i], &mStyle);
+        nsRefPtr<gfxWindowsFont> font =
+            gfxWindowsFont::GetOrMakeFont(mFontEntries[i], &mStyle);
         mFonts[i] = font;
     }
 
     return static_cast<gfxWindowsFont*>(mFonts[i].get());
 }
 
 gfxFontGroup *
 gfxWindowsFontGroup::Copy(const gfxFontStyle *aStyle)
@@ -1498,43 +1532,45 @@ public:
         cairo_win32_scaled_font_select_font(scaledFont, mDC);
 
         mFontSelected = PR_TRUE;
     }
 
     struct TextRange {
         TextRange(PRUint32 aStart,  PRUint32 aEnd) : start(aStart), end(aEnd) { }
         PRUint32 Length() const { return end - start; }
-        nsRefPtr<FontEntry> font;
+        nsRefPtr<gfxWindowsFont> font;
         PRUint32 start, end;
     };
 
     void SetRange(PRUint32 i) {
-        nsRefPtr<FontEntry> fe;
+        nsRefPtr<gfxWindowsFont> font;
         if (mRanges[i].font)
-            fe = mRanges[i].font;
+            font = mRanges[i].font;
         else
-            fe = mGroup->GetFontEntryAt(0);
+            font = mGroup->GetFontAt(0);
 
-        nsRefPtr<gfxWindowsFont> font = GetOrMakeFont(fe, mGroup->GetStyle());
         SetCurrentFont(font);
 
         mRangeString = mItemString + mRanges[i].start;
         mRangeLength = mRanges[i].Length();
     }
 
     PRBool HasCharacter(FontEntry *aFontEntry, PRUint32 ch) {
         if (aFontEntry->mCharacterMap.test(ch))
             return PR_TRUE;
 
         if (aFontEntry->mUnknownCMAP) {
             if (ch > 0xFFFF)
                 return PR_FALSE;
 
-            nsRefPtr<gfxWindowsFont> font = GetOrMakeFont(aFontEntry, mGroup->GetStyle());
+            nsRefPtr<gfxWindowsFont> font =
+                gfxWindowsFont::GetOrMakeFont(aFontEntry, mGroup->GetStyle());
+            if (!font->IsValid())
+                return PR_FALSE;
 
             HDC dc = GetDC((HWND)nsnull);
             HFONT hfont = font->GetHFONT();
             HFONT oldFont = (HFONT)SelectObject(dc, hfont);
 
             PRUnichar str[1] = { (PRUnichar)ch };
             WORD glyph[1];
 
@@ -1558,51 +1594,61 @@ public:
 
             SelectObject(dc, oldFont);
             ReleaseDC(NULL, dc);
         }
 
         return PR_FALSE;
     }
 
-    inline FontEntry *WhichFontSupportsChar(const nsTArray<nsRefPtr<FontEntry> >& fonts, PRUint32 ch) {
+    inline already_AddRefed<gfxWindowsFont>
+    WhichFontSupportsChar(const nsTArray<nsRefPtr<FontEntry> >& fonts, PRUint32 ch) {
         for (PRUint32 i = 0; i < fonts.Length(); i++) {
             nsRefPtr<FontEntry> fe = fonts[i];
             if (fe->mSymbolFont && !mGroup->GetStyle()->familyNameQuirks)
                 continue;
-            if (HasCharacter(fe, ch))
-                return fe;
+            if (HasCharacter(fe, ch)) {
+                nsRefPtr<gfxWindowsFont> font =
+                    gfxWindowsFont::GetOrMakeFont(fe, mGroup->GetStyle());
+                // Check that the font is still usable.
+                if (!font->IsValid())
+                    continue;
+                return font.forget();
+            }
         }
         return nsnull;
     }
 
-
     static inline bool IsJoiner(PRUint32 ch) {
         return (ch == 0x200C ||
                 ch == 0x200D ||
                 ch == 0x2060);
     }
 
-    inline FontEntry *FindFontForChar(PRUint32 ch, PRUint32 prevCh, PRUint32 nextCh, FontEntry *aFont) {
-        nsRefPtr<FontEntry> selectedFont;
+    inline already_AddRefed<gfxWindowsFont>
+    FindFontForChar(PRUint32 ch, PRUint32 prevCh, PRUint32 nextCh,
+                    gfxWindowsFont *aFont) {
+        nsRefPtr<gfxWindowsFont> selectedFont;
 
         // if this character or the next one is a joiner use the
         // same font as the previous range if we can
         if (IsJoiner(ch) || IsJoiner(prevCh) || IsJoiner(nextCh)) {
-            if (aFont && HasCharacter(aFont, ch))
+            if (aFont && HasCharacter(aFont->GetFontEntry(), ch)) {
+                NS_ADDREF(aFont);
                 return aFont;
+            }
         }
 
         // check the list of fonts
         selectedFont = WhichFontSupportsChar(mGroup->GetFontList(), ch);
 
         // don't look in other fonts if the character is in a Private Use Area
         if ((ch >= 0xE000  && ch <= 0xF8FF) || 
             (ch >= 0xF0000 && ch <= 0x10FFFD))
-            return selectedFont;
+            return selectedFont.forget();
 
         // check out the style's language group
         if (!selectedFont) {
             nsAutoTArray<nsRefPtr<FontEntry>, 5> fonts;
             this->GetPrefFonts(mGroup->GetStyle()->langGroup.get(), fonts);
             selectedFont = WhichFontSupportsChar(fonts, ch);
         }
 
@@ -1640,29 +1686,29 @@ public:
                         this->GetPrefFonts(langGroup, fonts);
                         selectedFont = WhichFontSupportsChar(fonts, ch);
                     }
                 }
             }
         }
 
         // before searching for something else check the font used for the previous character
-        if (!selectedFont && aFont && HasCharacter(aFont, ch))
+        if (!selectedFont && aFont && HasCharacter(aFont->GetFontEntry(), ch))
             selectedFont = aFont;
 
         // otherwise look for other stuff
         if (!selectedFont) {
             PR_LOG(gFontLog, PR_LOG_DEBUG, (" - Looking for best match"));
 
             nsRefPtr<gfxWindowsFont> refFont = mGroup->GetFontAt(0);
             gfxWindowsPlatform *platform = gfxWindowsPlatform::GetPlatform();
             selectedFont = platform->FindFontForChar(ch, refFont);
         }
 
-        return selectedFont;
+        return selectedFont.forget();
     }
 
     PRUint32 ComputeRanges() {
         if (mItemLength == 0)
             return 0;
 
         PR_LOG(gFontLog, PR_LOG_DEBUG, ("Computing ranges for string: (len = %d)", mItemLength));
 
@@ -1677,41 +1723,42 @@ public:
 
             PR_LOG(gFontLog, PR_LOG_DEBUG, (" 0x%04x - ", ch));
             PRUint32 nextCh = 0;
             if (i+1 < mItemLength) {
                 nextCh = mItemString[i+1];
                 if ((i+2 < mItemLength) && NS_IS_HIGH_SURROGATE(nextCh) && NS_IS_LOW_SURROGATE(mItemString[i+2]))
                     nextCh = SURROGATE_TO_UCS4(nextCh, mItemString[i+2]);
             }
-            nsRefPtr<FontEntry> fe = FindFontForChar(ch,
-                                                     prevCh,
-                                                     nextCh,
-                                                     (mRanges.Length() == 0) ? nsnull : mRanges[mRanges.Length() - 1].font);
+            nsRefPtr<gfxWindowsFont> font =
+                FindFontForChar(ch,
+                                prevCh,
+                                nextCh,
+                                (mRanges.Length() == 0) ? nsnull : mRanges[mRanges.Length() - 1].font);
 
             prevCh = ch;
 
             if (mRanges.Length() == 0) {
                 TextRange r(0,1);
-                r.font = fe;
+                r.font = font;
                 mRanges.AppendElement(r);
             } else {
                 TextRange& prevRange = mRanges[mRanges.Length() - 1];
-                if (prevRange.font != fe) {
+                if (prevRange.font != font) {
                     // close out the previous range
                     prevRange.end = origI;
 
                     TextRange r(origI, i+1);
-                    r.font = fe;
+                    r.font = font;
                     mRanges.AppendElement(r);
                 }
             }
             if (PR_LOG_TEST(gFontLog, PR_LOG_DEBUG)) {
-                if (fe)
-                    PR_LOG(gFontLog, PR_LOG_DEBUG, (" - Using %s", NS_LossyConvertUTF16toASCII(fe->GetName()).get()));
+                if (font)
+                    PR_LOG(gFontLog, PR_LOG_DEBUG, (" - Using %s", NS_LossyConvertUTF16toASCII(font->GetUniqueName()).get()));
                 else
                     PR_LOG(gFontLog, PR_LOG_DEBUG, (" - Unable to find font"));
             }
         }
         mRanges[mRanges.Length()-1].end = mItemLength;
 
         PRUint32 nranges = mRanges.Length();
         PR_LOG(gFontLog, PR_LOG_DEBUG, (" Found %d ranges", nranges));
--- a/gfx/thebes/src/gfxWindowsPlatform.cpp
+++ b/gfx/thebes/src/gfxWindowsPlatform.cpp
@@ -484,36 +484,40 @@ gfxWindowsPlatform::FindFontForCharProc(
         (rank == data->matchRank && Compare(fe->GetName(), data->bestMatch->GetName()) > 0)) {
         data->bestMatch = fe;
         data->matchRank = rank;
     }
 
     return PL_DHASH_NEXT;
 }
 
-
-FontEntry *
+already_AddRefed<gfxWindowsFont>
 gfxWindowsPlatform::FindFontForChar(PRUint32 aCh, gfxWindowsFont *aFont)
 {
     // is codepoint with no matching font? return null immediately
     if (mCodepointsWithNoFonts.test(aCh)) {
         return nsnull;
     }
 
     FontSearch data(aCh, aFont);
 
     // find fonts that support the character
     mFonts.Enumerate(gfxWindowsPlatform::FindFontForCharProc, &data);
 
-    // no match? add to set of non-matching codepoints
-    if (!data.bestMatch) {
-        mCodepointsWithNoFonts.set(aCh);
+    if (data.bestMatch) {
+        nsRefPtr<gfxWindowsFont> font =
+            gfxWindowsFont::GetOrMakeFont(data.bestMatch, aFont->GetStyle());
+        if (font->IsValid())
+            return font.forget();
+        return nsnull;
     }
 
-    return data.bestMatch;
+    // no match? add to set of non-matching codepoints
+    mCodepointsWithNoFonts.set(aCh);
+    return nsnull;
 }
 
 gfxFontGroup *
 gfxWindowsPlatform::CreateFontGroup(const nsAString &aFamilies,
                                     const gfxFontStyle *aStyle)
 {
     return new gfxWindowsFontGroup(aFamilies, aStyle);
 }
--- a/js/src/jsdbgapi.cpp
+++ b/js/src/jsdbgapi.cpp
@@ -115,16 +115,17 @@ js_UntrapScriptCode(JSContext *cx, JSScr
                 for (sn = notes; !SN_IS_TERMINATOR(sn); sn = SN_NEXT(sn))
                     continue;
                 nbytes += (sn - notes + 1) * sizeof *sn;
 
                 code = (jsbytecode *) JS_malloc(cx, nbytes);
                 if (!code)
                     break;
                 memcpy(code, script->code, nbytes);
+                JS_CLEAR_GSN_CACHE(cx);
             }
             code[trap->pc - script->code] = trap->op;
         }
     }
     DBG_UNLOCK(rt);
     return code;
 }
 
@@ -143,19 +144,21 @@ JS_SetTrap(JSContext *cx, JSScript *scri
     trap = FindTrap(rt, script, pc);
     if (trap) {
         JS_ASSERT(trap->script == script && trap->pc == pc);
         JS_ASSERT(*pc == JSOP_TRAP);
     } else {
         sample = rt->debuggerMutations;
         DBG_UNLOCK(rt);
         trap = (JSTrap *) JS_malloc(cx, sizeof *trap);
-        if (!trap || !js_AddRoot(cx, &trap->closure, "trap->closure")) {
-            if (trap)
-                JS_free(cx, trap);
+        if (!trap)
+            return JS_FALSE;
+        trap->closure = NULL;
+        if(!js_AddRoot(cx, &trap->closure, "trap->closure")) {
+            JS_free(cx, trap);
             return JS_FALSE;
         }
         DBG_LOCK(rt);
         twin = (rt->debuggerMutations != sample)
                ? FindTrap(rt, script, pc)
                : NULL;
         if (twin) {
             junk = trap;
@@ -167,18 +170,20 @@ JS_SetTrap(JSContext *cx, JSScript *scri
             trap->pc = pc;
             trap->op = (JSOp)*pc;
             *pc = JSOP_TRAP;
         }
     }
     trap->handler = handler;
     trap->closure = closure;
     DBG_UNLOCK(rt);
-    if (junk)
+    if (junk) {
+        js_RemoveRoot(rt, &junk->closure);
         JS_free(cx, junk);
+    }
     return JS_TRUE;
 }
 
 JS_PUBLIC_API(JSOp)
 JS_GetTrapOpcode(JSContext *cx, JSScript *script, jsbytecode *pc)
 {
     JSRuntime *rt;
     JSTrap *trap;
--- a/js/src/jsfun.cpp
+++ b/js/src/jsfun.cpp
@@ -1715,17 +1715,17 @@ fun_applyConstructor(JSContext *cx, uint
     *sp++ = JSVAL_NULL; /* this is filled automagically */
     for (i = 0; i < length; i++) {
         ok = JS_GetElement(cx, aobj, (jsint)i, sp);
         if (!ok)
             goto out;
         sp++;
     }
 
-    ok = js_InvokeConstructor(cx, invokevp, length);
+    ok = js_InvokeConstructor(cx, length, invokevp);
     *vp = *invokevp;
 out:
     js_FreeStack(cx, mark);
     return ok;
 }
 #endif
 
 static JSFunctionSpec function_methods[] = {
--- a/js/src/jsinterp.cpp
+++ b/js/src/jsinterp.cpp
@@ -847,16 +847,19 @@ js_ComputeThis(JSContext *cx, JSBool laz
 {
     if (JSVAL_IS_NULL(argv[-1]))
         return js_ComputeGlobalThis(cx, lazy, argv);
     return ComputeThis(cx, lazy, argv);
 }
 
 #if JS_HAS_NO_SUCH_METHOD
 
+#define JSSLOT_FOUND_FUNCTION   JSSLOT_PRIVATE
+#define JSSLOT_SAVED_ID         (JSSLOT_PRIVATE + 1)
+
 JSClass js_NoSuchMethodClass = {
     "NoSuchMethod",
     JSCLASS_HAS_RESERVED_SLOTS(2) | JSCLASS_IS_ANONYMOUS |
     JSCLASS_HAS_CACHED_PROTO(JSProto_NoSuchMethod),
     JS_PropertyStub,  JS_PropertyStub,  JS_PropertyStub,   JS_PropertyStub,
     JS_EnumerateStub, JS_ResolveStub,   JS_ConvertStub,    JS_FinalizeStub,
     NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL
 };
@@ -941,48 +944,59 @@ js_OnUnknownMethod(JSContext *cx, jsval 
                 vp[0] = ID_TO_VALUE(id);
         }
 #endif
         obj = js_NewObject(cx, &js_NoSuchMethodClass, NULL, NULL, 0);
         if (!obj) {
             ok = JS_FALSE;
             goto out;
         }
-        STOBJ_SET_SLOT(obj, JSSLOT_PRIVATE, tvr.u.value);
-        STOBJ_SET_SLOT(obj, JSSLOT_PRIVATE + 1, vp[0]);
+        obj->fslots[JSSLOT_FOUND_FUNCTION] = tvr.u.value;
+        obj->fslots[JSSLOT_SAVED_ID] = vp[0];
         vp[0] = OBJECT_TO_JSVAL(obj);
     }
     ok = JS_TRUE;
 
   out:
     JS_POP_TEMP_ROOT(cx, &tvr);
     return ok;
 }
 
 static JSBool
 NoSuchMethod(JSContext *cx, uintN argc, jsval *vp, uint32 flags)
 {
-    JSObject *obj, *thisp, *argsobj;
-    jsval fval, idval, args[2];
+    jsval *invokevp;
+    void *mark;
+    JSBool ok;
+    JSObject *obj, *argsobj;
+
+    invokevp = js_AllocStack(cx, 2 + 2, &mark);
+    if (!invokevp)
+        return JS_FALSE;
 
     JS_ASSERT(!JSVAL_IS_PRIMITIVE(vp[0]));
+    JS_ASSERT(!JSVAL_IS_PRIMITIVE(vp[1]));
     obj = JSVAL_TO_OBJECT(vp[0]);
     JS_ASSERT(STOBJ_GET_CLASS(obj) == &js_NoSuchMethodClass);
-    fval = OBJ_GET_SLOT(cx, obj, JSSLOT_PRIVATE);
-    idval = OBJ_GET_SLOT(cx, obj, JSSLOT_PRIVATE + 1);
-
-    JS_ASSERT(!JSVAL_IS_PRIMITIVE(vp[1]));
-    thisp = JSVAL_TO_OBJECT(vp[1]);
-
-    args[0] = idval;
+
+    invokevp[0] = obj->fslots[JSSLOT_FOUND_FUNCTION];
+    invokevp[1] = vp[1];
+    invokevp[2] = obj->fslots[JSSLOT_SAVED_ID];
     argsobj = js_NewArrayObject(cx, argc, vp + 2);
-    if (!argsobj)
-        return JS_FALSE;
-    args[1] = OBJECT_TO_JSVAL(argsobj);
-    return js_InternalInvoke(cx, thisp, fval, flags, 2, args, &vp[0]);
+    if (!argsobj) {
+        ok = JS_FALSE;
+    } else {
+        invokevp[3] = OBJECT_TO_JSVAL(argsobj);
+        ok = (flags & JSINVOKE_CONSTRUCT)
+             ? js_InvokeConstructor(cx, 2, invokevp)
+             : js_Invoke(cx, 2, invokevp, flags);
+        vp[0] = invokevp[0];
+    }
+    js_FreeStack(cx, mark);
+    return ok;
 }
 
 #endif /* JS_HAS_NO_SUCH_METHOD */
 
 /*
  * We check if the function accepts a primitive value as |this|. For that we
  * use a table that maps value's tag into the corresponding function flag.
  */
@@ -1797,17 +1811,17 @@ js_StrictlyEqual(JSContext *cx, jsval lv
         ld = JSVAL_TO_INT(lval);
         rd = *JSVAL_TO_DOUBLE(rval);
         return JSDOUBLE_COMPARE(ld, ==, rd, JS_FALSE);
     }
     return lval == rval;
 }
 
 JSBool
-js_InvokeConstructor(JSContext *cx, jsval *vp, uintN argc)
+js_InvokeConstructor(JSContext *cx, uintN argc, jsval *vp)
 {
     JSFunction *fun, *fun2;
     JSObject *obj, *obj2, *proto, *parent;
     jsval lval, rval;
     JSClass *clasp;
 
     fun = NULL;
     obj2 = NULL;
@@ -3799,17 +3813,17 @@ interrupt:
           END_CASE(JSOP_POS)
 
           BEGIN_CASE(JSOP_NEW)
             /* Get immediate argc and find the constructor function. */
             argc = GET_ARGC(regs.pc);
             vp = regs.sp - (2 + argc);
             JS_ASSERT(vp >= fp->spbase);
 
-            if (!js_InvokeConstructor(cx, vp, argc))
+            if (!js_InvokeConstructor(cx, argc, vp))
                 goto error;
             regs.sp = vp + 1;
             LOAD_INTERRUPT_HANDLER(cx);
           END_CASE(JSOP_NEW)
 
           BEGIN_CASE(JSOP_DELNAME)
             LOAD_ATOM(0);
             id = ATOM_TO_JSID(atom);
--- a/js/src/jsinterp.h
+++ b/js/src/jsinterp.h
@@ -450,17 +450,17 @@ extern JSBool
 js_InternalGetOrSet(JSContext *cx, JSObject *obj, jsid id, jsval fval,
                     JSAccessMode mode, uintN argc, jsval *argv, jsval *rval);
 
 extern JSBool
 js_Execute(JSContext *cx, JSObject *chain, JSScript *script,
            JSStackFrame *down, uintN flags, jsval *result);
 
 extern JSBool
-js_InvokeConstructor(JSContext *cx, jsval *vp, uintN argc);
+js_InvokeConstructor(JSContext *cx, uintN argc, jsval *vp);
 
 extern JSBool
 js_Interpret(JSContext *cx);
 
 #define JSPROP_INITIALIZER 0x100   /* NB: Not a valid property attribute. */
 
 extern JSBool
 js_CheckRedeclaration(JSContext *cx, JSObject *obj, jsid id, uintN attrs,
--- a/js/src/jsopcode.cpp
+++ b/js/src/jsopcode.cpp
@@ -1601,18 +1601,28 @@ InitSprintStack(JSContext *cx, SprintSta
     ss->opcodes = (jsbytecode *) ((char *)space + offsetsz);
 
     ss->top = ss->inArrayInit = 0;
     ss->inGenExp = JS_FALSE;
     ss->printer = jp;
     return JS_TRUE;
 }
 
-static JS_INLINE jsbytecode *
-DecompileBytecode(SprintStack *ss, jsbytecode *pc, intN nb, JSOp nextop)
+/*
+ * If nb is non-negative, decompile nb bytecodes starting at pc.  Otherwise
+ * the decompiler starts at pc and continues until it reaches an opcode for
+ * which decompiling would result in the stack depth equaling -(nb + 1).
+ *
+ * The nextop parameter is either JSOP_NOP or the "next" opcode in order of
+ * abstract interpretation (not necessarily physically next in a bytecode
+ * vector). So nextop is JSOP_POP for the last operand in a comma expression,
+ * or JSOP_AND for the right operand of &&.
+ */
+static jsbytecode *
+Decompile(SprintStack *ss, jsbytecode *pc, intN nb, JSOp nextop)
 {
     JSContext *cx;
     JSPrinter *jp, *jp2;
     jsbytecode *startpc, *endpc, *pc2, *done, *forelem_tail, *forelem_done;
     ptrdiff_t tail, todo, len, oplen, cond, next;
     JSOp op, lastop, saveop;
     const JSCodeSpec *cs;
     jssrcnote *sn, *sn2;
@@ -1709,16 +1719,17 @@ DecompileBytecode(SprintStack *ss, jsbyt
  */
 #define GET_ATOM_QUOTE_AND_FMT(qfmt, ufmt, rval)                              \
     JS_BEGIN_MACRO                                                            \
         LOAD_ATOM(0);                                                         \
         GET_QUOTE_AND_FMT(qfmt, ufmt, rval);                                  \
     JS_END_MACRO
 
     cx = ss->sprinter.context;
+    JS_CHECK_RECURSION(cx, return NULL);
 
     jp = ss->printer;
     startpc = pc;
     endpc = (nb < 0) ? jp->script->code + jp->script->length : pc + nb;
     forelem_tail = forelem_done = NULL;
     tail = -1;
     todo = -2;                  /* NB: different from Sprint() error return. */
     saveop = JSOP_NOP;
@@ -4541,66 +4552,27 @@ DecompileBytecode(SprintStack *ss, jsbyt
 #undef LOCAL_ASSERT
 #undef ATOM_IS_IDENTIFIER
 #undef GET_QUOTE_AND_FMT
 #undef GET_ATOM_QUOTE_AND_FMT
 
     return pc;
 }
 
-/*
- * If nb is non-negative, decompile nb bytecodes starting at pc.  Otherwise
- * the decompiler starts at pc and continues until it reaches an opcode for
- * which decompiling would result in the stack depth equaling -(nb + 1).
- *
- * The nextop parameter is either JSOP_NOP or the "next" opcode in order of
- * abstract interpretation (not necessarily physically next in a bytecode
- * vector). So nextop is JSOP_POP for the last operand in a comma expression,
- * or JSOP_AND for the right operand of &&.
- */
-static jsbytecode *
-Decompile(SprintStack *ss, jsbytecode *pc, intN nb, JSOp nextop)
-{
-    JSContext *cx;
-    JSPrinter *jp;
-    jsbytecode *oldcode, *oldmain, *code;
-
-    cx = ss->sprinter.context;
-    JS_CHECK_RECURSION(cx, return NULL);
-
-    jp = ss->printer;
-    oldcode = jp->script->code;
-    oldmain = jp->script->main;
-    code = js_UntrapScriptCode(cx, jp->script);
-    if (code != oldcode) {
-        jp->script->code = code;
-        jp->script->main = code + (oldmain - jp->script->code);
-        pc = code + (pc - oldcode);
-    }
-
-    pc = DecompileBytecode(ss, pc, nb, nextop);
-
-    if (code != oldcode) {
-        JS_free(cx, jp->script->code);
-        jp->script->code = oldcode;
-        jp->script->main = oldmain;
-    }
-    return (pc ? pc - code + oldcode : NULL);
-}
-
 static JSBool
 DecompileCode(JSPrinter *jp, JSScript *script, jsbytecode *pc, uintN len,
               uintN pcdepth)
 {
     uintN depth, i;
     SprintStack ss;
     JSContext *cx;
     void *mark;
     JSBool ok;
     JSScript *oldscript;
+    jsbytecode *oldcode, *oldmain, *code;
     char *last;
 
     depth = script->depth;
     JS_ASSERT(pcdepth <= depth);
 
     /* Initialize a sprinter for use with the offset stack. */
     cx = jp->sprinter.context;
     mark = JS_ARENA_MARK(&cx->tempPool);
@@ -4625,21 +4597,35 @@ DecompileCode(JSPrinter *jp, JSScript *s
             ss.offsets[i] = -2 - (ptrdiff_t)i;
             ss.opcodes[i] = *jp->pcstack[i];
         }
     }
 
     /* Call recursive subroutine to do the hard work. */
     oldscript = jp->script;
     jp->script = script;
+    oldcode = jp->script->code;
+    oldmain = jp->script->main;
+    code = js_UntrapScriptCode(cx, jp->script);
+    if (code != oldcode) {
+        jp->script->code = code;
+        jp->script->main = code + (oldmain - jp->script->code);
+        pc = code + (pc - oldcode);
+    }
+
     ok = Decompile(&ss, pc, len, JSOP_NOP) != NULL;
+    if (code != oldcode) {
+        JS_free(cx, jp->script->code);
+        jp->script->code = oldcode;
+        jp->script->main = oldmain;
+    }
     jp->script = oldscript;
 
     /* If the given code didn't empty the stack, do it now. */
-    if (ss.top) {
+    if (ok && ss.top) {
         do {
             last = OFF2STR(&ss.sprinter, PopOff(&ss, JSOP_POP));
         } while (ss.top > pcdepth);
         js_printf(jp, "%s", last);
     }
 
 out:
     /* Free all temporary stuff allocated under this call. */
--- a/js/src/xpconnect/src/XPCCrossOriginWrapper.cpp
+++ b/js/src/xpconnect/src/XPCCrossOriginWrapper.cpp
@@ -335,16 +335,21 @@ XPC_XOW_FunctionWrapper(JSContext *cx, J
     return JS_FALSE;
   }
 
   JSFunction *fun = JS_ValueToFunction(cx, funToCall);
   if (!fun) {
     return ThrowException(NS_ERROR_ILLEGAL_VALUE, cx);
   }
 
+  XPCCallContext ccx(JS_CALLER, cx);
+  if (!ccx.IsValid()) {
+    return ThrowException(NS_ERROR_FAILURE, cx);
+  }
+
   nsresult rv = CanAccessWrapper(cx, JSVAL_TO_OBJECT(funToCall));
   if (NS_FAILED(rv) && rv != NS_ERROR_DOM_PROP_ACCESS_DENIED) {
     return ThrowException(rv, cx);
   }
 
   JSNative native = JS_GetFunctionNative(cx, fun);
   NS_ASSERTION(native, "How'd we get here with a scripted function?");
 
@@ -553,16 +558,22 @@ XPC_XOW_AddProperty(JSContext *cx, JSObj
     // Allow us to define a property on ourselves.
     return JS_TRUE;
   }
 
   JSObject *wrappedObj = GetWrappedObject(cx, obj);
   if (!wrappedObj) {
     return ThrowException(NS_ERROR_ILLEGAL_VALUE, cx);
   }
+
+  XPCCallContext ccx(JS_CALLER, cx);
+  if (!ccx.IsValid()) {
+    return ThrowException(NS_ERROR_FAILURE, cx);
+  }
+
   nsresult rv = CanAccessWrapper(cx, wrappedObj);
   if (NS_FAILED(rv)) {
     if (rv == NS_ERROR_DOM_PROP_ACCESS_DENIED) {
       // Can't override properties on foreign objects.
       return ThrowException(rv, cx);
     }
     return JS_FALSE;
   }
@@ -573,16 +584,22 @@ XPC_XOW_AddProperty(JSContext *cx, JSObj
 
 JS_STATIC_DLL_CALLBACK(JSBool)
 XPC_XOW_DelProperty(JSContext *cx, JSObject *obj, jsval id, jsval *vp)
 {
   JSObject *wrappedObj = GetWrappedObject(cx, obj);
   if (!wrappedObj) {
     return ThrowException(NS_ERROR_ILLEGAL_VALUE, cx);
   }
+
+  XPCCallContext ccx(JS_CALLER, cx);
+  if (!ccx.IsValid()) {
+    return ThrowException(NS_ERROR_FAILURE, cx);
+  }
+
   nsresult rv = CanAccessWrapper(cx, wrappedObj);
   if (NS_FAILED(rv)) {
     if (rv == NS_ERROR_DOM_PROP_ACCESS_DENIED) {
       // Can't delete properties on foreign objects.
       return ThrowException(rv, cx);
     }
     return JS_FALSE;
   }
@@ -736,16 +753,22 @@ JS_STATIC_DLL_CALLBACK(JSBool)
 XPC_XOW_Enumerate(JSContext *cx, JSObject *obj)
 {
   obj = GetWrapper(obj);
   JSObject *wrappedObj = GetWrappedObject(cx, obj);
   if (!wrappedObj) {
     // Nothing to enumerate.
     return JS_TRUE;
   }
+
+  XPCCallContext ccx(JS_CALLER, cx);
+  if (!ccx.IsValid()) {
+    return ThrowException(NS_ERROR_FAILURE, cx);
+  }
+
   nsresult rv = CanAccessWrapper(cx, wrappedObj);
   if (NS_FAILED(rv)) {
     if (rv == NS_ERROR_DOM_PROP_ACCESS_DENIED) {
       // Can't enumerate on foreign objects.
       return ThrowException(rv, cx);
     }
 
     return JS_FALSE;
@@ -762,16 +785,21 @@ XPC_XOW_NewResolve(JSContext *cx, JSObje
 
   JSObject *wrappedObj = GetWrappedObject(cx, obj);
   if (!wrappedObj) {
     // No wrappedObj means that this is probably the prototype.
     *objp = nsnull;
     return JS_TRUE;
   }
 
+  XPCCallContext ccx(JS_CALLER, cx);
+  if (!ccx.IsValid()) {
+    return ThrowException(NS_ERROR_FAILURE, cx);
+  }
+
   nsresult rv = CanAccessWrapper(cx, wrappedObj);
   if (NS_FAILED(rv)) {
     if (rv != NS_ERROR_DOM_PROP_ACCESS_DENIED) {
       return JS_FALSE;
     }
 
     // We're dealing with a cross-origin lookup. Ensure that we're allowed to
     // resolve this property and resolve it if so. Otherwise, we deny access
@@ -841,16 +869,21 @@ XPC_XOW_Convert(JSContext *cx, JSObject 
     if (type == JSTYPE_STRING || type == JSTYPE_VOID) {
       return XPC_XOW_toString(cx, obj, 0, nsnull, vp);
     }
 
     *vp = OBJECT_TO_JSVAL(obj);
     return JS_TRUE;
   }
 
+  XPCCallContext ccx(JS_CALLER, cx);
+  if (!ccx.IsValid()) {
+    return ThrowException(NS_ERROR_FAILURE, cx);
+  }
+
   // Note: JSTYPE_VOID and JSTYPE_STRING are equivalent.
   nsresult rv = CanAccessWrapper(cx, wrappedObj);
   if (NS_FAILED(rv) &&
       (rv != NS_ERROR_DOM_PROP_ACCESS_DENIED ||
        (type != JSTYPE_STRING && type != JSTYPE_VOID))) {
     // Ensure that we report some kind of error.
     if (rv == NS_ERROR_DOM_PROP_ACCESS_DENIED) {
       ThrowException(rv, cx);
@@ -910,16 +943,22 @@ XPC_XOW_CheckAccess(JSContext *cx, JSObj
 JS_STATIC_DLL_CALLBACK(JSBool)
 XPC_XOW_Call(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval)
 {
   JSObject *wrappedObj = GetWrappedObject(cx, obj);
   if (!wrappedObj) {
     // Nothing to call.
     return JS_TRUE;
   }
+
+  XPCCallContext ccx(JS_CALLER, cx);
+  if (!ccx.IsValid()) {
+    return ThrowException(NS_ERROR_FAILURE, cx);
+  }
+
   nsresult rv = CanAccessWrapper(cx, wrappedObj);
   if (NS_FAILED(rv)) {
     if (rv == NS_ERROR_DOM_PROP_ACCESS_DENIED) {
       // Can't call.
       return ThrowException(rv, cx);
     }
 
     return JS_FALSE;
@@ -941,16 +980,22 @@ XPC_XOW_Construct(JSContext *cx, JSObjec
                   jsval *rval)
 {
   JSObject *realObj = GetWrapper(JSVAL_TO_OBJECT(argv[-2]));
   JSObject *wrappedObj = GetWrappedObject(cx, realObj);
   if (!wrappedObj) {
     // Nothing to construct.
     return JS_TRUE;
   }
+
+  XPCCallContext ccx(JS_CALLER, cx);
+  if (!ccx.IsValid()) {
+    return ThrowException(NS_ERROR_FAILURE, cx);
+  }
+
   nsresult rv = CanAccessWrapper(cx, wrappedObj);
   if (NS_FAILED(rv)) {
     if (rv == NS_ERROR_DOM_PROP_ACCESS_DENIED) {
       // Can't construct.
       return ThrowException(rv, cx);
     }
     return JS_FALSE;
   }
@@ -965,16 +1010,22 @@ XPC_XOW_Construct(JSContext *cx, JSObjec
 
   return XPC_XOW_RewrapIfNeeded(cx, callee, rval);
 }
 
 JS_STATIC_DLL_CALLBACK(JSBool)
 XPC_XOW_HasInstance(JSContext *cx, JSObject *obj, jsval v, JSBool *bp)
 {
   JSObject *iface = GetWrappedObject(cx, obj);
+
+  XPCCallContext ccx(JS_CALLER, cx);
+  if (!ccx.IsValid()) {
+    return ThrowException(NS_ERROR_FAILURE, cx);
+  }
+
   nsresult rv = CanAccessWrapper(cx, iface);
   if (NS_FAILED(rv)) {
     if (rv == NS_ERROR_DOM_PROP_ACCESS_DENIED) {
       // Don't do this test across origins.
       return ThrowException(rv, cx);
     }
     return JS_FALSE;
   }
@@ -1044,16 +1095,23 @@ XPC_XOW_Equality(JSContext *cx, JSObject
 JS_STATIC_DLL_CALLBACK(JSObject *)
 XPC_XOW_Iterator(JSContext *cx, JSObject *obj, JSBool keysonly)
 {
   JSObject *wrappedObj = GetWrappedObject(cx, obj);
   if (!wrappedObj) {
     ThrowException(NS_ERROR_INVALID_ARG, cx);
     return nsnull;
   }
+
+  XPCCallContext ccx(JS_CALLER, cx);
+  if (!ccx.IsValid()) {
+    ThrowException(NS_ERROR_FAILURE, cx);
+    return nsnull;
+  }
+
   nsresult rv = CanAccessWrapper(cx, wrappedObj);
   if (NS_FAILED(rv)) {
     if (rv == NS_ERROR_DOM_PROP_ACCESS_DENIED) {
       // Can't create iterators for foreign objects.
       ThrowException(rv, cx);
       return nsnull;
     }
 
@@ -1106,16 +1164,21 @@ XPC_XOW_toString(JSContext *cx, JSObject
       JS_NewStringCopyN(cx, protoString.get(), protoString.Length());
     if (!str) {
       return JS_FALSE;
     }
     *rval = STRING_TO_JSVAL(str);
     return JS_TRUE;
   }
 
+  XPCCallContext ccx(JS_CALLER, cx);
+  if (!ccx.IsValid()) {
+    return ThrowException(NS_ERROR_FAILURE, cx);
+  }
+
   nsresult rv = CanAccessWrapper(cx, wrappedObj);
   if (rv == NS_ERROR_DOM_PROP_ACCESS_DENIED) {
     nsIScriptSecurityManager *ssm = XPCWrapper::GetSecurityManager();
     if (!ssm) {
       return ThrowException(NS_ERROR_NOT_INITIALIZED, cx);
     }
     rv = ssm->CheckPropertyAccess(cx, wrappedObj,
                                   STOBJ_GET_CLASS(wrappedObj)->name,
new file mode 100755
--- /dev/null
+++ b/js/tests/js1_5/extensions/regress-431428.js
@@ -0,0 +1,70 @@
+/* -*- 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 JavaScript Engine testing utilities.
+ *
+ * The Initial Developer of the Original Code is
+ * Mozilla Foundation.
+ * Portions created by the Initial Developer are Copyright (C) 2007
+ * the Initial Developer. All Rights Reserved.
+ *
+ * Contributor(s): Jesse Ruderman
+ *
+ * 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 ***** */
+
+var gTestfile = 'regress-431428.js';
+//-----------------------------------------------------------------------------
+var BUGNUMBER = 431428;
+var summary = 'Do not crash with for..in, trap';
+var actual = 'No Crash';
+var expect = 'No Crash';
+
+
+//-----------------------------------------------------------------------------
+test();
+//-----------------------------------------------------------------------------
+
+function test()
+{
+  enterFunc ('test');
+  printBugNumber(BUGNUMBER);
+  printStatus (summary);
+ 
+  function f() { 
+    for ( var a in [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17]) { }
+  }
+
+  if (typeof trap == 'function')
+  {
+    "" + f;
+    trap(f, 0, "");
+    "" + f;
+  }
+
+  reportCompare(expect, actual, summary);
+
+  exitFunc ('test');
+}
--- a/layout/printing/nsPrintEngine.cpp
+++ b/layout/printing/nsPrintEngine.cpp
@@ -2196,16 +2196,37 @@ nsPrintEngine::DoPrint(nsPrintObject * a
             mPrt->mPrintSettings->GetMarginInTwips(marginTwips);
             mPrt->mPrintSettings->GetUnwriteableMarginInTwips(unwrtMarginTwips);
             nsMargin totalMargin = poPresContext->TwipsToAppUnits(marginTwips + 
                                                               unwrtMarginTwips);
             if (startPageNum == endPageNum) {
               {
                 startRect.y -= totalMargin.top;
                 endRect.y   -= totalMargin.top;
+
+                // Clip out selection regions above the top of the first page
+                if (startRect.y < 0) {
+                  // Reduce height to be the height of the positive-territory
+                  // region of original rect
+                  startRect.height = PR_MAX(0, startRect.YMost());
+                  startRect.y = 0;
+                }
+                if (endRect.y < 0) {
+                  // Reduce height to be the height of the positive-territory
+                  // region of original rect
+                  endRect.height = PR_MAX(0, endRect.YMost());
+                  endRect.y = 0;
+                }
+                NS_ASSERTION(endRect.y >= startRect.y,
+                             "Selection end point should be after start point");
+                NS_ASSERTION(startRect.height >= 0,
+                             "rect should have non-negative height.");
+                NS_ASSERTION(endRect.height >= 0,
+                             "rect should have non-negative height.");
+
                 nscoord selectionHgt = endRect.y + endRect.height - startRect.y;
                 // XXX This is temporary fix for printing more than one page of a selection
                 pageSequence->SetSelectionHeight(startRect.y * aPO->mZoomRatio,
                                                  selectionHgt * aPO->mZoomRatio);
 
                 // calc total pages by getting calculating the selection's height
                 // and then dividing it by how page content frames will fit.
                 nscoord pageWidth, pageHeight;
--- a/layout/style/nsCSSKeywordList.h
+++ b/layout/style/nsCSSKeywordList.h
@@ -556,16 +556,18 @@ CSS_KEY(groupbox, groupbox)
 CSS_KEY(checkbox-container, checkboxcontainer)
 CSS_KEY(radio-container, radiocontainer)
 CSS_KEY(checkbox-label, checkboxlabel)
 CSS_KEY(radio-label, radiolabel)
 CSS_KEY(button-focus, buttonfocus)
 CSS_KEY(media-toolbox, media_toolbox)
 CSS_KEY(communications-toolbox, communications_toolbox)
 CSS_KEY(browsertabbar-toolbox, browsertabbar_toolbox)
+CSS_KEY(-moz-win-mediatext, _moz_win_mediatext)
+CSS_KEY(-moz-win-communicationstext, _moz_win_communicationstext)
 
 #ifdef MOZ_SVG
 //CSS_KEY(all, all)
 CSS_KEY(alphabetic, alphabetic)
 //CSS_KEY(auto, auto)
 CSS_KEY(bevel, bevel)
 CSS_KEY(butt, butt)
 CSS_KEY(central, central)
--- a/layout/tools/reftest/reftest.js
+++ b/layout/tools/reftest/reftest.js
@@ -46,29 +46,33 @@ const NS_LOCAL_FILE_CONTRACTID = "@mozil
 const IO_SERVICE_CONTRACTID = "@mozilla.org/network/io-service;1";
 const NS_LOCALFILEINPUTSTREAM_CONTRACTID =
           "@mozilla.org/network/file-input-stream;1";
 const NS_SCRIPTSECURITYMANAGER_CONTRACTID =
           "@mozilla.org/scriptsecuritymanager;1";
 const NS_REFTESTHELPER_CONTRACTID =
           "@mozilla.org/reftest-helper;1";
 
-const LOAD_FAILURE_TIMEOUT = 120000; // ms
+const LOAD_FAILURE_TIMEOUT = 150000; // ms
 
 var gBrowser;
 var gCanvas1, gCanvas2;
 var gURLs;
 var gState;
 var gFailureTimeout;
 var gServer;
 var gCount = 0;
 
 var gIOService;
 var gReftestHelper;
 
+var gCurrentTestStartTime;
+var gSlowestTestTime = 0;
+var gSlowestTestURL;
+
 const EXPECTED_PASS = 0;
 const EXPECTED_FAIL = 1;
 const EXPECTED_RANDOM = 2;
 const EXPECTED_DEATH = 3;  // test must be skipped to avoid e.g. crash/hang
 const EXPECTED_LOAD = 4; // test without a reference (just test that it does
                          // not assert, crash, hang, or leak)
 
 const HTTP_SERVER_PORT = 4444;
@@ -284,24 +288,28 @@ function StartCurrentTest()
     if (gURLs.length == 0)
         DoneTests();
     else
         StartCurrentURI(1);
 }
 
 function StartCurrentURI(aState)
 {
+    gCurrentTestStartTime = Date.now();
     gFailureTimeout = setTimeout(LoadFailed, LOAD_FAILURE_TIMEOUT);
 
     gState = aState;
     gBrowser.loadURI(gURLs[0]["url" + aState].spec);
 }
 
 function DoneTests()
 {
+    dump("REFTEST FINISHED: Slowest test took " + gSlowestTestTime +
+         "ms (" + gSlowestTestURL + ")\n");
+
     if (gServer)
         gServer.stop();
     goQuitApplication();
 }
 
 function CanvasToURL(canvas)
 {
     var ctx = whichCanvas.getContext("2d");
@@ -373,16 +381,23 @@ function OnDocumentLoad(event)
         // first to get us after the onload has fired in the content, and
         // the second to get us after any setTimeout(foo, 0) in the content.
         setTimeout(setTimeout, 0, DocumentLoaded, 0);
     }
 }
 
 function DocumentLoaded()
 {
+    // Keep track of which test was slowest, and how long it took.
+    var currentTestRunTime = Date.now() - gCurrentTestStartTime;
+    if (currentTestRunTime > gSlowestTestTime) {
+        gSlowestTestTime = currentTestRunTime;
+        gSlowestTestURL  = gURLs[0]["url" + gState].spec;
+    }
+
     clearTimeout(gFailureTimeout);
 
     if (gURLs[0].expected == EXPECTED_LOAD) {
         dump("REFTEST PASS (LOAD ONLY): " + gURLs[0].prettyPath + "\n");
         gURLs.shift();
         StartCurrentTest();
         return;
     }
--- a/layout/xul/base/src/nsMenuPopupFrame.cpp
+++ b/layout/xul/base/src/nsMenuPopupFrame.cpp
@@ -1189,61 +1189,54 @@ nsMenuPopupFrame::SetPopupPosition(nsIFr
       PRInt32 moveDistX = screenLeftTwips - screenViewLocX;
       xpos += moveDistX;
       screenViewLocX += moveDistX;
     }
     if ( (screenViewLocX + mRect.width) > screenRightTwips )
       xpos -= (screenViewLocX + mRect.width) - screenRightTwips;
 
     // Now the Y position.  If the popup is up too high, slide it down so it's
-    // on screen.
+    // on screen. This can't make the popup overlap screenViewLocX/Y since
+    // we're moving it down away from screenViewLocY.
     if ( screenViewLocY < screenTopTwips ) {
       PRInt32 moveDistY = screenTopTwips - screenViewLocY;
       ypos += moveDistY;
       screenViewLocY += moveDistY;
     }
 
     // Now if the popup extends down too far, either resize it or flip it to be
     // above the anchor point and resize it to fit above, depending on where we
-    // have more room.
+    // have more room. But ensure it doesn't overlap screenViewLocX/Y.
     if ( (screenViewLocY + mRect.height) > screenBottomTwips ) {
       // XXXbz it'd be good to make use of IsMoreRoomOnOtherSideOfParent and
       // such here, but that's really focused on having a nonempty parent
       // rect...
-      if (screenViewLocY > screenBottomTwips) {
-        // if the popup is positioned off the edge, move it up. This is important
-        // when the popup is constrained to the content area so that the popup
-        // doesn't extend past the edge. This is a rare situation so include this
-        // check within the other.
-
-        // we already constrained the height to the screen size above, so this
-        // calculation should always result in a y position below the top.
-        NS_ASSERTION(mRect.height <= screenBottomTwips - screenTopTwips, "height too large");
-        ypos += screenBottomTwips - screenViewLocY - mRect.height;
-      }
-      else if (screenBottomTwips - screenViewLocY >
-               screenViewLocY - screenTopTwips) {
+      if (screenBottomTwips - screenViewLocY > screenViewLocY - screenTopTwips) {
         // More space below our desired point.  Resize to fit in this space.
         // Note that this is making mRect smaller; othewise we would not have
         // reached this code.
         mRect.height = screenBottomTwips - screenViewLocY;
       } else {
         // More space above our desired point.  Flip and resize to fit in this
         // space.
-        // First move screenViewLocY and ypos up because the offset needs to flip
-        screenViewLocY -= 2*offsetForContextMenu;
-        ypos -= 2*offsetForContextMenu;
-        if (mRect.height > screenViewLocY - screenTopTwips) {
+        // First figure out where the bottom of the popup is going to be.
+        nscoord newBottomY =
+          screenViewLocY - 2*offsetForContextMenu - margin.TopBottom();
+        // Make sure the bottom is on the screen
+        newBottomY = PR_MIN(newBottomY, screenBottomTwips);
+        newBottomY = PR_MAX(newBottomY, screenTopTwips);
+        if (mRect.height > newBottomY - screenTopTwips) {
           // We wouldn't fit.  Shorten before flipping.
-          mRect.height = screenViewLocY - screenTopTwips;
+          mRect.height = newBottomY - screenTopTwips;
         }
-        ypos -= (mRect.height + margin.top + margin.bottom);
+        // Adjust ypos to match
+        ypos += newBottomY - screenViewLocY - mRect.height;
       }
     }
-  }  
+  }
 
   presContext->GetViewManager()->MoveViewTo(GetView(), xpos, ypos); 
 
   // Now that we've positioned the view, sync up the frame's origin.
   nsPoint frameOrigin = GetPosition();
   nsPoint offsetToView;
   GetOriginToViewOffset(offsetToView, nsnull);
   frameOrigin -= offsetToView;
--- a/memory/jemalloc/Makefile.in
+++ b/memory/jemalloc/Makefile.in
@@ -78,16 +78,22 @@ else
 # Using a pre-built DLL, so just install it.
 libs:: $(WIN32_CUSTOM_CRT_DIR)/mozcrt19.dll
 	$(INSTALL) $< $(FINAL_TARGET)
 endif
 
 else
 
 MODULE_OPTIMIZE_FLAGS = -O2
+ifeq ($(OS_ARCH),SunOS)
+ifndef GNU_CC
+MODULE_OPTIMIZE_FLAGS = -xO5
+endif
+endif
+
 LIBRARY_NAME	= jemalloc
 
 ifeq (Darwin,$(OS_TARGET))
 # Build jemalloc as a shared lib, so that the library init function is executed.
 FORCE_SHARED_LIB= 1
 else
 # Make jemalloc part of libxul, in order to reduce dynamic loading overhead.
 MODULE		= jemalloc
--- a/memory/jemalloc/jemalloc.c
+++ b/memory/jemalloc/jemalloc.c
@@ -238,17 +238,19 @@ typedef unsigned char uint8_t;
 typedef unsigned uint32_t;
 typedef unsigned long long uint64_t;
 typedef unsigned long long uintmax_t;
 
 #define	MALLOC_DECOMMIT
 #endif
 
 #ifndef MOZ_MEMORY_WINDOWS
+#ifndef MOZ_MEMORY_SOLARIS
 #include <sys/cdefs.h>
+#endif
 #ifndef __DECONST
 #  define __DECONST(type, var)	((type)(uintptr_t)(const void *)(var))
 #endif
 #ifndef MOZ_MEMORY
 __FBSDID("$FreeBSD: src/lib/libc/stdlib/malloc.c,v 1.162 2008/02/06 02:59:54 jasone Exp $");
 #include "libc_private.h"
 #ifdef MALLOC_DEBUG
 #  define _LOCK_DEBUG
@@ -261,17 +263,19 @@ typedef unsigned long long uintmax_t;
 #  define MADV_FREE	MADV_DONTNEED
 #endif
 #include <sys/param.h>
 #ifndef MOZ_MEMORY
 #include <sys/stddef.h>
 #endif
 #include <sys/time.h>
 #include <sys/types.h>
+#ifndef MOZ_MEMORY_SOLARIS
 #include <sys/sysctl.h>
+#endif
 #include "tree.h"
 #ifndef MOZ_MEMORY
 #include <sys/tree.h>
 #endif
 #include <sys/uio.h>
 #ifndef MOZ_MEMORY
 #include <sys/ktrace.h> /* Must come after several other sys/ includes. */
 
@@ -342,17 +346,17 @@ static const bool __isthreaded = true;
    /* Disable inlining to make debugging easier. */
 #ifdef inline
 #undef inline
 #endif
 
 #  define inline
 #endif
 
-#ifndef MOZ_MEMORY_WINDOWS
+#ifdef __GNUC__
 #define	VISIBLE __attribute__((visibility("default")))
 #else
 #define	VISIBLE
 #endif
 
 /* Size of stack-allocated buffer passed to strerror_r(). */
 #define	STRERROR_BUF		64
 
@@ -1024,16 +1028,18 @@ static chunk_stats_t	stats_chunks;
  */
 const char	*_malloc_options
 #ifdef MOZ_MEMORY_WINDOWS
 = "A10n2F"
 #elif (defined(MOZ_MEMORY_DARWIN))
 = "AP10n"
 #elif (defined(MOZ_MEMORY_LINUX))
 = "A10n2F"
+#elif (defined(MOZ_MEMORY_SOLARIS))
+= "A10n2F"
 #endif
 ;
 
 #ifndef MALLOC_PRODUCTION
 static bool	opt_abort = true;
 #ifdef MALLOC_FILL
 static bool	opt_junk = true;
 #endif
@@ -4979,63 +4985,21 @@ malloc_ncpus(void)
 	error = host_processor_info(mach_host_self(), PROCESSOR_BASIC_INFO,
 				    &n, &pinfo, &pinfocnt);
 	if (error != KERN_SUCCESS)
 		return (1); /* Error. */
 	else
 		return (n);
 }
 #elif (defined(MOZ_MEMORY_SOLARIS))
-#include <kstat.h>
 
 static inline unsigned
 malloc_ncpus(void)
 {
-	unsigned ret;
-	kstat_ctl_t *ctl;
-	kstat_t *kstat;
-	kstat_named_t *named;
-	unsigned i;
-
-	if ((ctl = kstat_open()) == NULL)
-		return (1); /* Error. */
-
-	if ((kstat = kstat_lookup(ctl, "unix", -1, "system_misc")) == NULL)
-		return (1); /* Error. */
-
-	if (kstat_read(ctl, kstat, NULL) == -1)
-		return (1); /* Error. */
-
-	named = KSTAT_NAMED_PTR(kstat);
-
-	for (i = 0; i < kstat->ks_ndata; i++) {
-		if (strcmp(named[i].name, "ncpus") == 0) {
-			/* Figure out which one of these to actually use. */
-			switch(named[i].data_type) {
-			case KSTAT_DATA_INT32:
-				ret = named[i].value.i32;
-				break;
-			case KSTAT_DATA_UINT32:
-				ret = named[i].value.ui32;
-				break;
-			case KSTAT_DATA_INT64:
-				ret = named[i].value.i64;
-				break;
-			case KSTAT_DATA_UINT64:
-				ret = named[i].value.ui64;
-				break;
-			default:
-				return (1); /* Error. */
-			}
-		}
-	}
-
-	kstat_close(ctl); /* Don't bother checking for an error. */
-
-	return (ret);
+	return sysconf(_SC_NPROCESSORS_ONLN);
 }
 #else
 static inline unsigned
 malloc_ncpus(void)
 {
 
 	/*
 	 * We lack a way to determine the number of CPUs on this platform, so
@@ -5792,90 +5756,95 @@ RETURN:
 #endif
 		errno = ENOMEM;
 	}
 
 	UTRACE(0, size, ret);
 	return (ret);
 }
 
+#ifdef MOZ_MEMORY_DARWIN
+VISIBLE
+inline void *
+moz_memalign(size_t alignment, size_t size)
+#elif (defined(MOZ_MEMORY_SOLARIS))
+#  ifdef __SUNPRO_C
+void *
+memalign(size_t alignment, size_t size);
+#pragma no_inline(memalign)
+#  elif (defined(__GNU_C__)
+__attribute__((noinline))
+#  endif
+VISIBLE
+void *
+memalign(size_t alignment, size_t size)
+#else
+VISIBLE
+inline void *
+memalign(size_t alignment, size_t size)
+#endif
+{
+	void *ret;
+
+	assert(((alignment - 1) & alignment) == 0 && alignment >=
+	    sizeof(void *));
+
+	if (malloc_init()) {
+		ret = NULL;
+		goto RETURN;
+	}
+
+	ret = ipalloc(alignment, size);
+
+RETURN:
+#ifdef MALLOC_XMALLOC
+	if (opt_xmalloc && ret == NULL) {
+		_malloc_message(_getprogname(),
+		": (malloc) Error in memalign(): out of memory\n", "", "");
+		abort();
+	}
+#endif
+	UTRACE(0, size, ret);
+	return (ret);
+}
+
 VISIBLE
 #ifdef MOZ_MEMORY_DARWIN
 inline int
 moz_posix_memalign(void **memptr, size_t alignment, size_t size)
 #else
 int
 posix_memalign(void **memptr, size_t alignment, size_t size)
 #endif
 {
-	int ret;
 	void *result;
 
-	if (malloc_init())
-		result = NULL;
-	else {
-		/* Make sure that alignment is a large enough power of 2. */
-		if (((alignment - 1) & alignment) != 0
-		    || alignment < sizeof(void *)) {
-#ifdef MALLOC_XMALLOC
-			if (opt_xmalloc) {
-				_malloc_message(_getprogname(),
-				    ": (malloc) Error in posix_memalign(): "
-				    "invalid alignment\n", "", "");
-				abort();
-			}
-#endif
-			result = NULL;
-			ret = EINVAL;
-			goto RETURN;
-		}
-
-		result = ipalloc(alignment, size);
-	}
-
-	if (result == NULL) {
+	/* Make sure that alignment is a large enough power of 2. */
+	if (((alignment - 1) & alignment) != 0 || alignment < sizeof(void *)) {
 #ifdef MALLOC_XMALLOC
 		if (opt_xmalloc) {
 			_malloc_message(_getprogname(),
-			": (malloc) Error in posix_memalign(): out of memory\n",
-			"", "");
+			    ": (malloc) Error in posix_memalign(): "
+			    "invalid alignment\n", "", "");
 			abort();
 		}
 #endif
-		ret = ENOMEM;
-		goto RETURN;
+		return (EINVAL);
 	}
 
+#ifdef MOZ_MEMORY_DARWIN
+	result = moz_memalign(alignment, size);
+#else
+	result = memalign(alignment, size);
+#endif
+	if (result == NULL)
+		return (ENOMEM);
+
 	*memptr = result;
-	ret = 0;
-
-RETURN:
-	UTRACE(0, size, result);
-	return (ret);
-}
-
-VISIBLE
-#ifdef MOZ_MEMORY_DARWIN
-inline void *
-moz_memalign(size_t alignment, size_t size)
-#else
-void *
-memalign(size_t alignment, size_t size)
-#endif
-{
-	void *ret;
-
-#ifdef MOZ_MEMORY_DARWIN
-	if (moz_posix_memalign(&ret, alignment, size) != 0)
-#else
-	if (posix_memalign(&ret, alignment, size) != 0)
-#endif
-		return (NULL);
-
-	return ret;
+	return (0);
 }
 
 VISIBLE
 #ifdef MOZ_MEMORY_DARWIN
 inline void *
 moz_valloc(size_t size)
 #else
 void *
--- a/netwerk/streamconv/converters/nsIndexedToHTML.cpp
+++ b/netwerk/streamconv/converters/nsIndexedToHTML.cpp
@@ -469,47 +469,55 @@ nsIndexedToHTML::OnStartRequest(nsIReque
     nsCOMPtr<nsIURI> innerUri = NS_GetInnermostURI(uri);
     if (!innerUri)
         return NS_ERROR_UNEXPECTED;
     nsCOMPtr<nsIFileURL> fileURL(do_QueryInterface(innerUri));
     //XXX bug 388553: can't use skinnable icons here due to security restrictions
     if (fileURL) {
         //buffer.AppendLiteral("chrome://global/skin/dirListing/local.png");
         buffer.AppendLiteral("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAB"
-                             "AAAAAQCAYAAAAf8/9hAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZS"
-                             "BJbWFnZVJlYWR5ccllPAAAAWhJREFUeNrEk71KA0EQx/97uR"
-                             "A4CCIkNmIEO2NnYaOInc/gC1hHfAhLU0ewEi1S2YiFnRZWNh"
-                             "JTaFLEkySHgbtLvFzua929j1wC5hRSODDMMLPz29lhllBKMY"
-                             "8ImFPEl6vCKbOlGfly8aB1lEioXa7QWRLmkKQih1Cv8iM8t7"
-                             "EL1iFN6swHwPWYugDhU0kFR5ifL+746gsNYtypV0/4kycAmg"
-                             "YqEKjtNzhW/9fB5da3Id/vU12uVwKAKMIaqOgrClb3zmZXkv"
-                             "zYVZtV6PLxYQDwPAw1BVI2C9o7ny6KJkCmw3rzhpt3cRzotr"
-                             "CQKwC2Ex+O3j05xjBnah1ubgOAYcAxDaTTmWCYfDujQkJCG9"
-                             "KYcR0Trj3ilXc+YPDZZgEbmcUtICXF1/uQ8EoOCDsxlGcQIQ"
-                             "3qjh59wEfjCctrmxh2HuKCBIDarbHdsS+Y+8UB5V7jtcT0z/"
-                             "ufXZLYugjXgkgs8u+/8VuAAQBqe8GpcIXMpgAAAABJRU5Erk"
-                             "Jggg==");
+                             "AAAAAQCAYAAAAf8%2F9hAAAAGXRFWHRTb2Z0d2FyZQBBZG9i"
+                             "ZSBJbWFnZVJlYWR5ccllPAAAAjFJREFUeNqsU8uOElEQPffR"
+                             "3XQ3ONASdBJCSBxHos5%2B3Bg3rvkCv8PElS78gPkO%2FATj"
+                             "QoUdO2ftrJiRh6aneTb9sOpC4weMN6lcuFV16pxDIfI8x12O"
+                             "YIDhcPiu2Wx%2B%2FHF5CW1Z6Jyegt%2FTNEWSJIjjGFEUIQ"
+                             "xDrFYrWFSzXC4%2FdLvd95pRKpXKy%2BpRFZ7nwaWo1%2BsG"
+                             "nQG2260BKJfLKJVKGI1GEEJw7ateryd0v993W63WEwjgxfn5"
+                             "obGYzgCbzcaEbdsIggDj8Riu6z6iUk9SYZMSx8W0LMsM%2FS"
+                             "KK75xnJlIq80anQXdbEp0OhcPJ0eiaJnGRMEyyPDsAKKUM9c"
+                             "lkYoDo3SZJzzSdp0VSKYmfV1co%2Bz580kw5KDIM8RbRfEnU"
+                             "f1HzxtQyMAGcaGruTKczMzEIaqhKifV6jd%2BzGQQB5llunF"
+                             "%2FM52BizC2K5sYPYvZcu653tjOM9O93wnYc08gmkgg4VAxi"
+                             "xfqFUJT36AYBZGd6PJkFCZnnlBxMp38gqIgLpZB0y4Nph18l"
+                             "yWh5FFbrOSxbl3V4G%2BVB7T4ajYYxTyuLtO%2BCvWGgJE1M"
+                             "c7JNsJEhvgw%2FQV4fo%2F24nbEsX2u1d5sVyn8sJO0ZAQiI"
+                             "YnFh%2BxrfLz%2Fj29cBS%2FO14zg3i8XigW3ZkErDtmKoeM"
+                             "%2BAJGRMnXeEPGKf0nCD1ydvkDzU9Jbc6OpR7WIw6L8lQ%2B"
+                             "4pQ1%2FlPF0RGM9Ns91Wmptk0GfB4EJkt77vXYj%2F8m%2B8"
+                             "y%2FkrwABHbz2H9V68DQAAAABJRU5ErkJggg%3D%3D");
     } else {
         //buffer.AppendLiteral("chrome://global/skin/dirListing/remote.png");
         buffer.AppendLiteral("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAB"
-                             "AAAAAQCAYAAAAf8/9hAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZS"
-                             "BJbWFnZVJlYWR5ccllPAAAAdBJREFUeNqcUz1LA0EQfXsXDz"
-                             "8jKAERsQiYQuwEsbfwq7AWe/0FamVl6S84W7GxESvTi/4EGz"
-                             "VW2ojxI8ll9y6368yuCSYRURdmd9/uzJs3e3PCGIP9/TODf4"
-                             "y9vTWRaYL19dlvnYxxEycyENB8oIGjk5K9twT1dNiC09PLX2"
-                             "VeXJxr7VsK0lTjxctCrCwj1w+MsPUB2QAYIIsS4E0BV+E5Yp"
-                             "V2E8SJtqsmhSmr1EwK8HGNghPaUw6UKYmMG90ESazt5QA5Kr"
-                             "qvkwUUyE+Q8YGGdipsMpkiqnQQKGK9zUygQE41CujxPp2J0P"
-                             "dcdiZlH6ne2hUwm5KurmpMh5/BLD8iMs9zpTVLl7JBKjoUSO"
-                             "XqqiiHWTJzBkwgHEH8haBdQdUdrs4MkWeZtMLZN2OCfOT9A3"
-                             "2JTgVEMBbdwVAqbbStmfcOwzZQEyvCnv+FIFYCxfPoj40s3G"
-                             "yM+w3C8MJmqrwHmwyvr2Wb+/R0Ly9bQlQPSSB2dhc6GomeuC"
-                             "77bHA+H8D3a04+dYKhx8vnsyiV4tCYQSTJ62FXI0n3xOHS0r"
-                             "jF8/OTGB3tt/vn5wjlcoRCASgWH8OkYVoErRJ4bG8fm6enmx"
-                             "8rz+WmcHCwIZr4Q4ABAI8O/FsARX5sAAAAAElFTkSuQmCC");
+                             "AAAAAQCAYAAAAf8%2F9hAAAAGXRFWHRTb2Z0d2FyZQBBZG9i"
+                             "ZSBJbWFnZVJlYWR5ccllPAAAAeBJREFUeNqcU81O20AQ%2Ft"
+                             "Z2AgQSYQRqL1UPVG2hAUQkxLEStz4DrXpLpD5Drz31Cajax%"
+                             "2Bghhx6qHIJURBTxIwQRwopCBbZjHMcOTrzermPipsSt1Iw0"
+                             "3p3ZmW%2B%2B2R0TxhgOD34wjCHZlQ0iDYz9yvEfhxMTCYhE"
+                             "QDIZhkxKd2sqzX2TOD2vBQCQhpPefng1ZP2dVPlLLdpL8SEM"
+                             "cxng%2Fbs0RIHhtgs4twxOh%2BHjZxvzDx%2F3GQQiDFISiR"
+                             "BLFMPKTRMollzcWECrDVhtxtdRVsL9youPxGj%2FbdfFlUZh"
+                             "tDyYbYqWRUdai1oQRZ5oHeHl2gNM%2B01Uqio8RlH%2Bnsaz"
+                             "JzNwXcq1B%2BiXPHprlEEymeBfXs1w8XxxihfyuXqoHqpoGj"
+                             "ZM04bddgG%2F9%2B8WGj87qDdsrK9m%2BoA%2BpbhQTDh2l1"
+                             "%2Bi2weNbSHMZyjvNXmVbqh9Fj5Oz27uEoP%2BSTxANruJs9"
+                             "L%2FT6P0ewqPx5nmiAG5f6AoCtN1PbJzuRyJAyDBzzSQYvEr"
+                             "f06yYxhGXlEa8H2KVGoasjwLx3Ewk858opQWXm%2B%2Fib9E"
+                             "QrBzclLLLy89xYvlpchvtixcX6uo1y%2FzsiwHrkIsgKbp%2"
+                             "BYWFOWicuqppoNTnStHzPFCPQhBEBOyGAX4JMADFetubi4BS"
+                             "YAAAAABJRU5ErkJggg%3D%3D");
     }
     buffer.AppendLiteral("\">\n<title>");
 
     // Anything but a gopher url needs to end in a /,
     // otherwise we end up linking to file:///foo/dirfile
 
     if (!mTextToSubURI) {
         mTextToSubURI = do_GetService(NS_ITEXTTOSUBURI_CONTRACTID, &rv);
--- a/toolkit/components/places/src/nsNavHistory.cpp
+++ b/toolkit/components/places/src/nsNavHistory.cpp
@@ -923,19 +923,58 @@ nsNavHistory::CreateTriggers()
       "WHEN OLD.visit_type NOT IN (0,4,7) "
       "BEGIN "
         "UPDATE moz_places SET visit_count = visit_count - 1 "
         "WHERE moz_places.id = OLD.place_id AND visit_count > 0; "
       "END"));
     NS_ENSURE_SUCCESS(rv, rv);
 
     rv = createTriggersTransaction.Commit();
+    NS_ENSURE_SUCCESS(rv, rv);
   }
 
-  NS_ENSURE_SUCCESS(rv, rv);
+  // we are creating 1 trigger on moz_bookmarks to remove unused keywords
+  nsCOMPtr<mozIStorageStatement> detectRemoveKeywordsTrigger;
+  rv = mDBConn->CreateStatement(NS_LITERAL_CSTRING(
+      "SELECT name FROM sqlite_master WHERE type = 'trigger' AND "
+      "name = 'moz_bookmarks_beforedelete_v1_trigger'"),
+    getter_AddRefs(detectRemoveKeywordsTrigger));
+  NS_ENSURE_SUCCESS(rv, rv);
+
+  hasTrigger = PR_FALSE;
+  rv = detectRemoveKeywordsTrigger->ExecuteStep(&hasTrigger);
+  NS_ENSURE_SUCCESS(rv, rv);
+  rv = detectRemoveKeywordsTrigger->Reset();
+  NS_ENSURE_SUCCESS(rv, rv);
+
+  if (!hasTrigger) {
+    // Remove dangling keywords.
+    // We must remove old keywords that have not been deleted with bookmarks.
+    // See bug 421180 for details.
+    rv = mDBConn->ExecuteSimpleSQL(NS_LITERAL_CSTRING(
+        "DELETE FROM moz_keywords WHERE id IN ("
+          "SELECT k.id FROM moz_keywords k "
+          "LEFT OUTER JOIN moz_bookmarks b ON b.keyword_id = k.id "
+          "WHERE b.id IS NULL)"));
+    NS_ENSURE_SUCCESS(rv, rv);
+
+    // moz_bookmarks_beforedelete_v1_trigger
+    // Remove keywords if there are no more bookmarks using them.
+    rv = mDBConn->ExecuteSimpleSQL(NS_LITERAL_CSTRING(
+      "CREATE TRIGGER IF NOT EXISTS moz_bookmarks_beforedelete_v1_trigger "
+      "BEFORE DELETE ON moz_bookmarks FOR EACH ROW "
+      "WHEN OLD.keyword_id NOT NULL "
+      "BEGIN "
+        "DELETE FROM moz_keywords WHERE id = OLD.keyword_id AND "
+        " NOT EXISTS (SELECT id FROM moz_bookmarks "
+          "WHERE keyword_id = OLD.keyword_id AND id <> OLD.id LIMIT 1); "
+      "END"));
+    NS_ENSURE_SUCCESS(rv, rv);
+  }
+
   return NS_OK;
 }
 
 nsresult
 nsNavHistory::InitializeIdleTimer()
 {
   if (mIdleTimer) {
     mIdleTimer->Cancel();
@@ -2942,20 +2981,24 @@ PlacesSQLQueryBuilder::SelectAsURI()
         mQueryString += NS_LITERAL_CSTRING(
           " WHERE h.hidden <> 1 AND v.visit_type NOT IN (0,4)"
             " {ADDITIONAL_CONDITIONS} ");
 
       mGroupBy = NS_LITERAL_CSTRING(" GROUP BY h.id");
       break;
 
     case nsINavHistoryQueryOptions::QUERY_TYPE_BOOKMARKS:
+      // Don't initialize on var creation, that would give an error on compile
+      // because we are in the same scope of the switch clause and the var could
+      // not be initialized. Do an assignment rather than an initialization.
+      nsNavHistory* history;
+      history = nsNavHistory::GetHistoryService();
+      NS_ENSURE_STATE(history);
+
       if (mResultType == nsINavHistoryQueryOptions::RESULTS_AS_TAG_CONTENTS) {
-        nsNavHistory* history = nsNavHistory::GetHistoryService();
-        NS_ENSURE_STATE(history);
-
         // Order-by clause is hardcoded because we need to discard duplicates
         // in FilterResultSet. We will retain only the last modified item,
         // so we are ordering by place id and last modified to do a faster
         // filtering.
         mSkipOrderBy = PR_TRUE;
 
         mQueryString = NS_LITERAL_CSTRING(
           "SELECT b2.fk, h.url, COALESCE(b2.title, h.title), h.rev_host, "
@@ -2966,28 +3009,32 @@ PlacesSQLQueryBuilder::SelectAsURI()
             "JOIN moz_places h ON b2.fk = h.id AND b2.type = 1 "
             "LEFT OUTER JOIN moz_favicons f ON h.favicon_id = f.id "
             "WHERE b2.id IN ("
               "SELECT b1.id FROM moz_bookmarks b1 "
               "WHERE b1.fk IN "
                 "(SELECT b.fk FROM moz_bookmarks b WHERE b.type = 1 {ADDITIONAL_CONDITIONS}) "
               "AND NOT EXISTS "
                 "(SELECT id FROM moz_bookmarks WHERE id = b1.parent AND parent = ") +
-                nsPrintfCString("%d", history->GetTagsFolder()) +
+                nsPrintfCString("%lld", history->GetTagsFolder()) +
               NS_LITERAL_CSTRING(")) ORDER BY b2.fk DESC, b2.lastModified DESC");
       }
       else {
         mQueryString = NS_LITERAL_CSTRING(
           "SELECT b.fk, h.url, COALESCE(b.title, h.title), h.rev_host, "
             "h.visit_count,"
             SQL_STR_FRAGMENT_MAX_VISIT_DATE( "b.fk" )
             ", f.url, null, b.id, b.dateAdded, b.lastModified "
           "FROM moz_bookmarks b "
-               "JOIN moz_places h ON b.fk = h.id AND b.type = 1 "
-               "LEFT OUTER JOIN moz_favicons f ON h.favicon_id = f.id ");
+          "JOIN moz_places h ON b.fk = h.id AND b.type = 1 "
+          "LEFT OUTER JOIN moz_favicons f ON h.favicon_id = f.id "
+          "WHERE NOT EXISTS "
+            "(SELECT id FROM moz_bookmarks WHERE id = b.parent AND parent = ") +
+            nsPrintfCString("%lld", history->GetTagsFolder()) +
+            NS_LITERAL_CSTRING(") {ADDITIONAL_CONDITIONS}");
       }
       break;
 
     default:
       return NS_ERROR_NOT_IMPLEMENTED;
   }
   return NS_OK;
 }
new file mode 100644
--- /dev/null
+++ b/toolkit/components/places/tests/unit/test_402799.js
@@ -0,0 +1,95 @@
+/* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim:set ts=2 sw=2 sts=2 et: */
+/* ***** BEGIN LICENSE BLOCK *****
+ * Version: MPL 1.1/GPL 2.0/LGPL 2.1
+ *
+ * The contents of this file are subject to the Mozilla Public License Version
+ * 1.1 (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ * http://www.mozilla.org/MPL/
+ *
+ * Software distributed under the License is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+ * for the specific language governing rights and limitations under the
+ * License.
+ *
+ * The Original Code is Places unit test code.
+ *
+ * The Initial Developer of the Original Code is
+ * Mozilla Corporation.
+ * Portions created by the Initial Developer are Copyright (C) 2008
+ * the Initial Developer. All Rights Reserved.
+ *
+ * Contributor(s):
+ *   Marco Bonardo <mak77@supereva.it> (Original Author)
+ *
+ * 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 ***** */
+
+// Get history services
+try {
+  var histsvc = Cc["@mozilla.org/browser/nav-history-service;1"].
+                getService(Ci.nsINavHistoryService);
+  var bhist = histsvc.QueryInterface(Ci.nsIBrowserHistory);
+} catch(ex) {
+  do_throw("Could not get history services\n");
+}
+
+// Get bookmark service
+try {
+  var bmsvc = Cc["@mozilla.org/browser/nav-bookmarks-service;1"].
+              getService(Ci.nsINavBookmarksService);
+}
+catch(ex) {
+  do_throw("Could not get the nav-bookmarks-service\n");
+}
+
+// Get tagging service
+try {
+  var tagssvc = Cc["@mozilla.org/browser/tagging-service;1"].
+                getService(Ci.nsITaggingService);
+} catch(ex) {
+  do_throw("Could not get tagging service\n");
+}
+
+
+// main
+function run_test() {
+  var uri1 = uri("http://foo.bar/");
+
+  // create 2 bookmarks on the same uri
+  var bookmark1id = bmsvc.insertBookmark(bmsvc.bookmarksMenuFolder, uri1,
+                                         bmsvc.DEFAULT_INDEX, "title 1");
+  var bookmark2id = bmsvc.insertBookmark(bmsvc.toolbarFolder, uri1,
+                                         bmsvc.DEFAULT_INDEX, "title 2");
+  // add some tags
+  tagssvc.tagURI(uri1, ["foo", "bar", "foobar", "foo bar"]);
+
+  // check that a generic bookmark query returns only real bookmarks
+  var options = histsvc.getNewQueryOptions();
+  options.queryType = Ci.nsINavHistoryQueryOptions.QUERY_TYPE_BOOKMARKS;
+
+  var query = histsvc.getNewQuery();
+  var result = histsvc.executeQuery(query, options);
+  var root = result.root;
+
+  root.containerOpen = true;
+  var cc = root.childCount;
+  do_check_eq(cc, 2);
+  var node1 = root.getChild(0);
+  do_check_eq(bmsvc.getFolderIdForItem(node1.itemId), bmsvc.bookmarksMenuFolder);
+  var node2 = root.getChild(1);
+  do_check_eq(bmsvc.getFolderIdForItem(node2.itemId), bmsvc.toolbarFolder);
+  root.containerOpen = false;
+}
--- a/toolkit/components/places/tests/unit/test_419731.js
+++ b/toolkit/components/places/tests/unit/test_419731.js
@@ -78,30 +78,31 @@ function run_test() {
 
   // get tag folder id
   var options = histsvc.getNewQueryOptions();
   var query = histsvc.getNewQuery();
   query.setFolders([bmsvc.tagsFolder], 1);
   var result = histsvc.executeQuery(query, options);
   var tagRoot = result.root;
   tagRoot.containerOpen = true;
-  var tag1node = tagRoot.getChild(0)
-                        .QueryInterface(Ci.nsINavHistoryContainerResultNode);
-  var tag1itemId = tag1node.itemId;
+  var tagNode = tagRoot.getChild(0)
+                       .QueryInterface(Ci.nsINavHistoryContainerResultNode);
+  var tagItemId = tagNode.itemId;
   tagRoot.containerOpen = false;
 
   // change bookmark 1 title
   bmsvc.setItemTitle(bookmark1id, "new title 1");
 
   // check that tag container contains new title
   options = histsvc.getNewQueryOptions();
   options.queryType = Ci.nsINavHistoryQueryOptions.QUERY_TYPE_BOOKMARKS;
   options.resultType = options.RESULTS_AS_TAG_CONTENTS;
-  options.includeHidden = true;
+
   query = histsvc.getNewQuery();
+  query.setFolders([tagItemId], 1);
   result = histsvc.executeQuery(query, options);
   var root = result.root;
 
   root.containerOpen = true;
   var cc = root.childCount;
   do_check_eq(cc, 1);
   var node = root.getChild(0);
   do_check_eq(node.title, "new title 1");
@@ -109,20 +110,21 @@ function run_test() {
 
   // change bookmark 2 title
   bmsvc.setItemTitle(bookmark2id, "new title 2");
 
   // check that tag container contains new title
   options = histsvc.getNewQueryOptions();
   options.queryType = Ci.nsINavHistoryQueryOptions.QUERY_TYPE_BOOKMARKS;
   options.resultType = options.RESULTS_AS_TAG_CONTENTS;
-  options.includeHidden = true;
+
   query = histsvc.getNewQuery();
+  query.setFolders([tagItemId], 1);
   result = histsvc.executeQuery(query, options);
   root = result.root;
 
   root.containerOpen = true;
   cc = root.childCount;
   do_check_eq(cc, 1);
-  var node = root.getChild(0);
+  node = root.getChild(0);
   do_check_eq(node.title, "new title 2");
   root.containerOpen = false;
 }
new file mode 100644
--- /dev/null
+++ b/toolkit/components/places/tests/unit/test_421180.js
@@ -0,0 +1,114 @@
+/* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim:set ts=2 sw=2 sts=2 et: */
+/* ***** BEGIN LICENSE BLOCK *****
+ * Version: MPL 1.1/GPL 2.0/LGPL 2.1
+ *
+ * The contents of this file are subject to the Mozilla Public License Version
+ * 1.1 (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ * http://www.mozilla.org/MPL/
+ *
+ * Software distributed under the License is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+ * for the specific language governing rights and limitations under the
+ * License.
+ *
+ * The Original Code is Places unit test code.
+ *
+ * The Initial Developer of the Original Code is
+ * Mozilla Corporation.
+ * Portions created by the Initial Developer are Copyright (C) 2008
+ * the Initial Developer. All Rights Reserved.
+ *
+ * Contributor(s):
+ *   Marco Bonardo <mak77@supereva.it> (Original Author)
+ *
+ * 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 ***** */
+
+// Get bookmarks service
+try {
+  var bmsvc = Cc["@mozilla.org/browser/nav-bookmarks-service;1"].
+              getService(Ci.nsINavBookmarksService);
+}
+catch(ex) {
+  do_throw("Could not get bookmarks service\n");
+}
+
+// Get database connection
+try {
+  var dirSvc = Cc["@mozilla.org/file/directory_service;1"].
+               getService(Ci.nsIProperties);
+  var storage = Cc["@mozilla.org/storage/service;1"].
+                getService(Ci.mozIStorageService);
+  var database = dirSvc.get('ProfD', Ci.nsIFile);
+  database.append("places.sqlite");
+  var mDBConn = storage.openDatabase(database);
+}
+catch(ex) {
+  do_throw("Could not get database connection\n");
+}
+
+// main
+function run_test() {
+  var bookmarkedURI = uri("http://foo.bar");
+  var keyword = "testkeyword";
+
+  // TEST 1
+  // 1. add a bookmark
+  // 2. add a keyword to it
+  // 3. remove bookmark
+  // 4. check that keyword has gone
+  var bookmarkId = bmsvc.insertBookmark(bmsvc.bookmarksMenuFolder,
+                                        bookmarkedURI,
+                                        bmsvc.DEFAULT_INDEX,
+                                        "A bookmark");
+  bmsvc.setKeywordForBookmark(bookmarkId, keyword);
+  // remove bookmark
+  bmsvc.removeItem(bookmarkId);
+
+  // check that keyword has been removed
+  var sql = "SELECT id FROM moz_keywords WHERE keyword = ?1";
+  var stmt = mDBConn.createStatement(sql);
+  stmt.bindUTF8StringParameter(0, keyword);
+  do_check_false(stmt.executeStep());
+
+
+  // TEST 2
+  // 1. add 2 bookmarks
+  // 2. add the same keyword to them
+  // 3. remove first bookmark
+  // 4. check that keyword is still there
+  var bookmarkId1 = bmsvc.insertBookmark(bmsvc.bookmarksMenuFolder,
+                                        bookmarkedURI,
+                                        bmsvc.DEFAULT_INDEX,
+                                        "A bookmark");
+  bmsvc.setKeywordForBookmark(bookmarkId1, keyword);
+
+  var bookmarkId2 = bmsvc.insertBookmark(bmsvc.toolbarFolder,
+                                        bookmarkedURI,
+                                        bmsvc.DEFAULT_INDEX,
+                                        keyword);
+  bmsvc.setKeywordForBookmark(bookmarkId2, keyword);
+
+  // remove first bookmark
+  bmsvc.removeItem(bookmarkId1);
+
+  // check that keyword is still there
+  var sql = "SELECT id FROM moz_keywords WHERE keyword = ?1";
+  var stmt = mDBConn.createStatement(sql);
+  stmt.bindUTF8StringParameter(0, keyword);
+  do_check_true(stmt.executeStep());
+
+}
--- a/toolkit/components/places/tests/unit/test_multi_word_tags.js
+++ b/toolkit/components/places/tests/unit/test_multi_word_tags.js
@@ -41,16 +41,25 @@
 // Get history service
 try {
   var histsvc = Cc["@mozilla.org/browser/nav-history-service;1"].
                 getService(Ci.nsINavHistoryService);
 } catch(ex) {
   do_throw("Could not get history service\n");
 }
 
+// Get bookmark service
+try {
+  var bmsvc = Cc["@mozilla.org/browser/nav-bookmarks-service;1"].
+              getService(Ci.nsINavBookmarksService);
+}
+catch(ex) {
+  do_throw("Could not get the nav-bookmarks-service\n");
+}
+
 // Get tagging service
 try {
   var tagssvc = Cc["@mozilla.org/browser/tagging-service;1"].
                 getService(Ci.nsITaggingService);
 } catch(ex) {
   do_throw("Could not get tagging service\n");
 }
 
@@ -58,26 +67,34 @@ try {
 function run_test() {
   var uri1 = uri("http://site.tld/1");
   var uri2 = uri("http://site.tld/2");
   var uri3 = uri("http://site.tld/3");
   var uri4 = uri("http://site.tld/4");
   var uri5 = uri("http://site.tld/5");
   var uri6 = uri("http://site.tld/6");
 
+  bmsvc.insertBookmark(bmsvc.bookmarksMenuFolder, uri1, bmsvc.DEFAULT_INDEX, null);
+  bmsvc.insertBookmark(bmsvc.bookmarksMenuFolder, uri2, bmsvc.DEFAULT_INDEX, null);
+  bmsvc.insertBookmark(bmsvc.bookmarksMenuFolder, uri3, bmsvc.DEFAULT_INDEX, null);
+  bmsvc.insertBookmark(bmsvc.bookmarksMenuFolder, uri4, bmsvc.DEFAULT_INDEX, null);
+  bmsvc.insertBookmark(bmsvc.bookmarksMenuFolder, uri5, bmsvc.DEFAULT_INDEX, null);
+  bmsvc.insertBookmark(bmsvc.bookmarksMenuFolder, uri6, bmsvc.DEFAULT_INDEX, null);
+
   tagssvc.tagURI(uri1, ["foo"]);
   tagssvc.tagURI(uri2, ["bar"]);
   tagssvc.tagURI(uri3, ["cheese"]);
   tagssvc.tagURI(uri4, ["foo bar"]);
   tagssvc.tagURI(uri5, ["bar cheese"]);
   tagssvc.tagURI(uri6, ["foo bar cheese"]);
 
   // exclude livemark items, search for "item", should get one result
   var options = histsvc.getNewQueryOptions();
   options.queryType = Ci.nsINavHistoryQueryOptions.QUERY_TYPE_BOOKMARKS;
+
   var query = histsvc.getNewQuery();
   query.searchTerms = "foo";
   var result = histsvc.executeQuery(query, options);
   var root = result.root;
   root.containerOpen = true;
   do_check_eq(root.childCount, 3);
   do_check_eq(root.getChild(0).uri, "http://site.tld/1");
   do_check_eq(root.getChild(1).uri, "http://site.tld/4");
--- a/toolkit/components/places/tests/unit/test_resolveNullBookmarkTitles.js
+++ b/toolkit/components/places/tests/unit/test_resolveNullBookmarkTitles.js
@@ -64,32 +64,33 @@ try {
   do_throw("Could not get tagging service\n");
 }
 
 // main
 function run_test() {
   var uri1 = uri("http://foo.tld/");
   var uri2 = uri("https://bar.tld/");
 
+  bhist.addPageWithDetails(uri1, "foo title", Date.now() * 1000);
+  bhist.addPageWithDetails(uri2, "bar title", Date.now() * 1000);
+
+  bmsvc.insertBookmark(bmsvc.bookmarksMenuFolder, uri1, bmsvc.DEFAULT_INDEX, null);
+  bmsvc.insertBookmark(bmsvc.bookmarksMenuFolder, uri2, bmsvc.DEFAULT_INDEX, null);
+  
   tagssvc.tagURI(uri1, ["tag 1"]);
   tagssvc.tagURI(uri2, ["tag 2"]);
 
-  bhist.addPageWithDetails(uri1, "foo title", Date.now() * 1000);
-
-  bhist.addPageWithDetails(uri2, "bar title", Date.now() * 1000);
-
   var options = histsvc.getNewQueryOptions();
   options.queryType = Ci.nsINavHistoryQueryOptions.QUERY_TYPE_BOOKMARKS;
-  options.maxResults = 2;
-
-  options = histsvc.getNewQueryOptions();
-  options.queryType = Ci.nsINavHistoryQueryOptions.QUERY_TYPE_BOOKMARKS;
-  options.maxResults = 2;
+  options.resultType = options.RESULTS_AS_TAG_CONTENTS;
 
   var query = histsvc.getNewQuery();
-  query.setFolders([bmsvc.tagsFolder], 1);
+  // if we don't set a tag folder, RESULTS_AS_TAG_CONTENTS will return all
+  // tagged URIs
   var result = histsvc.executeQuery(query, options);
   var root = result.root;
   root.containerOpen = true;
   do_check_eq(root.childCount, 2);
-  do_check_eq(root.getChild(0).title, "foo title");
-  do_check_eq(root.getChild(1).title, "bar title");
+  // actually RESULTS_AS_TAG_CONTENTS return results ordered by place_id DESC
+  // so they are reversed
+  do_check_eq(root.getChild(0).title, "bar title");
+  do_check_eq(root.getChild(1).title, "foo title");
 }
--- a/toolkit/content/customizeToolbar.js
+++ b/toolkit/content/customizeToolbar.js
@@ -188,16 +188,22 @@ function persistCurrentSets()
  */
 function wrapToolbarItems()
 {
   for (var i = 0; i < gToolbox.childNodes.length; ++i) {
     var toolbar = getToolbarAt(i);
     if (isCustomizableToolbar(toolbar)) {
       for (var k = 0; k < toolbar.childNodes.length; ++k) {
         var item = toolbar.childNodes[k];
+
+#ifdef XP_MACOSX
+        if (item.firstChild && item.firstChild.localName == "menubar")
+          continue;
+#endif
+
         if (isToolbarItem(item)) {
           var nextSibling = item.nextSibling;
           
           var wrapper = wrapToolbarItem(item);
           
           if (nextSibling)
             toolbar.insertBefore(wrapper, nextSibling);
           else
--- a/toolkit/content/tests/widgets/test_popupincontent.xul
+++ b/toolkit/content/tests/widgets/test_popupincontent.xul
@@ -12,17 +12,17 @@
 
 <!--
   This test checks that popups in content areas don't extend past the content area.
   -->
 
 <hbox>
   <spacer width="100"/>
   <menu id="menu">
-    <menupopup id="popup" onpopupshown="popupShown()" onpopuphidden="nextTest()">
+    <menupopup style="margin:10px;" id="popup" onpopupshown="popupShown()" onpopuphidden="nextTest()">
       <menuitem label="One"/>
       <menuitem label="Two"/>
       <menuitem label="Three"/>
       <menuitem label="Four"/>
       <menuitem label="Five"/>
       <menuitem label="A final longer label that is actually quite long. Very long indeed."/>
     </menupopup>
   </menu>
@@ -54,16 +54,24 @@ function nextTest()
       break;
     case "openPopupAtScreen":
       step = "left and top";
       popup.setAttribute("left", "800");
       popup.setAttribute("top", "2900");
       synthesizeMouse($("menu"), 2, 2, { });
       break;
     case "left and top":
+      step = "open near bottom";
+      // request that the menu be opened with a target point near the bottom of the window,
+      // so that the menu's top margin will push it completely outside the window.
+      var bo = document.documentElement.boxObject;
+      popup.setAttribute("top", bo.screenY + window.innerHeight - 5);
+      synthesizeMouse($("menu"), 2, 2, { });
+      break;
+    case "open near bottom":
       step = "large menu";
       popup.removeAttribute("left");
       popup.removeAttribute("top");
       for (var i = 0; i < 40; i++)
         menu.appendItem("Test", "");
       synthesizeMouse(menu, 2, 2, { });
       break;
     case "large menu":
@@ -85,16 +93,21 @@ function popupShown()
 
   // subtract one off the edge due to a rounding issue
   ok(popuprect.left >= windowrect.left, step + " left");
   ok(popuprect.right - 1 <= windowrect.right, step + " right");
 
   if (step == "left and top")
     originalHeight = popuprect.bottom - popuprect.top;
 
+  if (step == "open near bottom") {
+    // check that the menu flipped up so it's above our requested point
+    ok(popuprect.bottom - 1 <= windowrect.bottom - 5, step + " bottom");
+  }
+
   if (step == "largemenu") {
     ok(popuprect.top == windowrect.top, step + " top");
     ok(popuprect.bottom - 1 == windowrect.bottom, step + " bottom");
   }
   else {
     ok(popuprect.top >= windowrect.top, step + " top");
     ok(popuprect.bottom - 1 <= windowrect.bottom, step + " bottom");
     // XXXndeakin disable this test for now: bug 407937
--- a/toolkit/content/widgets/notification.xml
+++ b/toolkit/content/widgets/notification.xml
@@ -86,17 +86,18 @@
                 break;
               insertPos = notifications[n];
             }
 
             const XULNS = "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul";
             var newitem = document.createElementNS(XULNS, "notification");
             newitem.setAttribute("label", aLabel);
             newitem.setAttribute("value", aValue);
-            newitem.setAttribute("image", aImage);
+            if (aImage)
+                newitem.setAttribute("image", aImage);
             if (!insertPos) {
               newitem.style.position = "fixed";
               newitem.style.top = "100%";
             }
             this.insertBefore(newitem, insertPos);
 
             if (aButtons) {
               for (var b = 0; b < aButtons.length; b++) {
--- a/toolkit/themes/gnomestripe/global/notification.css
+++ b/toolkit/themes/gnomestripe/global/notification.css
@@ -16,19 +16,37 @@ notification[type="critical"] {
 }
 
 .messageImage {
   width: 16px;
   height: 16px;
   margin: 0px 1px 0px 6px;
 }
 
+/* Default icons for notifications */
+
+notification[type="info"] .messageImage {
+  list-style-image: url("chrome://global/skin/icons/information-16.png");
+}
+
+notification[type="warning"] .messageImage {
+  list-style-image: url("chrome://global/skin/icons/warning-16.png");
+}
+
+notification[type="critical"] .messageImage {
+  list-style-image: url("chrome://global/skin/icons/error-16.png");
+}
+
 .messageText {
   -moz-margin-start: 5px;
 }
 
 .messageButton {
   margin: 0px 5px 0px 5px;
 }
 
 .messageCloseButton {
   list-style-image: url("moz-icon://stock/gtk-close?size=menu");
 }
+
+.messageCloseButton > .toolbarbutton-icon {
+  margin: 0px !important;
+}
--- a/toolkit/themes/pinstripe/global/dialog.css
+++ b/toolkit/themes/pinstripe/global/dialog.css
@@ -62,65 +62,49 @@ dialog {
 .dialog-button {
   font: menu;
 }
 
 /* ::::: dialog header ::::: */
 
 dialogheader {
   margin: 0px 5px 5px 5px;
-  border: 2px solid;
-  -moz-border-top-colors: ThreeDShadow ThreeDDarkShadow;
-  -moz-border-right-colors: ThreeDHighlight ThreeDDarkShadow;
-  -moz-border-bottom-colors: ThreeDHighlight ThreeDDarkShadow;
-  -moz-border-left-colors: ThreeDShadow ThreeDDarkShadow;
   padding: 5px 8px;
-  background-color: Highlight;
-  color: HighlightText;
 }
 
 .dialogheader-title {
   margin: 0px !important;
   font-size: larger;
   font-weight: bold;
   display: none;
 }
 
 /* ::::: large dialog header ::::: */
 
 .header-large {
   -moz-box-orient: vertical;
   margin: -14px -14px 0;
-  border-left: none;
-  border-right: none;
-  border-top: 1px solid;
-  -moz-border-top-colors: #FFFFFF;
-  -moz-border-bottom-colors: #9999FF #777777;
   padding: 12px 5px 12px 25px;
-  background-color: #CCCCFF;
-  color: #000000;
 }
 
 .header-large > .dialogheader-title {
   font: inherit;
   font-weight: bold;
 }
 
 .header-large > .dialogheader-description {
   margin-left: 12px !important;
 }
 
 .dialogheader-description {
 	font-weight: bold !important;
-	border: 1px solid blue;
 }
 
 .dialogheader-title {
 	font-weight: bold !important;
-	border: 1px solid red;
 }
 
 #loginContainer {
 	padding-top: 10px;
 }
 
 #findDialog, #findDialog > menu, #findDialog > groupbox {
 	font: menu !important;
--- a/toolkit/themes/pinstripe/global/notification.css
+++ b/toolkit/themes/pinstripe/global/notification.css
@@ -26,16 +26,30 @@ notification[type="critical"] {
 }
 
 .messageImage {
   width: 16px;
   height: 16px;
   margin: 0px 1px 0px 6px;
 }
 
+/* Default icons for notifications */
+
+notification[type="info"] .messageImage {
+  list-style-image: url("chrome://global/skin/icons/information-16.png");
+}
+
+notification[type="warning"] .messageImage {
+  list-style-image: url("chrome://global/skin/icons/warning-16.png");
+}
+
+notification[type="critical"] .messageImage {
+  list-style-image: url("chrome://global/skin/icons/error-16.png");
+}
+
 .messageText {
   margin-top: 2px;
   font-weight: bold;
   -moz-margin-start: 5px;
 }
 
 .notification-inner > button {
   -moz-appearance: none !important;
--- a/toolkit/themes/winstripe/global/button.css
+++ b/toolkit/themes/winstripe/global/button.css
@@ -98,19 +98,19 @@ button:hover:active,
 button[open="true"],
 button[checked="true"] {
   -moz-border-top-colors: ThreeDDarkShadow ThreeDShadow transparent;
   -moz-border-right-colors: ThreeDDarkShadow ThreeDShadow transparent;
   -moz-border-bottom-colors: ThreeDDarkShadow ThreeDShadow transparent;
   -moz-border-left-colors: ThreeDDarkShadow ThreeDShadow transparent;
 }
 
-button:hover:active > .button-box,
-button[open="true"] > .button-box,
-button[checked="true"] > .button-box {
+button:hover:active > .button-box:not(:-moz-system-metric(windows-default-theme)),
+button[open="true"] > .button-box:not(:-moz-system-metric(windows-default-theme)),
+button[checked="true"] > .button-box:not(:-moz-system-metric(windows-default-theme)) {
   padding-top: 2px;
   padding-bottom: 1px;
   -moz-padding-start: 4px;
   -moz-padding-end: 3px;
 }
 
 /* .......... disabled state .......... */
 
--- a/toolkit/themes/winstripe/global/console/console.css
+++ b/toolkit/themes/winstripe/global/console/console.css
@@ -44,17 +44,17 @@
 .console-box {
   background-color: -moz-Field;
   color: -moz-FieldText;
 }
 
 /* ::::: console rows ::::: */
 
 .console-row {
-  border-bottom: 1px dotted threedshadow;
+  border-bottom: 1px solid ThreeDLightShadow;
   padding: 4px 0px;
 }
 
 .console-row-icon {
   padding: 4px;
   -moz-padding-start: 5px;
   -moz-box-align: start !important;
 }
--- a/toolkit/themes/winstripe/global/dirListing/dirListing.css
+++ b/toolkit/themes/winstripe/global/dirListing/dirListing.css
@@ -117,16 +117,21 @@ td:not(:first-child) {
 }
 
 .up::before {
   -moz-margin-end: 4px;
   -moz-margin-start: -20px;
   vertical-align: middle;
 %ifdef MOZ_WIDGET_GTK2
   content: url(moz-icon://stock/gtk-go-up?size=menu);
-}
-.dir::before {
-  content: url(moz-icon://stock/gtk-directory?size=menu);
 %else
   content: url(chrome://global/skin/dirListing/up.png);
 %endif
 }
 
+.dir::before {
+%ifdef MOZ_WIDGET_GTK2
+  content: url(moz-icon://stock/gtk-directory?size=menu);
+%else
+  content: url(chrome://global/skin/dirListing/folder.png);
+%endif
+}
+
new file mode 100644
index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..c266b012e8cb6bbcd8efca6cdf78c2b033333ad7
GIT binary patch
literal 572
zc$@(|0>k}@P)<h;3K|Lk000e1NJLTq000mG000mO1^@s6AM^iV0000PbVXQnQ*UN;
zcVTj606}DLVr3vnZDD6+Qe|Oed2z{QJOBUz-bqA3RCwBqQ@?8!K@k4-?xE2{5=_7%
zU}=#?n-u;fc9w~SmDro~Vr6SD{uve)2|-gN$b%pVA@~SJG4I~J{W0Ur?A^<8yg(NA
zc5i0q+i&KZb<B)khc9*(?ybCGA~5n`N}w2_h8O~}gOQ@&UEln$gLWvu#qc%Pzdtdj
zlWXVb_^qu!zdUD+Y3Cs0>WyP?_}=`r=nilUH+TZ5Kb{Gzj$g*0-4x|rP^#h38+yJ>
z@YRJ}G6nbCnE{EJC11&zJ4bY<fQ|_%`~xR%wC6G)@&@91x07WN;U|)UFzf>qxZ$7_
z=h_V*g{U7X;us_|#mXkhR2x%7Oe*U{sbctf`{U`st4FgGru76%NeV<&Cwu)i2~oa1
zO@83c+GC7I-=2kV>#vx$i|p5iDeQKNnMK}T+R9RcC@j^tvbu=n^{4QcqpevA(FZG#
zQqF-b{mO!rLG8WSVs(P$2OGk+qr$Y(gS7=a*P(7QYR4r}I2mA;J!n&30XSFWCQ+Hp
zz*n890QxSZcveJ(6aeZnP>EPopc?&F%Wo)|QY?jTGzB*ZnL#0?;DGY>!?{|!a?t|H
zh1O5TXa;aPJbF3)bN-%)uW6$_c`FXXulvpaK9=sUzSG@*0R{l(W_%ffeJel!0000<
KMNUMnLSTaL-3iM8
new file mode 100755
index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..102de5196014905f59909a9a0cb012c050e88ce3
GIT binary patch
literal 446
zc$@*g0YUzWP)<h;3K|Lk000e1NJLTq000mG000mO0{{R3C@l|D0000PbVXQnQ*UN;
zcVTj606}DLVr3vnZDD6+Qe|Oed2z{QJOBUyw@^$}MgRZ*?95-bgBj(xMdij?-o8_|
zgBi=8GSQ_r)2KStsyf-OJl?QA-?TyEwM662Yvayz<+w%l*>n8qpZ?2T{?=Rm;A{WZ
zTmRl-|K4N&-(vsYWB=f5|KM!@;%oopa{uUX|LA%D>2Lq(aR2Os|LueS?t1_3eE;xz
z|L~0e@r?iVhyV46|MrLf_K5%XnE&^f|NEi;{^bAu<^TVt|Np1||E~Z4yZ`^d|Nqth
z|LXt$_W%F+jt+$D00006bW%=J04AB4nW$<b>g@mk0E<aPK~xwS1;If|#6T1U!1_Op
z4kE%_L6>v?n}}{ag$f#z?q?MMfZCqG*9=hC8@#XY0~pSQmybu_b4ZA1_u#Fr2>`0b
zyzP|=MO<D-e$QHMwbgU`$;jH#DM=j<897d6nqB6$XXMx?=%l(ba{e`}tj>9tk(CLi
o$;wFjvQ#CVn5iBB-~<5h4_p{g+AqC$(f|Me07*qoM6N<$f_vfdTmS$7
deleted file mode 100644
index c266b012e8cb6bbcd8efca6cdf78c2b033333ad7..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
GIT binary patch
literal 0
Hc$@<O00001
index 102de5196014905f59909a9a0cb012c050e88ce3..c5da02b7fcba44bf1ed72db879d59e9f9519c69e
GIT binary patch
literal 655
zc$@)`0&x9_P)<h;3K|Lk000e1NJLTq000mG000mO1^@s6AM^iV0000PbVXQnQ*UN;
zcVTj606}DLVr3vnZDD6+Qe|Oed2z{QJOBU!F-b&0RCwB~Q_GGLQ4l@%(cN@6IM5Pw
z5<*BEN21Pt+!!~m`2xSg#FZ}mfcXym1mi-59Xn_3teBC9rl)x}{jlmn;|Gj4sa&{K
zb?Tf$A@V%OU5;RY;c)n_*=&CNad`=CS?HXeg5T3LMUo_l;}}sCAq+#TRx4Okvs^Ae
zbi3X6no%m1%FF6e6`tq8rKs2I2Au)6+pPg8m&+)XN*Iks5JGV6t6r}sbidzsTdmd;
z2;jx}`Ju6x&H$Uu#)NI#2!a6P@ffb_KB7`jQel%4$HlZP%MAS@itn6fCQ>T%MyEk{
zTN0fPg~Q3w=$a;RkuXfMJUaj=r404SWMY8m-6l!TG@YkKQYnd_S63+eK77(lIVds=
z@fOj1Nz{K)^TyONFaexsYVJ&@Gcz#=YN$$y^?Hrpvl#>d=2>o>U(DxVV$3ay=Ee_V
z_FTKJceXQ(^zV1Vb{x~lCXxs^R19Lp`h`%G_vi)zWM_IjnFR@%=ad{wr+*-*hzq5V
zbjyQjhhHVhXn7P?>p3i2mvwj><w5N}8jXfAPb-VG?}EKypd?L9bFxjaks-beKS5p}
zqy4y@u`FL}wRf8p%6}{*?HK_Gh+=VJ`x@UbKjYii0Za3><2W~q#o~c&*^o-ZwqmGw
z&wwOkOr3XxJYt{HaD&$;Z;(9H^p@P{>QU`tFzCM}L+&X<U*$Yq5g5-+v)xvjn`F>u
p!Qet<x4!RPi2w3$yvzA3zyL>YJ%{yPybS;V002ovPDHLkV1i=`E>i#i
--- a/toolkit/themes/winstripe/global/jar.mn
+++ b/toolkit/themes/winstripe/global/jar.mn
@@ -73,16 +73,17 @@ classic.jar:
         skin/classic/global/console/console.css                  (console/console.css)
         skin/classic/global/console/console-toolbar.png          (console/console-toolbar.png)
         skin/classic/global/console/bullet-error.png             (console/bullet-error.png)
         skin/classic/global/console/bullet-question.png          (console/bullet-question.png)
         skin/classic/global/console/bullet-warning.png           (console/bullet-warning.png)
         skin/classic/global/console/console-error-caret.gif      (console/console-error-caret.gif)
         skin/classic/global/console/console-error-dash.gif       (console/console-error-dash.gif)
 *       skin/classic/global/dirListing/dirListing.css            (dirListing/dirListing.css)
+        skin/classic/global/dirListing/folder.png                (dirListing/folder.png)
         skin/classic/global/dirListing/local.png                 (dirListing/local.png)
         skin/classic/global/dirListing/remote.png                (dirListing/remote.png)
         skin/classic/global/dirListing/up.png                    (dirListing/up.png)
         skin/classic/global/Filepicker.png                       (filepicker/Filepicker.png)
         skin/classic/global/icons/autoscroll.png                 (icons/autoscroll.png)
         skin/classic/global/icons/blacklist_favicon.png          (icons/blacklist_favicon.png)
         skin/classic/global/icons/blacklist_large.png            (icons/blacklist_large.png)
         skin/classic/global/icons/Close.gif                      (icons/Close.gif)
@@ -231,17 +232,18 @@ classic.jar:
         skin/classic/aero/global/console/console.css                     (console/console.css)
         skin/classic/aero/global/console/console-toolbar.png             (console/console-toolbar-aero.png)
         skin/classic/aero/global/console/bullet-error.png                (console/bullet-error-aero.png)
         skin/classic/aero/global/console/bullet-question.png             (console/bullet-question-aero.png)
         skin/classic/aero/global/console/bullet-warning.png              (console/bullet-warning-aero.png)
         skin/classic/aero/global/console/console-error-caret.gif         (console/console-error-caret.gif)
         skin/classic/aero/global/console/console-error-dash.gif          (console/console-error-dash.gif)
 *       skin/classic/aero/global/dirListing/dirListing.css               (dirListing/dirListing.css)
-        skin/classic/aero/global/dirListing/local.png                    (dirListing/local-aero.png)
+        skin/classic/aero/global/dirListing/folder.png                   (dirListing/folder-aero.png)
+        skin/classic/aero/global/dirListing/local.png                    (dirListing/local.png)
         skin/classic/aero/global/dirListing/remote.png                   (dirListing/remote-aero.png)
         skin/classic/aero/global/dirListing/up.png                       (dirListing/up-aero.png)
         skin/classic/aero/global/Filepicker.png                          (filepicker/Filepicker.png)
         skin/classic/aero/global/icons/autoscroll.png                    (icons/autoscroll-aero.png)
         skin/classic/aero/global/icons/blacklist_favicon.png             (icons/blacklist_favicon-aero.png)
         skin/classic/aero/global/icons/blacklist_large.png               (icons/blacklist_large-aero.png)
         skin/classic/aero/global/icons/Close.gif                         (icons/Close.gif)
         skin/classic/aero/global/icons/close.png                         (icons/close-aero.png)
--- a/toolkit/themes/winstripe/global/menu.css
+++ b/toolkit/themes/winstripe/global/menu.css
@@ -222,16 +222,24 @@ menuitem[checked="true"] > .menu-iconic-
 
 menuitem[type="radio"] {
   -moz-appearance: radiomenuitem;
 }
 menuitem[type="radio"] > .menu-iconic-left {
   -moz-appearance: menuradio;
 }
 
+menuitem[type="checkbox"] > .menu-iconic-left > .menu-iconic-icon,
+menuitem[checked="true"] > .menu-iconic-left > .menu-iconic-icon,
+menuitem[type="radio"] > .menu-iconic-left > .menu-iconic-icon {
+  /* prevent .menu-iconic-icon from enforcing a minimal height of 16px (see bug 411064)
+     XXXzeniko apply that .menu-iconic-icon rule only for children of .menu-iconic */
+  display: none;
+}
+
 /* ::::: menuseparator ::::: */
 
 menuseparator {
   -moz-appearance: menuseparator;
   padding: 3px 1px 4px 1px;
   border-top: 1px solid ThreeDShadow;
   border-bottom: 1px solid ThreeDHighlight;
 }
--- a/toolkit/themes/winstripe/global/notification.css
+++ b/toolkit/themes/winstripe/global/notification.css
@@ -16,16 +16,30 @@ notification[type="critical"] {
 }
 
 .messageImage {
   width: 16px;
   height: 16px;
   margin: 0px 1px 0px 6px;
 }
 
+/* Default icons for notifications */
+
+notification[type="info"] .messageImage {
+  list-style-image: url("chrome://global/skin/icons/information-16.png");
+}
+
+notification[type="warning"] .messageImage {
+  list-style-image: url("chrome://global/skin/icons/warning-16.png");
+}
+
+notification[type="critical"] .messageImage {
+  list-style-image: url("chrome://global/skin/icons/error-16.png");
+}
+
 .messageText {
   -moz-margin-start: 5px;
 }
 
 .messageButton {
   margin: 0px 5px 0px 5px;
 }
 
--- a/tools/patcher/patcher2.pl
+++ b/tools/patcher/patcher2.pl
@@ -708,20 +708,20 @@ sub CreateCompletePatchinfo {
                 for my $c (@channels) {
                     my $snippetDir = GetSnippetDirFromChannel(
                      config => $config->GetCurrentUpdate(), channel => $c);
 
                     my $snippetToAppVersion = $to->{'appv'};
                     my $prettySnippetToAppVersion = $to->{'prettyAppv'};
                     foreach my $channel (keys(%{$currentUpdateRcInfo})) {
                         if ($c eq $channel) {
-                            $snippetToAppVersion = $to->{'appv'} . 'rc' .
+                            $snippetToAppVersion = $to->{'appv'} . 'build' .
                              $currentUpdateRcInfo->{$channel};
                             $prettySnippetToAppVersion = $to->{'prettyAppv'} .
-                             'rc' . $currentUpdateRcInfo->{$channel};
+                             ' (build ' . $currentUpdateRcInfo->{$channel} . ')';
                             last;
                         }
                     }
 
                     my $aus_prefix = catfile($u, $snippetDir, 
                                              $from_aus_app,
                                              $from_aus_version,
                                              $from_aus_platform,
@@ -739,17 +739,17 @@ sub CreateCompletePatchinfo {
                     #printf("partial = %s", Data::Dumper::Dumper($partial_patch));
                     #printf("complete = %s", Data::Dumper::Dumper($complete_patch));
 
                     # This is just prettyfication for the PrintProgress() call,
                     # so we know which channels have had rc's added to their
                     # appv's.
                     my $progressVersion = $u;
                     if ($snippetToAppVersion ne $to->{'appv'}) {
-                        $progressVersion =~ s/$to->{'appv'}/$snippetToAppVersion/;
+                        $progressVersion =~ s/\-$to->{'appv'}/-$snippetToAppVersion/;
                     }
                     PrintProgress(total => $total, current => $i,
                      string => "$progressVersion/$p/$l/$c");
 
                     $complete_patch->{'patch_path'} = $to_path;
                     $complete_patch->{'type'} = 'complete';
 
                     my $hash_type = $DEFAULT_HASH_TYPE;
@@ -801,21 +801,21 @@ sub CreateCompletePatchinfo {
                         foreach my $testChan (split(/[\s,]+/, 
                          $u_config->{$u}->{'testchannel'})) {
                     
                             $snippetToAppVersion = $to->{'appv'};
                             $prettySnippetToAppVersion = $to->{'prettyAppv'};
                             foreach my $channel 
                              (keys(%{$currentUpdateRcInfo})) {
                                 if ($testChan eq $channel) {
-                                    $snippetToAppVersion = $to->{'appv'} . 'rc' 
+                                    $snippetToAppVersion = $to->{'appv'} . 'build' 
                                     . $currentUpdateRcInfo->{$channel};
                                     $prettySnippetToAppVersion =
-                                     $to->{'prettyAppv'} . 'rc' .
-                                     $currentUpdateRcInfo->{$channel};
+                                     $to->{'prettyAppv'} . ' (build ' .
+                                     $currentUpdateRcInfo->{$channel} . ')';
                                     last;
                                 }
                             }
 
                             # Note that we munge the copy here, but below
                             # we use $to->{appv} in the SubstitutePath() call
                             # to handle the URL; we do this because we only
                             # want the snippet to have the rc value for its
@@ -979,20 +979,20 @@ sub CreatePastReleasePatchinfo {
                      $config->GetCurrentUpdate(), channel => $channel);
                   
                     my $snippetToAppVersion = $patchLocaleNode->{'appv'};
                     my $prettySnippetToAppVersion =
                      $patchLocaleNode->{'prettyAppv'};
                     foreach my $rcChan (keys(%{$currentReleaseRcInfo})) {
                         if ($rcChan eq $channel) {
                             $snippetToAppVersion = $patchLocaleNode->{'appv'} .
-                             'rc' . $currentReleaseRcInfo->{$channel};
+                             'build' . $currentReleaseRcInfo->{$channel};
                             $prettySnippetToAppVersion =
-                             $patchLocaleNode->{'prettyAppv'} . 'rc' .
-                             $currentReleaseRcInfo->{$channel};
+                             $patchLocaleNode->{'prettyAppv'} . ' (build ' .
+                             $currentReleaseRcInfo->{$channel} . ')';
                             last;
                         }
                     }
 
                     my $ausPrefix = catfile($prefixStr, $ausDir, $fromAusApp,
                                              $fromAusVersion, $fromAusPlatform,
                                              $fromAusBuildId, $locale,
                                              $channel);
@@ -1202,20 +1202,20 @@ sub CreatePartialPatchinfo {
 
                     my $snippetDir = GetSnippetDirFromChannel(config =>
                      $u_config->{$u}, channel => $c);
 
                     my $snippetToAppVersion = $to->{'appv'};
                     my $prettySnippetToAppVersion = $to->{'prettyAppv'};
                     foreach my $channel (keys(%{$currentUpdateRcInfo})) {
                         if ($c eq $channel) {
-                            $snippetToAppVersion = $to->{'appv'} . 'rc' .
+                            $snippetToAppVersion = $to->{'appv'} . 'build' .
                              $currentUpdateRcInfo->{$channel};
                             $prettySnippetToAppVersion = $to->{'prettyAppv'} .
-                             'rc' . $currentUpdateRcInfo->{$channel};
+                             ' (build ' . $currentUpdateRcInfo->{$channel} . ')';
 
                             $serveCompleteUpdateToRcs =
                              (!$disableCompleteJumpForRcs) &&
                              (int($currentUpdateRcInfo->{$channel}) > 1);
 
                             if ($serveCompleteUpdateToRcs) {
                                 $snippetPathname = $complete_pathname;
                                 $snippetUrl = $gen_complete_url;
@@ -1241,17 +1241,17 @@ sub CreatePartialPatchinfo {
                     next if ( -e $partial_patch->{'info_path'} or ! -e $snippetPathname );
                     $i++;
 
                     # This is just prettyfication for the PrintProgress() call,
                     # so we know which channels have had rc's added to their
                     # appv's.
                     my $progressVersion = $u;
                     if ($snippetToAppVersion ne $to->{'appv'}) {
-                        $progressVersion =~ s/$to->{'appv'}/$snippetToAppVersion/;
+                        $progressVersion =~ s/\-$to->{'appv'}/-$snippetToAppVersion/;
                     }
                     PrintProgress(total => $total, current => $i,
                      string => "$progressVersion/$p/$l/$c");
 
                     $partial_patch->{'patch_path'} = $snippetPathname;
                     $partial_patch->{'type'} = 'partial';
 
                     $partial_patch->{'hash_type'} = $DEFAULT_HASH_TYPE;
@@ -1318,21 +1318,21 @@ sub CreatePartialPatchinfo {
                             $testPatch->{'size'} = $testPatchSize;
                             $testPatch->{'hash_value'} = $testPatchHash;
 
                             $snippetToAppVersion = $to->{'appv'};
                             $prettySnippetToAppVersion = $to->{'prettyAppv'};
                             foreach my $channel 
                              (keys(%{$currentUpdateRcInfo})) {
                                 if ($testChan eq $channel) {
-                                    $snippetToAppVersion = $to->{'appv'} . 'rc'
+                                    $snippetToAppVersion = $to->{'appv'} . 'build'
                                      . $currentUpdateRcInfo->{$channel};
                                     $prettySnippetToAppVersion =
-                                     $to->{'prettyAppv'} . 'rc' .
-                                     $currentUpdateRcInfo->{$channel};
+                                     $to->{'prettyAppv'} . ' (build ' .
+                                     $currentUpdateRcInfo->{$channel} . ')';
                                     last;
                                 }
                             }
 
                             # Note that we munge the copy here, but below
                             # we use $to->{appv} in the SubstitutePath() call
                             # to handle the URL; we do this because we only
                             # want the snippet to have the rc value for its
--- a/uriloader/exthandler/nsExternalHelperAppService.cpp
+++ b/uriloader/exthandler/nsExternalHelperAppService.cpp
@@ -900,23 +900,26 @@ nsExternalHelperAppService::GetProtocolH
 
   PRBool exists;
   nsresult rv = GetProtocolHandlerInfoFromOS(aScheme, &exists, aHandlerInfo);
   if (NS_FAILED(rv)) {
     // Either it knows nothing, or we ran out of memory
     return NS_ERROR_FAILURE;
   }
   
-  rv = NS_ERROR_FAILURE;
   nsCOMPtr<nsIHandlerService> handlerSvc = do_GetService(NS_HANDLERSERVICE_CONTRACTID);
-  if (handlerSvc)
-    rv = handlerSvc->FillHandlerInfo(*aHandlerInfo, EmptyCString());
-
-  if (NS_SUCCEEDED(rv))
-    return NS_OK;
+  if (handlerSvc) {
+    PRBool hasHandler = PR_FALSE;
+    (void) handlerSvc->Exists(*aHandlerInfo, &hasHandler);
+    if (hasHandler) {
+      rv = handlerSvc->FillHandlerInfo(*aHandlerInfo, EmptyCString());
+      if (NS_SUCCEEDED(rv))
+        return NS_OK;
+    }
+  }
   
   return SetProtocolHandlerDefaults(*aHandlerInfo, exists);
 }
 
 NS_IMETHODIMP
 nsExternalHelperAppService::GetProtocolHandlerInfoFromOS(const nsACString &aScheme,
                                                          PRBool *found,
                                                          nsIHandlerInfo **aHandlerInfo)
@@ -2362,26 +2365,36 @@ NS_IMETHODIMP nsExternalHelperAppService
     return NS_ERROR_OUT_OF_MEMORY;
 
   // (2) Now, let's see if we can find something in our datastore
   // This will not overwrite the OS information that interests us
   // (i.e. default application, default app. description)
   nsresult rv;
   nsCOMPtr<nsIHandlerService> handlerSvc = do_GetService(NS_HANDLERSERVICE_CONTRACTID);
   if (handlerSvc) {
-    rv = handlerSvc->FillHandlerInfo(*_retval, EmptyCString());
-    LOG(("Data source: Via type: retval 0x%08x\n", rv));
+    PRBool hasHandler = PR_FALSE;
+    (void) handlerSvc->Exists(*_retval, &hasHandler);
+    if (hasHandler) {
+      rv = handlerSvc->FillHandlerInfo(*_retval, EmptyCString());
+      LOG(("Data source: Via type: retval 0x%08x\n", rv));
+    } else {
+      rv = NS_ERROR_NOT_AVAILABLE;
+    }
+ 
     found = found || NS_SUCCEEDED(rv);
 
     if (!found || NS_FAILED(rv)) {
       // No type match, try extension match
       if (!aFileExt.IsEmpty()) {
         nsCAutoString overrideType;
         rv = handlerSvc->GetTypeFromExtension(aFileExt, overrideType);
-        if (NS_SUCCEEDED(rv)) {
+        if (NS_SUCCEEDED(rv) && !overrideType.IsEmpty()) {
+          // We can't check handlerSvc->Exists() here, because we have a
+          // overideType. That's ok, it just results in some console noise.
+          // (If there's no handler for the override type, it throws)
           rv = handlerSvc->FillHandlerInfo(*_retval, overrideType);
           LOG(("Data source: Via ext: retval 0x%08x\n", rv));
           found = found || NS_SUCCEEDED(rv);
         }
       }
     }
   }
 
@@ -2450,17 +2463,17 @@ NS_IMETHODIMP nsExternalHelperAppService
       return rv;
     }
   }
 
   // Check user-set prefs
   nsCOMPtr<nsIHandlerService> handlerSvc = do_GetService(NS_HANDLERSERVICE_CONTRACTID);
   if (handlerSvc)
     rv = handlerSvc->GetTypeFromExtension(aFileExt, aContentType);
-  if (NS_SUCCEEDED(rv))
+  if (NS_SUCCEEDED(rv) && !aContentType.IsEmpty())
     return NS_OK;
 
   // Ask OS.
   PRBool found = PR_FALSE;
   nsCOMPtr<nsIMIMEInfo> mi = GetMIMEInfoFromOS(EmptyCString(), aFileExt, &found);
   if (mi && found)
     return mi->GetMIMEType(aContentType);
 
--- a/uriloader/exthandler/nsHandlerService.js
+++ b/uriloader/exthandler/nsHandlerService.js
@@ -255,23 +255,21 @@ HandlerService.prototype = {
       // nsIExternalProtocolHandlerService.getProtocolHandlerInfo().
       // Necessary because calling that from here would make XPConnect barf
       // when getService tried to re-enter the constructor for this
       // service.
       let osDefaultHandlerFound = {};
       let protoInfo = protoSvc.getProtocolHandlerInfoFromOS(scheme, 
                                osDefaultHandlerFound);
       
-      try {
+      if (this.exists(protoInfo))
         this.fillHandlerInfo(protoInfo, null);
-      } catch (ex) {
-        // pick some sane defaults
+      else
         protoSvc.setProtocolHandlerDefaults(protoInfo, 
                                             osDefaultHandlerFound.value);
-      }
 
       // cache the possible handlers to avoid extra xpconnect traversals.      
       let possibleHandlers = protoInfo.possibleApplicationHandlers;
 
       for each (var handlerPrefs in schemes[scheme]) {
 
         let handlerApp = Cc["@mozilla.org/uriloader/web-handler-app;1"].
                          createInstance(Ci.nsIWebHandlerApp);
@@ -399,18 +397,27 @@ HandlerService.prototype = {
 
     // Write the changes to the database immediately so we don't lose them
     // if the application crashes.
     if (this._ds instanceof Ci.nsIRDFRemoteDataSource)
       this._ds.Flush();
   },
 
   exists: function HS_exists(aHandlerInfo) {
-    var typeID = this._getTypeID(this._getClass(aHandlerInfo), aHandlerInfo.type);
-    return this._hasLiteralAssertion(typeID, NC_VALUE, aHandlerInfo.type);
+    var found;
+
+    try {
+      var typeID = this._getTypeID(this._getClass(aHandlerInfo), aHandlerInfo.type);
+      found = this._hasLiteralAssertion(typeID, NC_VALUE, aHandlerInfo.type);
+    } catch (e) {
+      // If the RDF threw (eg, corrupt file), treat as non-existent.
+      found = false;
+    }
+
+    return found;
   },
 
   remove: function HS_remove(aHandlerInfo) {
     var preferredHandlerID =
       this._getPreferredHandlerID(this._getClass(aHandlerInfo), aHandlerInfo.type);
     this._removeAssertions(preferredHandlerID);
 
     var infoID = this._getInfoID(this._getClass(aHandlerInfo), aHandlerInfo.type);
@@ -465,17 +472,17 @@ HandlerService.prototype = {
 
     if (typeID && this._hasValue(typeID, NC_VALUE)) {
       let type = this._getValue(typeID, NC_VALUE);
       if (type == "")
         throw Cr.NS_ERROR_FAILURE;
       return type;
     }
 
-    throw Cr.NS_ERROR_NOT_AVAILABLE;
+    return "";
   },
 
 
   //**************************************************************************//
   // Retrieval Methods
 
   /**
    * Retrieve the preferred action for the info record with the given ID.
--- a/uriloader/exthandler/nsIHandlerService.idl
+++ b/uriloader/exthandler/nsIHandlerService.idl
@@ -85,17 +85,19 @@ interface nsIHandlerService : nsISupport
    * In that situation, you can call this method to fill in the handler info
    * object with information about that other type by passing the other type
    * as the aOverrideType parameter.
    *
    * @param aHandlerInfo   the handler info object
    * @param aOverrideType  a type to use instead of aHandlerInfo::type
    *
    * Note: if there is no information in the datastore about this type,
-   * this method throws NS_ERROR_NOT_AVAILABLE.
+   * this method throws NS_ERROR_NOT_AVAILABLE. Callers are encouraged to
+   * check exists() before calling fillHandlerInfo(), to prevent spamming the
+   * console with XPCOM exception errors.
    */
   void fillHandlerInfo(in nsIHandlerInfo aHandlerInfo,
                        in ACString aOverrideType);
 
   /**
    * Save the preferred action, preferred handler, possible handlers, and
    * always ask properties of the given handler info object to the datastore.
    * Updates an existing record or creates a new one if necessary.
@@ -104,17 +106,18 @@ interface nsIHandlerService : nsISupport
    * the default value nsIHandlerInfo::useHelperApp.
    *
    * @param aHandlerInfo  the handler info object
    */
   void store(in nsIHandlerInfo aHandlerInfo);
 
   /**
    * Whether or not a record for the given handler info object exists
-   * in the datastore.
+   * in the datastore. If the datastore is corrupt (or some other error
+   * is caught in the implementation), false will be returned.
    *
    * @param aHandlerInfo  a handler info object
    *
    * @returns whether or not a record exists
    */
   boolean exists(in nsIHandlerInfo aHandlerInfo);
 
   /**
@@ -135,12 +138,12 @@ interface nsIHandlerService : nsISupport
    *
    * Note: in general, you should use nsIMIMEService::getTypeFromExtension
    * to get a MIME type from a file extension, as that method checks a variety
    * of other sources besides just the datastore.  Use this only when you want
    * to specifically get only the mapping available in the datastore.
    *
    * @param aFileExtension  the file extension
    *
-   * @returns the MIME type, if any; otherwise throws NS_ERROR_NOT_AVAILABLE
+   * @returns the MIME type, if any; otherwise returns an empty string ("").
    */
   ACString getTypeFromExtension(in ACString aFileExtension);
 };
--- a/uriloader/exthandler/tests/unit/test_handlerService.js
+++ b/uriloader/exthandler/tests/unit/test_handlerService.js
@@ -46,16 +46,19 @@ function run_test() {
                   getService(Ci.nsIMIMEService);
 
   const protoSvc = Cc["@mozilla.org/uriloader/external-protocol-service;1"].
                    getService(Ci.nsIExternalProtocolService);
   
   const prefSvc = Cc["@mozilla.org/preferences-service;1"].
                   getService(Ci.nsIPrefService);
                   
+  const ioService = Cc["@mozilla.org/network/io-service;1"].
+                    getService(Ci.nsIIOService);
+
   const rootPrefBranch = prefSvc.getBranch("");
   
   //**************************************************************************//
   // Sample Data
 
   // It doesn't matter whether or not this nsIFile is actually executable,
   // only that it has a path and exists.  Since we don't know any executable
   // that exists on all platforms (except possibly the application being
@@ -331,9 +334,53 @@ function run_test() {
   // Make sure the handler is the one we didn't remove.
   webPossibleHandler = possibleHandlersInfo.possibleApplicationHandlers.
                        queryElementAt(0, Ci.nsIWebHandlerApp);
   do_check_eq(webPossibleHandler.name, webHandler.name);
   do_check_true(webPossibleHandler.equals(webHandler));
 
   // FIXME: test round trip integrity for a protocol.
   // FIXME: test round trip integrity for a handler info with a web handler.
+
+  //**************************************************************************//
+  // getTypeFromExtension tests
+
+  // test non-existent extension
+  var lolType = handlerSvc.getTypeFromExtension("lolcat");
+  do_check_eq(lolType, "");
+
+
+  // add a handler for the extension
+  var lolHandler = mimeSvc.getFromTypeAndExtension("application/lolcat", null);
+
+  do_check_false(lolHandler.extensionExists("lolcat"));
+  lolHandler.preferredAction = Ci.nsIHandlerInfo.useHelperApp;
+  lolHandler.preferredApplicationHandler = localHandler;
+  lolHandler.alwaysAskBeforeHandling = false;
+
+  // store the handler
+  do_check_false(handlerSvc.exists(lolHandler));
+  handlerSvc.store(lolHandler);
+  do_check_true(handlerSvc.exists(lolHandler));
+
+  // Get a file:// string pointing to mimeTypes.rdf
+  var rdfFile = HandlerServiceTest._dirSvc.get("UMimTyp", Ci.nsIFile);
+  var fileHandler = ioService.getProtocolHandler("file").QueryInterface(Ci.nsIFileProtocolHandler);
+  var rdfFileURI = fileHandler.getURLSpecFromFile(rdfFile);
+
+  // Assign a file extenstion to the handler. handlerSvc.store() doesn't
+  // actually store any file extensions added with setFileExtensions(), you
+  // have to wade into RDF muck to do so.
+
+  // Based on toolkit/mozapps/downloads/content/helperApps.js :: addExtension()
+  var gRDF = Cc["@mozilla.org/rdf/rdf-service;1"].getService(Ci.nsIRDFService);
+  var mimeSource    = gRDF.GetUnicodeResource("urn:mimetype:application/lolcat");
+  var valueProperty = gRDF.GetUnicodeResource("http://home.netscape.com/NC-rdf#fileExtensions");
+  var mimeLiteral   = gRDF.GetLiteral("lolcat");
+
+  var DS = gRDF.GetDataSourceBlocking(rdfFileURI);
+  DS.Assert(mimeSource, valueProperty, mimeLiteral, true);
+
+
+  // test now-existent extension
+  lolType = handlerSvc.getTypeFromExtension("lolcat");
+  do_check_eq(lolType, "application/lolcat");
 }
--- a/widget/public/nsILookAndFeel.h
+++ b/widget/public/nsILookAndFeel.h
@@ -155,17 +155,21 @@ public:
     eColor__moz_mac_accentlightshadow,
     eColor__moz_mac_accentregularshadow,
     eColor__moz_mac_accentdarkshadow,
     eColor__moz_mac_accentdarkestshadow,
     
     //new in 10.2
     eColor__moz_mac_alternateprimaryhighlight, //active list highlight
     eColor__moz_mac_secondaryhighlight,        //inactive light hightlight
-  
+
+    // vista rebars
+    eColor__moz_win_mediatext,                     // media rebar text
+    eColor__moz_win_communicationstext,            // communications rebar text
+
     // keep this one last, please
     eColor_LAST_COLOR
   } nsColorID;
 
   // When modifying this list, also modify nsXPLookAndFeel::sIntPrefs
   // in widget/src/xpwidgts/nsXPLookAndFeel.cpp.
   typedef enum {
     eMetric_WindowTitleHeight,
--- a/widget/src/cocoa/nsMenuBarX.mm
+++ b/widget/src/cocoa/nsMenuBarX.mm
@@ -1040,16 +1040,21 @@ static BOOL gActOnSpecialCommands = YES;
       if (mostSpecificContent) {
         MenuHelpersX::DispatchCommandTo(mostSpecificContent);
       }
       else {
         [NSApp terminate:nil];
         return;
       }
     }
+    // Quit now if the "active" menu bar has changed (as the result of
+    // processing an app-global command above).  This resolves bmo bug
+    // 430506.
+    if (menuBar != nsMenuBarX::sLastGeckoMenuBarPainted)
+      return;
   }
 
   // Don't do anything unless this is not a keyboard command and
   // this isn't for the hidden window menu. We assume that if there
   // is no main window then the hidden window menu bar is up, even
   // if that isn't true for some reason we better play it safe if
   // there is no main window.
   if (gPerformKeyEquivOnStack && !gActOnKeyEquiv && [NSApp mainWindow])
--- a/widget/src/cocoa/nsMenuX.mm
+++ b/widget/src/cocoa/nsMenuX.mm
@@ -84,17 +84,17 @@ static PRBool gMenuMethodsSwizzled = PR_
 
 // CIDs
 #include "nsWidgetsCID.h"
 static NS_DEFINE_CID(kMenuCID,     NS_MENU_CID);
 static NS_DEFINE_CID(kMenuItemCID, NS_MENUITEM_CID);
 
 NS_IMPL_ISUPPORTS1(nsMenuX, nsIMenu)
 
-PRInt32 nsMenuX::sIndexingMenuLevel = nsnull;
+PRInt32 nsMenuX::sIndexingMenuLevel = 0;
 
 
 nsMenuX::nsMenuX()
 : mVisibleItemsCount(0), mParent(nsnull), mMenuBar(nsnull), mMacMenuID(0), 
   mMacMenu(nil), mNativeMenuItem(nil), mIsEnabled(PR_TRUE),
   mDestroyHandlerCalled(PR_FALSE), mNeedsRebuild(PR_TRUE),
   mConstructed(PR_FALSE), mVisible(PR_TRUE), mXBLAttached(PR_FALSE)
 {
--- a/widget/src/gtk2/nsWindow.cpp
+++ b/widget/src/gtk2/nsWindow.cpp
@@ -5458,16 +5458,22 @@ nsWindow::IMEDestroyContext(void)
     if (mIMEData->mContext) {
         workaround_gtk_im_display_closed(GTK_WIDGET(mContainer),
                                          mIMEData->mContext);
         gtk_im_context_set_client_window(mIMEData->mContext, nsnull);
         g_object_unref(G_OBJECT(mIMEData->mContext));
         mIMEData->mContext = nsnull;
     }
 
+    if (mIMEData->mSimpleContext) {
+        gtk_im_context_set_client_window(mIMEData->mSimpleContext, nsnull);
+        g_object_unref(G_OBJECT(mIMEData->mSimpleContext));
+        mIMEData->mSimpleContext = nsnull;
+    }
+
     if (mIMEData->mDummyContext) {
         // mIMEData->mContext and mIMEData->mDummyContext have the same
         // slaveType and signal_data so no need for another
         // workaround_gtk_im_display_closed.
         gtk_im_context_set_client_window(mIMEData->mDummyContext, nsnull);
         g_object_unref(G_OBJECT(mIMEData->mDummyContext));
         mIMEData->mDummyContext = nsnull;
     }
@@ -5483,17 +5489,17 @@ nsWindow::IMESetFocus(void)
     LOGIM(("IMESetFocus %p\n", (void *)this));
     GtkIMContext *im = IMEGetContext();
     if (!im)
         return;
 
     gtk_im_context_focus_in(im);
     gIMEFocusWindow = this;
 
-    if (!IMEIsEnabled()) {
+    if (!IMEIsEnabledState()) {
         // We should release IME focus for uim and scim.
         // These IMs are using snooper that is released at losing focus.
         IMELoseFocus();
     }
 }
 
 void
 nsWindow::IMELoseFocus(void)
@@ -5629,25 +5635,38 @@ GtkIMContext*
 nsWindow::IMEGetContext()
 {
     return IM_get_input_context(this);
 }
 
 static PRBool
 IsIMEEnabledState(PRUint32 aState)
 {
-    return aState == nsIKBStateControl::IME_STATUS_ENABLED ? PR_TRUE : PR_FALSE;
+    return aState == nsIKBStateControl::IME_STATUS_ENABLED;
 }
 
 PRBool
-nsWindow::IMEIsEnabled(void)
+nsWindow::IMEIsEnabledState(void)
 {
     return mIMEData ? IsIMEEnabledState(mIMEData->mEnabled) : PR_FALSE;
 }
 
+static PRBool
+IsIMEEditableState(PRUint32 aState)
+{
+    return aState == nsIKBStateControl::IME_STATUS_ENABLED ||
+           aState == nsIKBStateControl::IME_STATUS_PASSWORD;
+}
+
+PRBool
+nsWindow::IMEIsEditableState(void)
+{
+    return mIMEData ? IsIMEEditableState(mIMEData->mEnabled) : PR_FALSE;
+}
+
 nsWindow*
 nsWindow::IMEComposingWindow(void)
 {
     return mIMEData ? mIMEData->mComposingWindow : nsnull;
 }
 
 nsWindow*
 nsWindow::IMEGetOwningWindow(void)
@@ -5659,38 +5678,46 @@ nsWindow::IMEGetOwningWindow(void)
 void
 nsWindow::IMECreateContext(void)
 {
     mIMEData = new nsIMEData(this);
     if (!mIMEData)
         return;
 
     mIMEData->mContext = gtk_im_multicontext_new();
+    mIMEData->mSimpleContext = gtk_im_context_simple_new();
     mIMEData->mDummyContext = gtk_im_multicontext_new();
-    if (!mIMEData->mContext || !mIMEData->mDummyContext) {
+    if (!mIMEData->mContext || !mIMEData->mSimpleContext ||
+        !mIMEData->mDummyContext) {
         NS_ERROR("failed to create IM context.");
         IMEDestroyContext();
         return;
     }
 
     gtk_im_context_set_client_window(mIMEData->mContext,
                                      GTK_WIDGET(mContainer)->window);
+    gtk_im_context_set_client_window(mIMEData->mSimpleContext,
+                                     GTK_WIDGET(mContainer)->window);
     gtk_im_context_set_client_window(mIMEData->mDummyContext,
                                      GTK_WIDGET(mContainer)->window);
 
     g_signal_connect(G_OBJECT(mIMEData->mContext), "preedit_changed",
                      G_CALLBACK(IM_preedit_changed_cb), this);
     g_signal_connect(G_OBJECT(mIMEData->mContext), "commit",
                      G_CALLBACK(IM_commit_cb), this);
+    g_signal_connect(G_OBJECT(mIMEData->mSimpleContext), "preedit_changed",
+                     G_CALLBACK(IM_preedit_changed_cb), this);
+    g_signal_connect(G_OBJECT(mIMEData->mSimpleContext), "commit",
+                     G_CALLBACK(IM_commit_cb), this);
 }
 
 PRBool
 nsWindow::IMEFilterEvent(GdkEventKey *aEvent)
 {
-    if (!IMEIsEnabled())
+    if (!IMEIsEditableState())
         return FALSE;
 
     GtkIMContext *im = IMEGetContext();
     if (!im)
         return FALSE;
 
     gKeyEvent = aEvent;
     gboolean filtered = gtk_im_context_filter_keypress(im, aEvent);
@@ -5761,43 +5788,39 @@ nsWindow::GetIMEOpenState(PRBool* aState
 
 NS_IMETHODIMP
 nsWindow::SetIMEEnabled(PRUint32 aState)
 {
     IMEInitData();
     if (!mIMEData)
         return NS_OK;
 
-    PRBool newState = IsIMEEnabledState(aState);
-    PRBool oldState = IsIMEEnabledState(mIMEData->mEnabled);
-    if (newState == oldState) {
-        mIMEData->mEnabled = aState;
+    if (aState == mIMEData->mEnabled)
         return NS_OK;
-    }
 
     GtkIMContext *focusedIm = nsnull;
     // XXX Don't we need to check gFocusWindow?
     nsRefPtr<nsWindow> focusedWin = gIMEFocusWindow;
     if (focusedWin && focusedWin->mIMEData)
         focusedIm = focusedWin->mIMEData->mContext;
 
     if (focusedIm && focusedIm == mIMEData->mContext) {
         // Release current IME focus if IME is enabled.
-        if (oldState) {
+        if (IsIMEEditableState(mIMEData->mEnabled)) {
             focusedWin->ResetInputState();
             focusedWin->IMELoseFocus();
         }
 
         mIMEData->mEnabled = aState;
 
         // Even when aState is not PR_TRUE, we need to set IME focus.
         // Because some IMs are updating the status bar of them in this time.
         focusedWin->IMESetFocus();
     } else {
-        if (oldState)
+        if (IsIMEEditableState(mIMEData->mEnabled))
             ResetInputState();
         mIMEData->mEnabled = aState;
     }
 
     return NS_OK;
 }
 
 NS_IMETHODIMP
@@ -6124,17 +6147,21 @@ IM_get_owning_window(MozDrawingarea *aAr
 GtkIMContext *
 IM_get_input_context(nsWindow *aWindow)
 {
     if (!aWindow)
         return nsnull;
     nsWindow::nsIMEData *data = aWindow->mIMEData;
     if (!data)
         return nsnull;
-    return data->mEnabled ? data->mContext : data->mDummyContext;
+    if (data->mEnabled == nsIKBStateControl::IME_STATUS_ENABLED)
+        return data->mContext;
+    if (data->mEnabled == nsIKBStateControl::IME_STATUS_PASSWORD)
+        return data->mSimpleContext;
+    return data->mDummyContext;
 }
 
 #endif
 
 // return the gfxASurface for rendering to this widget
 gfxASurface*
 nsWindow::GetThebesSurface()
 {
--- a/widget/src/gtk2/nsWindow.h
+++ b/widget/src/gtk2/nsWindow.h
@@ -279,31 +279,43 @@ public:
     void               IMEComposeText    (const PRUnichar *aText,
                                           const PRInt32 aLen,
                                           const gchar *aPreeditString,
                                           const gint aCursorPos,
                                           const PangoAttrList *aFeedback);
     void               IMEComposeEnd     (void);
     GtkIMContext*      IMEGetContext     (void);
     nsWindow*          IMEGetOwningWindow(void);
-    PRBool             IMEIsEnabled      (void);
+    // "Enabled" means the users can use all IMEs.
+    // I.e., the focus is in the normal editors.
+    PRBool             IMEIsEnabledState (void);
+    // "Editable" means the users can input characters. They may be not able to
+    // use IMEs but they can use dead keys.
+    // I.e., the forcus is in the normal editors or the password editors or
+    // the |ime-mode: disabled;| editors.
+    PRBool             IMEIsEditableState(void);
     nsWindow*          IMEComposingWindow(void);
     void               IMECreateContext  (void);
     PRBool             IMEFilterEvent    (GdkEventKey *aEvent);
 
     /*
      *  |mIMEData| has all IME data for the window and its children widgets.
      *  Only stand-alone windows and child windows embedded in non-Mozilla GTK
      *  containers own IME contexts.
      *  But this is referred from all children after the widget gets focus.
      *  The children refers to its owning window's object.
      */
     struct nsIMEData {
         // Actual context. This is used for handling the user's input.
         GtkIMContext       *mContext;
+        // mSimpleContext is used for the password field and
+        // the |ime-mode: disabled;| editors. These editors disable IME.
+        // But dead keys should work. Fortunately, the simple IM context of
+        // GTK2 support only them.
+        GtkIMContext       *mSimpleContext;
         // mDummyContext is a dummy context and will be used in IMESetFocus()
         // when mEnabled is false. This mDummyContext IM state is always
         // "off", so it works to switch conversion mode to OFF on IM status
         // window.
         GtkIMContext       *mDummyContext;
         // This mComposingWindow is set in IMEComposeStart(), when user starts
         // composition, then unset in IMEComposeEnd() when user ends the
         // composition. We will keep the widget where the actual composition is
@@ -317,16 +329,17 @@ public:
         nsWindow           *mOwner;
         // The reference counter. When this will be zero by the decrement,
         // the decrementer must free the instance.
         PRUint32           mRefCount;
         // IME enabled state in this window.
         PRUint32           mEnabled;
         nsIMEData(nsWindow* aOwner) {
             mContext         = nsnull;
+            mSimpleContext   = nsnull;
             mDummyContext    = nsnull;
             mComposingWindow = nsnull;
             mOwner           = aOwner;
             mRefCount        = 1;
             mEnabled         = nsIKBStateControl::IME_STATUS_ENABLED;
         }
     };
     nsIMEData          *mIMEData;
--- a/widget/src/windows/nsLookAndFeel.cpp
+++ b/widget/src/windows/nsLookAndFeel.cpp
@@ -60,24 +60,29 @@ static OpenThemeDataPtr openTheme = NULL
 static CloseThemeDataPtr closeTheme = NULL;
 static GetThemeColorPtr getThemeColor = NULL;
 static IsAppThemedPtr isAppThemed = NULL;
 static GetCurrentThemeNamePtr getCurrentThemeName = NULL;
 
 static const char kThemeLibraryName[] = "uxtheme.dll";
 static HINSTANCE gThemeDLLInst = NULL;
 static HANDLE gMenuTheme = NULL;
+static HANDLE gMediaToolbarTheme = NULL;
+static HANDLE gCommunicationsToolbarTheme = NULL;
 
 #define MENU_POPUPITEM 14
+#define TP_BUTTON 1
 
 #define MPI_NORMAL 1
 #define MPI_HOT 2
 #define MPI_DISABLED 3
 #define MPI_DISABLEDHOT 4
 
+#define TS_NORMAL 1
+
 // From tmschema.h in the Vista SDK
 #define TMT_TEXTCOLOR 3803
 
 #endif
 
 // Constants only found in new (2K+, XP+, etc.) Windows.
 #ifndef COLOR_MENUHILIGHT
 #define COLOR_MENUHILIGHT    29
@@ -121,32 +126,59 @@ nsLookAndFeel::nsLookAndFeel() : nsXPLoo
   if(gThemeDLLInst)
   {
     openTheme = (OpenThemeDataPtr)GetProcAddress(gThemeDLLInst, "OpenThemeData");
     closeTheme = (CloseThemeDataPtr)GetProcAddress(gThemeDLLInst, "CloseThemeData");
     getThemeColor = (GetThemeColorPtr)GetProcAddress(gThemeDLLInst, "GetThemeColor");
     isAppThemed = (IsAppThemedPtr)GetProcAddress(gThemeDLLInst, "IsAppThemed");
     getCurrentThemeName = (GetCurrentThemeNamePtr)GetProcAddress(gThemeDLLInst, "GetCurrentThemeName");
     gMenuTheme = openTheme(NULL, L"Menu");
+    gMediaToolbarTheme = openTheme(NULL, L"Media::ToolBar");
+    gCommunicationsToolbarTheme = openTheme(NULL, L"Communications::ToolBar");
   }
 #endif
 }
 
 nsLookAndFeel::~nsLookAndFeel()
 {
 #ifndef WINCE
    if (gShell32DLLInst)
    {
        FreeLibrary(gShell32DLLInst);
        gShell32DLLInst = NULL;
        gSHAppBarMessage = NULL;
    }
 #endif
 }
 
+nsresult nsLookAndFeel::GetColorFromTheme(const PRUnichar* aClassList,
+                                          void* aTheme,
+                                          PRInt32 aPart,
+                                          PRInt32 aState,
+                                          PRInt32 aPropId,
+                                          nscolor &aColor)
+{
+  COLORREF color;
+  HRESULT hr;
+  hr = getThemeColor(aTheme, aPart, aState, aPropId, &color);
+  // Since we don't get theme changed messages, check if we lost the handle
+  if (hr == E_HANDLE)
+  {
+    closeTheme(aTheme);
+    aTheme = openTheme(NULL, (LPCWSTR)aClassList);
+    hr = getThemeColor(aTheme, aPart, aState, aPropId, &color);
+  }
+  if (hr == S_OK)
+  {
+    aColor = COLOREF_2_NSRGB(color);
+    return NS_OK;
+  }
+  return NS_ERROR_FAILURE;
+}
+
 nsresult nsLookAndFeel::NativeGetColor(const nsColorID aID, nscolor &aColor)
 {
   nsresult res = NS_OK;
 
   int idx;
   switch (aID) {
     case eColor_WindowBackground:
         idx = COLOR_WINDOW;
@@ -255,35 +287,20 @@ nsresult nsLookAndFeel::NativeGetColor(c
                 COLOR_MENUTEXT;
         break;
       }
       // Fall through
     case eColor__moz_menuhovertext:
 #ifndef WINCE
       if (isAppThemed && isAppThemed() && GetWindowsVersion() >= VISTA_VERSION)
       {
-        COLORREF color;
-        HRESULT hr;
-        hr = getThemeColor(gMenuTheme, MENU_POPUPITEM, MPI_HOT, TMT_TEXTCOLOR, &color);
-        if (hr == S_OK)
-        {
-          aColor = COLOREF_2_NSRGB(color);
-          return NS_OK;
-        }
-        // Since we don't get theme changed messages, check if we lost the handle
-        else if (hr == E_HANDLE)
-        {
-          closeTheme(gMenuTheme);
-          gMenuTheme = openTheme(NULL, L"Menu");
-          // gMenuTheme shouldn't be null since it was non-null before so we
-          // are running on Vista or higher
-          getThemeColor(gMenuTheme, MENU_POPUPITEM, MPI_HOT, TMT_TEXTCOLOR, &color);
-          aColor = COLOREF_2_NSRGB(color);
-          return NS_OK;
-        }
+        res = GetColorFromTheme(L"Menu", gMenuTheme,
+                                MENU_POPUPITEM, MPI_HOT, TMT_TEXTCOLOR, aColor);
+        if (NS_SUCCEEDED(res))
+          return res;
         // fall through to highlight case
       }
 #endif
     case eColor_highlighttext:
     case eColor__moz_html_cellhighlighttext:
       idx = COLOR_HIGHLIGHTTEXT;
       break;
     case eColor_inactiveborder:
@@ -341,16 +358,41 @@ nsresult nsLookAndFeel::NativeGetColor(c
       break;
     case eColor__moz_fieldtext:
       idx = COLOR_WINDOWTEXT;
       break;
     case eColor__moz_dialog:
     case eColor__moz_cellhighlight:
       idx = COLOR_3DFACE;
       break;
+    case eColor__moz_win_mediatext:
+#ifndef WINCE
+      if (isAppThemed && isAppThemed() && GetWindowsVersion() >= VISTA_VERSION) {
+        res = GetColorFromTheme(L"Media::Toolbar", gMediaToolbarTheme,
+                                TP_BUTTON, TS_NORMAL, TMT_TEXTCOLOR, aColor);
+        if (NS_SUCCEEDED(res))
+          return res;
+      }
+      // if we've gotten here just return -moz-dialogtext instead
+#endif
+      idx = COLOR_WINDOWTEXT;
+      break;
+    case eColor__moz_win_communicationstext:
+#ifndef WINCE
+      if (isAppThemed && isAppThemed() && GetWindowsVersion() >= VISTA_VERSION)
+      {
+        res = GetColorFromTheme(L"Communications::Toolbar", gCommunicationsToolbarTheme,
+                                TP_BUTTON, TS_NORMAL, TMT_TEXTCOLOR, aColor);
+        if (NS_SUCCEEDED(res))
+          return res;
+      }
+      // if we've gotten here just return -moz-dialogtext instead
+#endif
+      idx = COLOR_WINDOWTEXT;
+      break;
     case eColor__moz_dialogtext:
     case eColor__moz_cellhighlighttext:
       idx = COLOR_WINDOWTEXT;
       break;
     case eColor__moz_dragtargetzone:
       idx = COLOR_HIGHLIGHTTEXT;
       break;
     case eColor__moz_buttondefault:
--- a/widget/src/windows/nsLookAndFeel.h
+++ b/widget/src/windows/nsLookAndFeel.h
@@ -42,16 +42,22 @@
 #include "nsCOMPtr.h"
 
 class nsLookAndFeel: public nsXPLookAndFeel {
 public:
   nsLookAndFeel();
   virtual ~nsLookAndFeel();
 
   nsresult NativeGetColor(const nsColorID aID, nscolor &aColor);
+  nsresult GetColorFromTheme(const PRUnichar* aClassList,
+                             void* aTheme,
+                             PRInt32 aPart,
+                             PRInt32 aState,
+                             PRInt32 aPropId,
+                             nscolor &aColor);
   NS_IMETHOD GetMetric(const nsMetricID aID, PRInt32 & aMetric);
   NS_IMETHOD GetMetric(const nsMetricFloatID aID, float & aMetric);
   virtual PRUnichar GetPasswordCharacter();
 
 #ifdef NS_DEBUG
   // This method returns the actual (or nearest estimate) 
   // of the Navigator size for a given form control for a given font
   // and font size. This is used in NavQuirks mode to see how closely
--- a/widget/src/windows/nsWindow.cpp
+++ b/widget/src/windows/nsWindow.cpp
@@ -73,16 +73,17 @@
 #include "nsIObserverService.h"
 #include "imgIContainer.h"
 #include "gfxIImageFrame.h"
 #include "nsNativeCharsetUtils.h"
 #include "nsKeyboardLayout.h"
 #include "nsWidgetAtoms.h"
 #include <windows.h>
 #include <process.h>
+#include "nsUnicharUtils.h"
 
 #ifdef WINCE
 #include "aygshell.h"
 #include "imm.h"
 #include "tpcshell.h"
 #else
 // mmsystem.h is needed to build with WIN32_LEAN_AND_MEAN
 #include <mmsystem.h>
@@ -3098,16 +3099,26 @@ PRBool nsWindow::DispatchKeyEvent(PRUint
 
   event.nativeMsg = (void *)&pluginEvent;
 
   PRBool result = DispatchWindowEvent(&event);
 
   return result;
 }
 
+static PRBool
+StringCaseInsensitiveEquals(const PRUint16* aChars1, const PRUint32 aNumChars1,
+                          const PRUint16* aChars2, const PRUint32 aNumChars2) 
+{
+  if (aNumChars1 != aNumChars2)
+    return PR_FALSE;
+
+  nsCaseInsensitiveStringComparator comp;
+  return comp(aChars1, aChars2, aNumChars1) == 0;
+}
 
 //-------------------------------------------------------------------------
 //
 //
 //-------------------------------------------------------------------------
 BOOL nsWindow::OnKeyDown(UINT aVirtualKeyCode, UINT aScanCode, LPARAM aKeyData)
 {
 #ifdef VK_BROWSER_BACK
@@ -3268,33 +3279,78 @@ BOOL nsWindow::OnKeyDown(UINT aVirtualKe
     default:
       if (KeyboardLayout::IsPrintableCharKey(aVirtualKeyCode)) {
         numOfUniChars = numOfShiftStates =
           gKbdLayout.GetUniChars(uniChars, shiftStates,
                                  NS_ARRAY_LENGTH(uniChars));
       }
 
       if (mIsControlDown ^ mIsAltDown) {
+        PRUint8 capsLockState = (::GetKeyState(VK_CAPITAL) & 1) ? eCapsLock : 0;
         numOfUnshiftedChars =
-          gKbdLayout.GetUniCharsWithShiftState(aVirtualKeyCode, 0,
+          gKbdLayout.GetUniCharsWithShiftState(aVirtualKeyCode, capsLockState,
                        unshiftedChars, NS_ARRAY_LENGTH(unshiftedChars));
         numOfShiftedChars =
-          gKbdLayout.GetUniCharsWithShiftState(aVirtualKeyCode, eShift,
+          gKbdLayout.GetUniCharsWithShiftState(aVirtualKeyCode,
+                       capsLockState | eShift,
                        shiftedChars, NS_ARRAY_LENGTH(shiftedChars));
+
         // The current keyboard cannot input alphabets or numerics,
         // we should append them for Shortcut/Access keys.
         // E.g., for Cyrillic keyboard layout.
-        if (((NS_VK_0 <= DOMKeyCode && DOMKeyCode <= NS_VK_9) ||
-             (NS_VK_A <= DOMKeyCode && DOMKeyCode <= NS_VK_Z)) &&
-             unshiftedChars[0] != DOMKeyCode && shiftedChars[0] != DOMKeyCode) {
+        if (NS_VK_A <= DOMKeyCode && DOMKeyCode <= NS_VK_Z) {
           shiftedLatinChar = unshiftedLatinChar = DOMKeyCode;
-          if (NS_VK_A <= DOMKeyCode && DOMKeyCode <= NS_VK_Z)
+          if (capsLockState)
+            shiftedLatinChar += 0x20;
+          else
             unshiftedLatinChar += 0x20;
-          else
-            shiftedLatinChar = 0;
+          if (unshiftedLatinChar == unshiftedChars[0] &&
+              shiftedLatinChar == shiftedChars[0]) {
+              shiftedLatinChar = unshiftedLatinChar = 0;
+          }
+        } else {
+          PRUint16 ch = 0;
+          if (NS_VK_0 <= DOMKeyCode && DOMKeyCode <= NS_VK_9) {
+            ch = DOMKeyCode;
+          } else {
+            switch (aVirtualKeyCode) {
+              case VK_OEM_PLUS:   ch = '+'; break;
+              case VK_OEM_MINUS:  ch = '-'; break;
+            }
+          }
+          if (ch && unshiftedChars[0] != ch && shiftedChars[0] != ch) {
+            // Windows has assigned a virtual key code to the key even though
+            // the character can't be produced with this key.  That probably
+            // means the character can't be produced with any key in the
+            // current layout and so the assignment is based on a QWERTY
+            // layout.  Append this code so that users can access the shortcut.
+            unshiftedLatinChar = ch;
+          }
+        }
+
+        // If the charCode is not ASCII character, we should replace the
+        // charCode with ASCII character only when Ctrl is pressed.
+        // But don't replace the charCode when the charCode is not same as
+        // unmodified characters. In such case, Ctrl is sometimes used for a
+        // part of character inputting key combination like Shift.
+        if (mIsControlDown) {
+          PRUint8 currentState = eCtrl;
+          if (mIsShiftDown)
+            currentState |= eShift;
+
+          PRUint32 ch = mIsShiftDown ? shiftedLatinChar : unshiftedLatinChar;
+          if (ch &&
+              (numOfUniChars == 0 ||
+               StringCaseInsensitiveEquals(uniChars, numOfUniChars,
+                 mIsShiftDown ? shiftedChars : unshiftedChars,
+                 mIsShiftDown ? numOfShiftedChars : numOfUnshiftedChars))) {
+            numOfUniChars = numOfShiftStates = 1;
+            uniChars[0] = ch;
+            shiftStates[0] = currentState;
+          }
         }
       }
   }
 
   if (numOfUniChars > 0 || numOfShiftedChars > 0 || numOfUnshiftedChars > 0) {
     PRUint32 num = PR_MAX(numOfUniChars,
                           PR_MAX(numOfShiftedChars, numOfUnshiftedChars));
     PRUint32 skipUniChars = num - numOfUniChars;
--- a/widget/src/xpwidgets/nsXPLookAndFeel.cpp
+++ b/widget/src/xpwidgets/nsXPLookAndFeel.cpp
@@ -233,17 +233,19 @@ const char nsXPLookAndFeel::sColorPrefs[
   "ui.-moz-mac-accentlightesthighlight",
   "ui.-moz-mac-accentregularhighlight",
   "ui.-moz-mac-accentface",
   "ui.-moz-mac-accentlightshadow",
   "ui.-moz-mac-accentregularshadow",
   "ui.-moz-mac-accentdarkshadow",
   "ui.-moz-mac-accentdarkestshadow",
   "ui.-moz-mac-alternateprimaryhighlight",
-  "ui.-moz-mac-secondaryhighlight"
+  "ui.-moz-mac-secondaryhighlight",
+  "ui.-moz-win-mediatext",
+  "ui.-moz-win-communicationstext"
 };
 
 PRInt32 nsXPLookAndFeel::sCachedColors[nsILookAndFeel::eColor_LAST_COLOR] = {0};
 PRInt32 nsXPLookAndFeel::sCachedColorBits[COLOR_CACHE_SIZE] = {0};
 
 PRBool nsXPLookAndFeel::sInitialized = PR_FALSE;
 
 nsXPLookAndFeel::nsXPLookAndFeel() : nsILookAndFeel()
--- a/xpcom/stub/Makefile.in
+++ b/xpcom/stub/Makefile.in
@@ -58,19 +58,21 @@ REQUIRES	= string \
 		  $(NULL)
 
 LOCAL_INCLUDES	= -I$(srcdir)/../build
 
 CPPSRCS		= nsXPComStub.cpp
 
 ifndef MOZ_ENABLE_LIBXUL
 ifeq ($(OS_TARGET),OS2)
+ifndef MOZ_OS2_HIGH_MEMORY
 CPPSRCS         += nsOS2VACLegacy.cpp
 endif
 endif
+endif
 
 # If we have an import library, then copy that to the SDK.  Otherwise,
 # copy the shared library.
 ifneq (,$(filter OS2 WINCE WINNT,$(OS_ARCH)))
 SDK_LIBRARY = $(IMPORT_LIBRARY)
 else
 SDK_LIBRARY = $(SHARED_LIBRARY)
 endif