Landing MICROB_20070103_BRANCHThis should improve the standalone build story.Patches Wanted, Work will be on the MICROB_20070323_BRANCH
authortimeless@mozdev.org
Fri, 23 Mar 2007 08:56:57 -0700
changeset 36 9bb35e73790f947e53478b76fbc194d0a35c5c1f
parent 35 873c891351defd8b8f5e3b505b43cc99b434e9e9
child 37 e9e4be097803adeace0ffacc128e261163e8c955
push idunknown
push userunknown
push dateunknown
milestone1.9a3pre
Landing MICROB_20070103_BRANCHThis should improve the standalone build story.Patches Wanted, Work will be on the MICROB_20070323_BRANCH
embedding/browser/gtk/src/EmbedCertificates.cpp
embedding/browser/gtk/src/EmbedContentListener.h
embedding/browser/gtk/src/EmbedContextMenuInfo.cpp
embedding/browser/gtk/src/EmbedContextMenuInfo.h
embedding/browser/gtk/src/EmbedDownloadMgr.cpp
embedding/browser/gtk/src/EmbedDownloadMgr.h
embedding/browser/gtk/src/EmbedEventListener.cpp
embedding/browser/gtk/src/EmbedEventListener.h
embedding/browser/gtk/src/EmbedFilePicker.cpp
embedding/browser/gtk/src/EmbedFilePicker.h
embedding/browser/gtk/src/EmbedGlobalHistory.cpp
embedding/browser/gtk/src/EmbedGlobalHistory.h
embedding/browser/gtk/src/EmbedGtkTools.cpp
embedding/browser/gtk/src/EmbedGtkTools.h
embedding/browser/gtk/src/EmbedPasswordMgr.cpp
embedding/browser/gtk/src/EmbedPrivate.cpp
embedding/browser/gtk/src/EmbedPrivate.h
embedding/browser/gtk/src/EmbedProgress.cpp
embedding/browser/gtk/src/EmbedProgress.h
embedding/browser/gtk/src/EmbedPrompter.cpp
embedding/browser/gtk/src/EmbedPrompter.h
embedding/browser/gtk/src/EmbedWindow.cpp
embedding/browser/gtk/src/GtkPromptService.cpp
embedding/browser/gtk/src/Makefile.in
embedding/browser/gtk/src/gtkmozembed.h
embedding/browser/gtk/src/gtkmozembed2.cpp
embedding/browser/gtk/src/gtkmozembed_common.cpp
embedding/browser/gtk/src/gtkmozembed_common.h
embedding/browser/gtk/src/gtkmozembed_download.cpp
embedding/browser/gtk/src/gtkmozembed_download.h
embedding/browser/gtk/src/gtkmozembed_glue.cpp
embedding/browser/gtk/src/gtkmozembedprivate.h
--- a/embedding/browser/gtk/src/EmbedCertificates.cpp
+++ b/embedding/browser/gtk/src/EmbedCertificates.cpp
@@ -286,17 +286,17 @@ EmbedCertificates::ConfirmBadCertificate
   nsIX509Cert *cert,
   PRBool aSecSuccess,
   PRUint32 aError,
   PRBool *_retval)
 {
   nsresult rv;
   gpointer pCert = NULL;
   guint messint = 0;
-  nsCOMPtr<nsIDOMWindow> parent (do_GetInterface (ctx));
+  nsCOMPtr<nsIDOMWindow> parent(do_GetInterface(ctx));
 
   GtkMozEmbedCommon * common = nsnull;
   GtkMozEmbed *parentWidget = GTK_MOZ_EMBED(GetGtkWidgetForDOMWindow(parent));
 
   if (!parentWidget) {
     EmbedCommon * embedcommon = EmbedCommon::GetInstance();
     if (embedcommon)
       common = GTK_MOZ_EMBED_COMMON(embedcommon->mCommon);
--- a/embedding/browser/gtk/src/EmbedContentListener.h
+++ b/embedding/browser/gtk/src/EmbedContentListener.h
@@ -48,17 +48,17 @@ class EmbedPrivate;
 class EmbedContentListener : public nsIURIContentListener,
                              public nsSupportsWeakReference
 {
  public:
 
   EmbedContentListener();
   virtual ~EmbedContentListener();
 
-  nsresult Init (EmbedPrivate *aOwner);
+  nsresult Init(EmbedPrivate *aOwner);
 
   NS_DECL_ISUPPORTS
 
   NS_DECL_NSIURICONTENTLISTENER
 
  private:
 
   EmbedPrivate *mOwner;
--- a/embedding/browser/gtk/src/EmbedContextMenuInfo.cpp
+++ b/embedding/browser/gtk/src/EmbedContextMenuInfo.cpp
@@ -58,30 +58,34 @@
 #include "nsUnicharUtils.h"
 #include "nsIDOMMouseEvent.h"
 #include "nsIDOMNSEvent.h"
 #include "nsIDOMWindow.h"
 #include "nsIDOMWindowCollection.h"
 #include "nsIWebBrowser.h"
 #include "nsIDOM3Document.h"
 #include "nsIContent.h"
+#include "nsIPresShell.h"
 #include "nsIFormControl.h"
 #include "nsIDOMNSHTMLInputElement.h"
 #include "nsIDOMNSHTMLTextAreaElement.h"
 #include "nsIDOMHTMLInputElement.h"
 #include "nsIDOMHTMLTextAreaElement.h"
 #include "nsIDOMNSHTMLDocument.h"
 #include "nsIDOMNodeList.h"
 #include "nsISelection.h"
 #include "nsIDocument.h"
 #include "EmbedPrivate.h"
 #include <stdio.h>
 #include <stdarg.h>
 #include <stdlib.h>
 #include <glib.h>
+#if defined(FIXED_BUG347731) || !defined(MOZ_ENABLE_LIBXUL)
+#include "nsIFrame.h"
+#endif
 
 //*****************************************************************************
 // class EmbedContextMenuInfo
 //*****************************************************************************
 EmbedContextMenuInfo::EmbedContextMenuInfo(EmbedPrivate *aOwner) : mCtxFrameNum(-1), mEmbedCtxType(0)
 {
   mOwner = aOwner;
   mEventNode = nsnull;
@@ -107,28 +111,31 @@ NS_IMPL_ADDREF(EmbedContextMenuInfo)
 NS_IMPL_RELEASE(EmbedContextMenuInfo)
 NS_INTERFACE_MAP_BEGIN(EmbedContextMenuInfo)
 NS_INTERFACE_MAP_ENTRY(nsISupports)
 NS_INTERFACE_MAP_END
 
 nsresult
 EmbedContextMenuInfo::SetFrameIndex()
 {
-  nsCOMPtr <nsIDOMWindowCollection> frames;
-  mCtxDomWindow->GetFrames (getter_AddRefs (frames));
-  nsCOMPtr <nsIDOMWindow> currentWindow;
+  nsCOMPtr<nsIDOMWindowCollection> frames;
+  mCtxDomWindow->GetFrames(getter_AddRefs(frames));
+  nsCOMPtr<nsIDOMWindow> currentWindow;
   PRUint32 frameCount = 0;
-  frames->GetLength (&frameCount);
+  frames->GetLength(&frameCount);
   for (unsigned int i= 0; i < frameCount; i++) {
-    frames->Item(i, getter_AddRefs (currentWindow));
+    frames->Item(i, getter_AddRefs(currentWindow));
     nsCOMPtr<nsIDOMDocument> currentDoc;
-    currentWindow->GetDocument (getter_AddRefs(currentDoc));
+    currentWindow->GetDocument(getter_AddRefs(currentDoc));
     if (currentDoc == mCtxDocument) {
       mCtxFrameNum = i;
       mCtxDomWindow = currentWindow;
+      nsCOMPtr<nsIDocument> doc = do_QueryInterface(currentDoc);
+      if (doc)
+        mCtxDocTitle = doc->GetDocumentTitle();
       return NS_OK;
     }
   }
   return NS_ERROR_FAILURE;
 }
 
 nsresult
 EmbedContextMenuInfo::GetFormControlType(nsIDOMEvent* aEvent)
@@ -141,66 +148,66 @@ EmbedContextMenuInfo::GetFormControlType
   //    mOrigTarget  = target;
   if (SetFormControlType(target)) {
     nsCOMPtr<nsIDOMNode> eventNode = do_QueryInterface(target);
     if (!eventNode)
       return NS_OK;
     //Frame Stuff
     nsCOMPtr<nsIDOMDocument> domDoc;
     nsresult rv = eventNode->GetOwnerDocument(getter_AddRefs(domDoc));
-    if (!NS_SUCCEEDED (rv) || !domDoc) {
+    if (!NS_SUCCEEDED(rv) || !domDoc) {
       return NS_OK;
     }
     mEventNode = eventNode;
     mCtxDocument = domDoc;
     nsCOMPtr<nsIDocument> doc = do_QueryInterface(mCtxDocument);
     if (!doc)
       return NS_OK;
     nsIPresShell *presShell = doc->GetShellAt(0);
     if (!presShell)
       return NS_OK;
     nsCOMPtr<nsIContent> tgContent = do_QueryInterface(mEventTarget);
+	nsIFrame* frame = nsnull;
+#if defined(FIXED_BUG347731) || !defined(MOZ_ENABLE_LIBXUL)
 #ifdef MOZILLA_1_8_BRANCH
-    nsIFrame* frame = nsnull;
     presShell->GetPrimaryFrameFor(tgContent, &frame);
 #else
-    nsIFrame* frame = presShell->GetPrimaryFrameFor(tgContent);
+    frame = presShell->GetPrimaryFrameFor(tgContent);
 #endif
     if (frame)
       mFormRect = frame->GetScreenRectExternal();
+#endif
     return NS_OK;
   }
   return NS_ERROR_FAILURE;
 }
 
 nsresult
 EmbedContextMenuInfo::SetFormControlType(nsIDOMEventTarget *originalTarget)
 {
   nsresult rv = NS_ERROR_FAILURE;
   nsCOMPtr<nsIContent> targetContent = do_QueryInterface(originalTarget);
   mCtxFormType = 0;
 #ifdef MOZILLA_1_8_BRANCH
   if (targetContent && targetContent->IsContentOfType(nsIContent::eHTML_FORM_CONTROL)) {
 #else
   if (targetContent && targetContent->IsNodeOfType(nsIContent::eHTML_FORM_CONTROL)) {
 #endif
-    nsCOMPtr<nsIFormControl> formControl (do_QueryInterface(targetContent));
+    nsCOMPtr<nsIFormControl> formControl(do_QueryInterface(targetContent));
     if (formControl) {
       mCtxFormType = formControl->GetType();
       rv = NS_OK;
       //#ifdef MOZ_LOGGING
       switch (mCtxFormType) {
       case NS_FORM_BUTTON_BUTTON:
         break;
       case NS_FORM_BUTTON_RESET:
         break;
       case NS_FORM_BUTTON_SUBMIT:
         break;
-      case NS_FORM_FIELDSET:
-        break;
       case NS_FORM_INPUT_BUTTON:
         break;
       case NS_FORM_INPUT_CHECKBOX:
         break;
       case NS_FORM_INPUT_FILE:
         mEmbedCtxType |= GTK_MOZ_EMBED_CTX_INPUT;
         break;
       case NS_FORM_INPUT_HIDDEN:
@@ -236,25 +243,25 @@ EmbedContextMenuInfo::SetFormControlType
       case NS_FORM_OBJECT:
         break;
       default:
         break;
       }
       if (mEmbedCtxType & GTK_MOZ_EMBED_CTX_INPUT) {
         PRBool rdonly = PR_FALSE;
         if (mCtxFormType == NS_FORM_TEXTAREA) {
-          nsCOMPtr <nsIDOMHTMLTextAreaElement> input;
+          nsCOMPtr<nsIDOMHTMLTextAreaElement> input;
           input = do_QueryInterface(mEventNode, &rv);
           if (!NS_FAILED(rv) && input)
             rv = input->GetReadOnly(&rdonly);
           if (!NS_FAILED(rv) && rdonly) {
             mEmbedCtxType |= GTK_MOZ_EMBED_CTX_ROINPUT;
           }
         } else {
-          nsCOMPtr <nsIDOMHTMLInputElement> input;
+          nsCOMPtr<nsIDOMHTMLInputElement> input;
           input = do_QueryInterface(mEventNode, &rv);
           if (!NS_FAILED(rv) && input)
             rv = input->GetReadOnly(&rdonly);
           if (!NS_FAILED(rv) && rdonly) {
             mEmbedCtxType |= GTK_MOZ_EMBED_CTX_ROINPUT;
           }
         }
       }
@@ -274,29 +281,29 @@ EmbedContextMenuInfo::GetSelectedText()
     if (mCtxFormType == NS_FORM_INPUT_TEXT || mCtxFormType == NS_FORM_INPUT_FILE) {
       nsCOMPtr<nsIDOMNSHTMLInputElement> nsinput = do_QueryInterface(mEventNode, &rv);
       if (NS_SUCCEEDED(rv) && nsinput)
         nsinput->GetTextLength(&TextLength);
       if (TextLength > 0) {
         nsinput->GetSelectionEnd(&selEnd);
         nsinput->GetSelectionStart(&selStart);
         if (selStart < selEnd || mCtxFormType == NS_FORM_INPUT_FILE) {
-          nsCOMPtr<nsIDOMHTMLInputElement> input = do_QueryInterface (mEventNode, &rv);
+          nsCOMPtr<nsIDOMHTMLInputElement> input = do_QueryInterface(mEventNode, &rv);
           rv = input->GetValue(cString);
         }
       }
     } else if (mCtxFormType == NS_FORM_TEXTAREA) {
       nsCOMPtr<nsIDOMNSHTMLTextAreaElement> nsinput = do_QueryInterface(mEventNode, &rv);
       if (NS_SUCCEEDED(rv) && nsinput)
         nsinput->GetTextLength(&TextLength);
       if (TextLength > 0) {
         nsinput->GetSelectionStart(&selStart);
         nsinput->GetSelectionEnd(&selEnd);
         if (selStart < selEnd) {
-          nsCOMPtr<nsIDOMHTMLTextAreaElement> input = do_QueryInterface (mEventNode, &rv);
+          nsCOMPtr<nsIDOMHTMLTextAreaElement> input = do_QueryInterface(mEventNode, &rv);
           rv = input->GetValue(cString);
         }
       }
     }
     if (NS_SUCCEEDED(rv) && !cString.IsEmpty()) {
       if (selStart < selEnd) {
         cString.Cut(0, selStart);
         cString.Cut(selEnd-selStart, TextLength);
@@ -318,25 +325,25 @@ EmbedContextMenuInfo::GetSelectedText()
   return nsnull;
 }
 
 nsresult
 EmbedContextMenuInfo::CheckDomImageElement(nsIDOMNode *node, nsString& aHref,
                                            PRInt32 *aWidth, PRInt32 *aHeight)
 {
   nsresult rv = NS_ERROR_FAILURE;
-  nsCOMPtr <nsIDOMHTMLImageElement> image =
+  nsCOMPtr<nsIDOMHTMLImageElement> image =
     do_QueryInterface(node, &rv);
   if (image) {
-    rv = image->GetSrc (aHref);
+    rv = image->GetSrc(aHref);
     if (NS_FAILED(rv)) {
       return rv;
     }
-    rv = image->GetWidth (aWidth);
-    rv = image->GetHeight (aHeight);
+    rv = image->GetWidth(aWidth);
+    rv = image->GetHeight(aHeight);
     rv = NS_OK;
   }
   return rv;
 }
 
 nsresult
 EmbedContextMenuInfo::GetImageRequest(imgIRequest **aRequest, nsIDOMNode *aDOMNode)
 {
@@ -347,71 +354,84 @@ EmbedContextMenuInfo::GetImageRequest(im
   nsCOMPtr<nsIImageLoadingContent> content(do_QueryInterface(aDOMNode));
   NS_ENSURE_TRUE(content, NS_ERROR_FAILURE);
 
   return content->GetRequest(nsIImageLoadingContent::CURRENT_REQUEST,
                              aRequest);
 }
 
 nsresult
-EmbedContextMenuInfo::CheckDomHtmlNode(nsIDOMNode *node)
+EmbedContextMenuInfo::CheckDomHtmlNode(nsIDOMNode *aNode)
 {
   nsresult rv = NS_ERROR_FAILURE;
   nsString uTag;
   PRUint16 dnode_type;
+
+  nsCOMPtr<nsIDOMNode> node;
+  if (!aNode && mEventNode)
+    node = mEventNode;
+  nsCOMPtr<nsIDOMHTMLElement> element  = do_QueryInterface(node, &rv);
+  if (!element) {
+    element = do_QueryInterface(mOrigNode, &rv);
+    if (element) {
+      node = mOrigNode;
+      element  = do_QueryInterface(node, &rv);
+    }
+  }
+
   rv = node->GetNodeType(&dnode_type);
   if (NS_FAILED(rv)) {
     return rv;
   }
-  nsCOMPtr<nsIDOMHTMLElement> element  = do_QueryInterface(node);
+
   if (!((nsIDOMNode::ELEMENT_NODE == dnode_type) && element)) {
     return rv;
   }
-  nsCOMPtr <nsIDOMNSHTMLElement> nodeElement = do_QueryInterface(node, &rv);
+  nsCOMPtr<nsIDOMNSHTMLElement> nodeElement = do_QueryInterface(node, &rv);
   if (NS_SUCCEEDED(rv) && nodeElement) {
     mNSHHTMLElement = nodeElement;
   } else {
     mNSHHTMLElement = nsnull;
   }
   rv = element->GetLocalName(uTag);
   if (NS_FAILED(rv)) {
     return rv;
   }
   if (uTag.LowerCaseEqualsLiteral("object")) {
   }
   else if (uTag.LowerCaseEqualsLiteral("html")) {
   }
   else if (uTag.LowerCaseEqualsLiteral("a")) {
-    nsCOMPtr <nsIDOMHTMLAnchorElement> anchor = do_QueryInterface(node);
-    anchor->GetHref (mCtxHref);
+    nsCOMPtr<nsIDOMHTMLAnchorElement> anchor = do_QueryInterface(node);
+    anchor->GetHref(mCtxHref);
     mEmbedCtxType |= GTK_MOZ_EMBED_CTX_LINK;
     if (anchor && !mCtxHref.IsEmpty()) {
       if (mCtxHref.LowerCaseEqualsLiteral("text/smartbookmark")) {
         nsCOMPtr<nsIDOMNode> childNode;
-        node->GetFirstChild (getter_AddRefs(childNode));
+        node->GetFirstChild(getter_AddRefs(childNode));
         if (childNode) {
           PRInt32 width, height;
           rv = CheckDomImageElement(node, mCtxImgHref, &width, &height);
           if (NS_SUCCEEDED(rv))
             mEmbedCtxType |= GTK_MOZ_EMBED_CTX_IMAGE;
         }
       } else if (StringBeginsWith(mCtxHref, NS_LITERAL_STRING("mailto:"))) {
         mEmbedCtxType |= GTK_MOZ_EMBED_CTX_EMAIL;
       }
     }
   }
   else if (uTag.LowerCaseEqualsLiteral("area")) {
-    nsCOMPtr <nsIDOMHTMLAreaElement> area = do_QueryInterface(node, &rv);
+    nsCOMPtr<nsIDOMHTMLAreaElement> area = do_QueryInterface(node, &rv);
     if (NS_SUCCEEDED(rv) && area) {
       PRBool aNoHref = PR_FALSE;
-      rv = area->GetNoHref (&aNoHref);
+      rv = area->GetNoHref(&aNoHref);
       if (aNoHref == PR_FALSE)
-        rv = area->GetHref (mCtxHref);
+        rv = area->GetHref(mCtxHref);
       else
-        rv = area->GetTarget (mCtxHref);
+        rv = area->GetTarget(mCtxHref);
       mEmbedCtxType |= GTK_MOZ_EMBED_CTX_LINK;
       rv = NS_OK;
     }
   }
   else if (uTag.LowerCaseEqualsLiteral("img")) {
     PRInt32 width, height;
     rv = CheckDomImageElement(node, mCtxImgHref, &width, &height);
     if (NS_SUCCEEDED(rv))
@@ -431,40 +451,40 @@ EmbedContextMenuInfo::UpdateContextData(
   if (NS_FAILED(rv) || !event)
     return NS_ERROR_FAILURE;
   return UpdateContextData(event);
 }
 
 nsresult
 EmbedContextMenuInfo::GetElementForScroll(nsIDOMEvent *aEvent)
 {
-    if (!aEvent) return NS_ERROR_UNEXPECTED;
-    nsCOMPtr<nsIDOMNSEvent> nsevent (do_QueryInterface(aEvent));
-    nsCOMPtr<nsIDOMEventTarget> target;
-    nsevent->GetOriginalTarget(getter_AddRefs(target));
-    if (!target) return NS_ERROR_UNEXPECTED;
-    nsCOMPtr<nsIDOMNode> targetDOMNode (do_QueryInterface (target));
-    if (!targetDOMNode) return NS_ERROR_UNEXPECTED;
-    nsCOMPtr <nsIDOMDocument> targetDOMDocument;
-    targetDOMNode->GetOwnerDocument (getter_AddRefs (targetDOMDocument));
-    if (!targetDOMDocument) return NS_ERROR_UNEXPECTED;
-    return GetElementForScroll(targetDOMDocument);
+  if (!aEvent) return NS_ERROR_UNEXPECTED;
+  nsCOMPtr<nsIDOMNSEvent> nsevent(do_QueryInterface(aEvent));
+  nsCOMPtr<nsIDOMEventTarget> target;
+  nsevent->GetOriginalTarget(getter_AddRefs(target));
+  if (!target) return NS_ERROR_UNEXPECTED;
+  nsCOMPtr<nsIDOMNode> targetDOMNode(do_QueryInterface(target));
+  if (!targetDOMNode) return NS_ERROR_UNEXPECTED;
+  nsCOMPtr<nsIDOMDocument> targetDOMDocument;
+  targetDOMNode->GetOwnerDocument(getter_AddRefs(targetDOMDocument));
+  if (!targetDOMDocument) return NS_ERROR_UNEXPECTED;
+  return GetElementForScroll(targetDOMDocument);
 }
 
 nsresult
 EmbedContextMenuInfo::GetElementForScroll(nsIDOMDocument *targetDOMDocument)
 {
-  nsCOMPtr <nsIDOMElement> targetDOMElement;
-  targetDOMDocument->GetDocumentElement (getter_AddRefs (targetDOMElement));
+  nsCOMPtr<nsIDOMElement> targetDOMElement;
+  targetDOMDocument->GetDocumentElement(getter_AddRefs(targetDOMElement));
   if (!targetDOMElement) return NS_ERROR_UNEXPECTED;
-  nsString bodyName (NS_LITERAL_STRING ("body"));
-  nsCOMPtr <nsIDOMNodeList> bodyList;
-  targetDOMElement->GetElementsByTagName(bodyName, getter_AddRefs (bodyList));
+  nsString bodyName(NS_LITERAL_STRING("body"));
+  nsCOMPtr<nsIDOMNodeList> bodyList;
+  targetDOMElement->GetElementsByTagName(bodyName, getter_AddRefs(bodyList));
   PRUint32 i = 0;
-  bodyList->GetLength (&i);
+  bodyList->GetLength(&i);
   if (i) {
     nsCOMPtr<nsIDOMNode> domBodyNode;
     bodyList->Item(0, getter_AddRefs(domBodyNode));
     if (!domBodyNode) return NS_ERROR_UNEXPECTED;
     mNSHHTMLElementSc = do_QueryInterface(domBodyNode);
     if (!mNSHHTMLElementSc) return NS_ERROR_UNEXPECTED;
   }
   return NS_OK;
@@ -482,132 +502,133 @@ EmbedContextMenuInfo::UpdateContextData(
 
   PRUint16 eventphase;
   mCtxEvent->GetEventPhase(&eventphase);
   if (!eventphase) {
     mCtxEvent = nsnull;
     return NS_ERROR_FAILURE;
   }
 
-  nsresult res = nsnull;
   nsCOMPtr<nsIDOMEventTarget> originalTarget = nsnull;
   nsCOMPtr<nsIDOMNode> originalNode = nsnull;
 
   nsCOMPtr<nsIDOMNSEvent> aEvent = do_QueryInterface(mCtxEvent, &rv);
   if (NS_FAILED(rv) || !aEvent)
     return NS_OK;
 
-  nsCOMPtr<nsIDOMMouseEvent> mouseEvent (do_QueryInterface(mCtxEvent, &rv));
-  if(mouseEvent) {
+  nsCOMPtr<nsIDOMMouseEvent> mouseEvent(do_QueryInterface(mCtxEvent, &rv));
+  if (mouseEvent) {
     ((nsIDOMMouseEvent*)mouseEvent)->GetClientX(&mX);
     ((nsIDOMMouseEvent*)mouseEvent)->GetClientY(&mY);
   }
 
   if (aEvent)
-    res = aEvent->GetOriginalTarget(getter_AddRefs(originalTarget));
+    rv = aEvent->GetOriginalTarget(getter_AddRefs(originalTarget));
   originalNode = do_QueryInterface(originalTarget);
-  if (NS_FAILED(res) || !originalNode)
+  if (NS_FAILED(rv) || !originalNode)
     return NS_ERROR_NULL_POINTER;
 
   //    nsresult SelText = mOwner->ClipBoardAction(GTK_MOZ_EMBED_CAN_COPY);
   if (originalNode == mOrigNode)
     return NS_OK;
 
   mEmbedCtxType = GTK_MOZ_EMBED_CTX_NONE;
   mOrigNode = originalNode;
   if (mOrigNode) {
     nsString SOrigNode;
     mOrigNode->GetNodeName(SOrigNode);
-    if (SOrigNode.EqualsLiteral ("#document"))
+    if (SOrigNode.EqualsLiteral("#document"))
       return NS_OK;
-    if (SOrigNode.EqualsLiteral ("xul:thumb")
-        || SOrigNode.EqualsLiteral ("xul:slider")
-        || SOrigNode.EqualsLiteral ("xul:scrollbarbutton")
-        || SOrigNode.EqualsLiteral ("xul:vbox")
-        || SOrigNode.EqualsLiteral ("xul:spacer")) {
+    if (SOrigNode.EqualsLiteral("xul:thumb")
+        || SOrigNode.EqualsLiteral("xul:slider")
+        || SOrigNode.EqualsLiteral("xul:scrollbarbutton")
+        || SOrigNode.EqualsLiteral("xul:vbox")
+        || SOrigNode.EqualsLiteral("xul:spacer")) {
       mEmbedCtxType |= GTK_MOZ_EMBED_CTX_XUL;
       return NS_OK;
     }
   }
   if (mCtxEvent)
-    res = mCtxEvent->GetTarget(getter_AddRefs(mEventTarget));
-  if (NS_FAILED(res) || !mEventTarget) {
+    rv = mCtxEvent->GetTarget(getter_AddRefs(mEventTarget));
+  if (NS_FAILED(rv) || !mEventTarget) {
     return NS_OK;
   }
   nsCOMPtr<nsIDOMNode> eventNode = do_QueryInterface(mEventTarget, &rv);
   mEventNode = eventNode;
   //Frame Stuff
   nsCOMPtr<nsIDOMDocument> domDoc;
   if (mEventNode)
     rv = mEventNode->GetOwnerDocument(getter_AddRefs(domDoc));
-  if (!NS_SUCCEEDED (rv) || !domDoc) {
+  if (!NS_SUCCEEDED(rv) || !domDoc) {
     //  return NS_OK;
   }
-  if (NS_SUCCEEDED (rv) && domDoc && mCtxDocument != domDoc) {
+  if (NS_SUCCEEDED(rv) && domDoc && mCtxDocument != domDoc) {
     mCtxDocument = domDoc;
     mNSHHTMLElementSc = nsnull;
     nsCOMPtr<nsIDOM3Document> docuri = do_QueryInterface(mCtxDocument);
-    docuri->GetDocumentURI (mCtxURI);
+    docuri->GetDocumentURI(mCtxURI);
     NS_ENSURE_ARG_POINTER(mOwner);
     nsCOMPtr<nsIWebBrowser> webBrowser;
     mOwner->mWindow->GetWebBrowser(getter_AddRefs(webBrowser));
     webBrowser->GetContentDOMWindow(getter_AddRefs(mCtxDomWindow));
     nsCOMPtr<nsIDOMDocument> mainDocument;
-    mCtxDomWindow->GetDocument (getter_AddRefs(mainDocument));
+    mCtxDomWindow->GetDocument(getter_AddRefs(mainDocument));
     if (!mainDocument) {
       return NS_OK;
     }
     mCtxFrameNum = -1;
     if (mainDocument != domDoc) {
       mEmbedCtxType |= GTK_MOZ_EMBED_CTX_IFRAME;
       SetFrameIndex();
     }
   }
-  nsCOMPtr <nsIDOMElement> targetDOMElement;
-  mCtxDocument->GetDocumentElement (getter_AddRefs (targetDOMElement));
+  nsCOMPtr<nsIDOMElement> targetDOMElement;
+  mCtxDocument->GetDocumentElement(getter_AddRefs(targetDOMElement));
   if (!targetDOMElement) return NS_ERROR_UNEXPECTED;
   nsCOMPtr<nsIDOMNSHTMLDocument> htmlDoc = do_QueryInterface(mCtxDocument);
   if (htmlDoc) {
     nsString DMode;
     htmlDoc->GetDesignMode(DMode);
-    if (DMode.EqualsLiteral ("on")) {
+    if (DMode.EqualsLiteral("on")) {
       mEmbedCtxType |= GTK_MOZ_EMBED_CTX_INPUT;
       mEmbedCtxType |= GTK_MOZ_EMBED_CTX_RICHEDIT;
     }
   }
   nsCOMPtr<nsIDocument> doc = do_QueryInterface(mCtxDocument);
   if (!doc)
     return NS_OK;
   nsIPresShell *presShell = doc->GetShellAt(0);
   if (!presShell)
     return NS_OK;
   nsCOMPtr<nsIContent> tgContent = do_QueryInterface(mEventTarget);
   nsIFrame* frame = nsnull;
+#if defined(FIXED_BUG347731) || !defined(MOZ_ENABLE_LIBXUL)
   if (mEmbedCtxType & GTK_MOZ_EMBED_CTX_RICHEDIT)
     frame = presShell->GetRootFrame();
   else {
 #ifdef MOZILLA_1_8_BRANCH
-    nsIFrame* frame = nsnull;
+    frame = nsnull;
     presShell->GetPrimaryFrameFor(tgContent, &frame);
 #else
     frame = presShell->GetPrimaryFrameFor(tgContent);
 #endif
   }
   if (frame) {
     mFormRect = frame->GetScreenRectExternal();
   }
+#endif
   if (NS_SUCCEEDED(SetFormControlType(mEventTarget))) {
     return NS_OK;
   }
-  CheckDomHtmlNode(mEventNode);
+  CheckDomHtmlNode();
   nsCOMPtr<nsIDOMNode> node = mEventNode;
   nsCOMPtr<nsIDOMNode> parentNode;
-  node->GetParentNode (getter_AddRefs(parentNode));
+  node->GetParentNode(getter_AddRefs(parentNode));
   node = parentNode;
   while (node) {
-    if (NS_FAILED(CheckDomHtmlNode(node)))
+    if (NS_FAILED(CheckDomHtmlNode()))
       break;
-    node->GetParentNode (getter_AddRefs(parentNode));
+    node->GetParentNode(getter_AddRefs(parentNode));
     node = parentNode;
   }
   mEmbedCtxType |= GTK_MOZ_EMBED_CTX_DOCUMENT;
   return NS_OK;
 }
--- a/embedding/browser/gtk/src/EmbedContextMenuInfo.h
+++ b/embedding/browser/gtk/src/EmbedContextMenuInfo.h
@@ -42,17 +42,17 @@
 #ifndef EmbedContextMenuInfo_h__
 #define EmbedContextMenuInfo_h__
 #include "nsCOMPtr.h"
 #include "nsIDOMNode.h"
 #include "nsIDOMEvent.h"
 #include "imgIContainer.h"
 #include "imgIRequest.h"
 #include "nsIDOMEventTarget.h"
-#include "nsIFrame.h"
+#include "nsRect.h"
 // for strings
 #ifdef MOZILLA_INTERNAL_API
 #include "nsXPIDLString.h"
 #include "nsReadableUtils.h"
 #endif
 #include "EmbedWindow.h"
 #include "nsIDOMNSHTMLElement.h"
 //*****************************************************************************
@@ -69,31 +69,33 @@ public:
   nsresult          UpdateContextData(nsIDOMEvent *aDOMEvent);
   nsresult          UpdateContextData(void *aEvent);
   const char*       GetSelectedText();
   nsresult          GetElementForScroll(nsIDOMDocument *targetDOMDocument);
   nsresult          GetElementForScroll(nsIDOMEvent *aEvent);
   nsresult          CheckDomImageElement(nsIDOMNode *node, nsString& aHref,
                                        PRInt32 *aWidth, PRInt32 *aHeight);
   nsresult          GetImageRequest(imgIRequest **aRequest, nsIDOMNode *aDOMNode);
+  nsString          GetCtxDocTitle(void) { return mCtxDocTitle; };
 
 
   PRInt32                 mX, mY, mObjWidth, mObjHeight, mCtxFrameNum;
   nsString                mCtxURI, mCtxHref, mCtxImgHref;
   PRUint32                mEmbedCtxType;
   PRInt32 mCtxFormType;
   nsCOMPtr<nsIDOMNode>    mEventNode;
   nsCOMPtr<nsIDOMEventTarget> mEventTarget;
   nsCOMPtr<nsIDOMDocument>mCtxDocument;
-  nsIntRect               mFormRect;
+  nsRect               mFormRect;
   nsCOMPtr<nsIDOMWindow>  mCtxDomWindow;
   nsCOMPtr<nsIDOMEvent>   mCtxEvent;
   nsCOMPtr<nsIDOMNSHTMLElement> mNSHHTMLElement;
   nsCOMPtr<nsIDOMNSHTMLElement> mNSHHTMLElementSc;
 private:
   nsresult          SetFrameIndex();
   nsresult          SetFormControlType(nsIDOMEventTarget *originalTarget);
-  nsresult          CheckDomHtmlNode(nsIDOMNode *node);
+  nsresult          CheckDomHtmlNode(nsIDOMNode *aNode = nsnull);
 
   EmbedPrivate           *mOwner;
   nsCOMPtr<nsIDOMNode>    mOrigNode;
+  nsString                mCtxDocTitle;
 }; // class EmbedContextMenuInfo
 #endif // EmbedContextMenuInfo_h__
--- a/embedding/browser/gtk/src/EmbedDownloadMgr.cpp
+++ b/embedding/browser/gtk/src/EmbedDownloadMgr.cpp
@@ -64,241 +64,261 @@
 #include "nsCExternalHandlerService.h"
 #include "nsMemory.h"
 #include "nsNetError.h"
 #include "nsIStreamListener.h"
 #include "nsIFile.h"
 #include "nsILocalFile.h"
 #include "nsNetCID.h"
 #include <unistd.h>
-#include <gtkmozembed_download.h>
+#include "gtkmozembed_download.h"
+#include "nsIIOService.h"
+
+#define UNKNOWN_FILE_SIZE -1
+
 class EmbedDownloadMgr;
 class ProgressListener : public nsIWebProgressListener2
 {
 public:
-    ProgressListener(EmbedDownload *aDownload, nsCAutoString aFilename, nsISupports *aContext) : mFilename (aFilename)
-    {
-        mDownload = aDownload;
-        mContext = aContext;
-    };
-    ~ProgressListener()
+    ProgressListener(EmbedDownload *aDownload):mDownload(aDownload)
     {
     };
+
+    ~ProgressListener(void)
+    {
+    };
+
     NS_DECL_ISUPPORTS
     NS_DECL_NSIWEBPROGRESSLISTENER
     NS_DECL_NSIWEBPROGRESSLISTENER2
+
     EmbedDownload *mDownload;
-    nsISupports *mContext;            /** < The context object */
-    nsCOMPtr<nsILocalFile> mDestFile;
-    nsCAutoString mFilename;
-    nsCAutoString mLocalSaveFileName;
 };
 
 NS_IMPL_ISUPPORTS2(ProgressListener, nsIWebProgressListener2, nsIWebProgressListener)
 NS_IMPL_ISUPPORTS1(EmbedDownloadMgr, nsIHelperAppLauncherDialog)
 
 EmbedDownloadMgr::EmbedDownloadMgr(void)
 {
 }
 
 EmbedDownloadMgr::~EmbedDownloadMgr(void)
 {
 }
 
-nsresult
-EmbedDownloadMgr::Init()
+static gchar *
+RemoveSchemeFromFilePath(gchar *path)
 {
-  return NS_OK;
+  gchar *new_path = path;
+
+  if (!strncmp(path, "file://", 7)) {
+    /* XXX this should really look for the first non / after file:/ instead of
+     * assuming file://tmp v. file:///tmp
+     */
+    new_path = g_strdup(path+sizeof("file:/"));
+    g_free(path);
+  }
+    
+  return new_path;
 }
 
 NS_IMETHODIMP
-EmbedDownloadMgr::Show(nsIHelperAppLauncher *aLauncher, nsISupports *aContext, PRUint32 aForced)
+EmbedDownloadMgr::Show(nsIHelperAppLauncher *aLauncher,
+                       nsISupports *aContext,
+                       PRUint32 aForced)
 {
   nsresult rv;
-  mContext = aContext;
-  mLauncher = aLauncher;
-  rv = GetDownloadInfo();
+
+  /* create a Download object */
+  GtkObject* instance = gtk_moz_embed_download_new();
+  mDownload = (EmbedDownload *) GTK_MOZ_EMBED_DOWNLOAD(instance)->data;
+  mDownload->parent = instance;
+
+  rv = GetDownloadInfo(aLauncher, aContext);
+
+  /* Retrieve GtkMozEmbed object from DOM Window */
+  nsCOMPtr<nsIDOMWindow> parentDOMWindow = do_GetInterface(aContext);
+  mDownload->gtkMozEmbedParentWidget = GetGtkWidgetForDOMWindow(parentDOMWindow);
+
+  gtk_signal_emit(GTK_OBJECT(mDownload->gtkMozEmbedParentWidget),
+                  moz_embed_signals[DOWNLOAD_REQUEST],
+                  mDownload->server,
+                  mDownload->file_name,
+                  mDownload->file_type,
+                  (gulong) mDownload->file_size,
+                   1);
+
+  gtk_signal_emit(GTK_OBJECT(mDownload->parent),
+                  moz_embed_download_signals[DOWNLOAD_STARTED_SIGNAL],
+                  &mDownload->file_name_with_path);
+
+  if (!mDownload->file_name_with_path) {
+    gtk_moz_embed_download_do_command(GTK_MOZ_EMBED_DOWNLOAD(mDownload->parent),
+                                      GTK_MOZ_EMBED_DOWNLOAD_CANCEL);
+    return NS_OK;
+  }
+
+  mDownload->file_name_with_path = RemoveSchemeFromFilePath(mDownload->file_name_with_path);
+
+  return aLauncher->SaveToDisk(nsnull, PR_FALSE);
+}
+
+NS_METHOD
+EmbedDownloadMgr::GetDownloadInfo(nsIHelperAppLauncher *aLauncher,
+                                  nsISupports *aContext)
+{
+  /* File type */
+  nsCOMPtr<nsIMIMEInfo> mimeInfo;
+  nsresult rv = aLauncher->GetMIMEInfo(getter_AddRefs(mimeInfo));
+  if (NS_FAILED(rv))
+    return NS_ERROR_FAILURE;
+
+  nsCAutoString mimeType;
+  rv = mimeInfo->GetMIMEType(mimeType);
+  if (NS_FAILED(rv))
+    return NS_ERROR_FAILURE;
+
+  /* File name */
+  nsCAutoString tempFileName;
+  nsAutoString suggestedFileName;
+  rv = aLauncher->GetSuggestedFileName(suggestedFileName);
+
+  if (NS_FAILED(rv))
+    return NS_ERROR_FAILURE;
+
+  tempFileName = NS_ConvertUTF16toUTF8(suggestedFileName);
+
+  /* Complete source URL */
+  nsCOMPtr<nsIURI> uri;
+  rv = aLauncher->GetSource(getter_AddRefs(uri));
+  if (NS_FAILED(rv))
+    return NS_ERROR_FAILURE;
+
+  nsCAutoString spec;
+  rv = uri->Resolve(NS_LITERAL_CSTRING("."), spec);
+  if (NS_FAILED(rv))
+    return NS_ERROR_FAILURE;
+
+  /* Sets download object to keep control of each download. */
+  mDownload->launcher = aLauncher;
+  mDownload->downloaded_size = -1;
+  mDownload->file_name = g_strdup((gchar *) tempFileName.get());
+  mDownload->server = g_strconcat(spec.get(), (gchar *) mDownload->file_name, NULL);
+  mDownload->file_type = g_strdup(mimeType.get());
+  mDownload->file_size = UNKNOWN_FILE_SIZE;
+
   return NS_OK;
 }
 
-NS_METHOD EmbedDownloadMgr::GetDownloadInfo (void)
+NS_IMETHODIMP EmbedDownloadMgr::PromptForSaveToFile(nsIHelperAppLauncher *aLauncher,
+                                                    nsISupports *aWindowContext,
+                                                    const PRUnichar *aDefaultFile,
+                                                    const PRUnichar *aSuggestedFileExtension,
+                                                    nsILocalFile **_retval)
 {
-  nsresult rv;
-  // create a Download object
-  GtkObject* instance = gtk_moz_embed_download_new ();
-  EmbedDownload *download = (EmbedDownload *) GTK_MOZ_EMBED_DOWNLOAD(instance)->data;
-  // get file mimetype
-  rv = mLauncher->GetMIMEInfo (getter_AddRefs(mMIMEInfo));
-  if (NS_FAILED(rv)) return NS_ERROR_FAILURE;
-  nsCAutoString aMimeType;
-  rv = mMIMEInfo->GetMIMEType (aMimeType);
-  if (NS_FAILED(rv)) return NS_ERROR_FAILURE;
-  // get file name
-  nsCAutoString aTempFileName;
-  nsAutoString aSuggestedFileName;
-  rv = mLauncher->GetSuggestedFileName (aSuggestedFileName);
-  if (NS_FAILED(rv)) return NS_ERROR_FAILURE;
-  aTempFileName = NS_ConvertUTF16toUTF8 (aSuggestedFileName);
-  // get source url (concatened to file name)
-  rv = mLauncher->GetSource (getter_AddRefs(mUri));
-  if (NS_FAILED(rv)) return NS_ERROR_FAILURE;
-  rv = mUri->Resolve(NS_LITERAL_CSTRING("."), mSpec);
-  if (NS_FAILED(rv)) return NS_ERROR_FAILURE;
-  rv = mLauncher->GetTargetFile(getter_AddRefs(mDestFileTemp));
-  if (NS_FAILED(rv)) return NS_ERROR_FAILURE;
-  download->file_target = mDestFileTemp;
-  // creating a progress listener to follow the download and connecting it to the launcher which controls the download.
-  nsCOMPtr<nsIWebProgressListener2> listener = new ProgressListener(download, aTempFileName, mContext);
-  rv = mLauncher->SetWebProgressListener(listener);
-  if (NS_FAILED(rv)) return NS_ERROR_FAILURE;
-  // setting download vars to keep control of each download.
-  download->parent = instance;
-  download->started = 0;
-  download->downloaded_size = -1;
-  download->launcher = mLauncher;
-  download->file_name = g_strdup ((gchar *) aTempFileName.get());
-  download->server = g_strconcat(mSpec.get(), (gchar *) download->file_name, NULL);
-  download->file_type = g_strdup (aMimeType.get());
+  *_retval = nsnull;
+
+  nsCAutoString filePath;
+  filePath.Assign(mDownload->file_name_with_path);
+
+  nsCOMPtr<nsILocalFile> destFile;
+  NS_NewNativeLocalFile(filePath,
+                        PR_TRUE,
+                        getter_AddRefs(destFile));
+  if (!destFile)
+    return NS_ERROR_OUT_OF_MEMORY;
+
+  /* Progress listener to follow the download and connecting it to
+     the launcher which controls the download. */
+  nsCOMPtr<nsIWebProgressListener2> listener = new ProgressListener(mDownload);
+  if (!listener)
+    return NS_ERROR_OUT_OF_MEMORY;
+  
+  nsresult rv = aLauncher->SetWebProgressListener(listener);
+  if (NS_FAILED(rv))
+    return NS_ERROR_FAILURE;
+
+  NS_ADDREF(*_retval = destFile);
   return NS_OK;
 }
 
-// it should be used... but it's not possible to do it according ui flow
-NS_IMETHODIMP EmbedDownloadMgr::PromptForSaveToFile (nsIHelperAppLauncher *aLauncher,
-                                                        nsISupports *aWindowContext,
-                                                        const PRUnichar *aDefaultFile,
-                                                        const PRUnichar *aSuggestedFileExtension,
-                                                        nsILocalFile **_retval)
+/* nsIWebProgressListener Functions
+   all these methods must be here due to nsIWebProgressListener/2 inheritance */
+NS_IMETHODIMP ProgressListener::OnStatusChange(nsIWebProgress *aWebProgress,
+                                               nsIRequest *aRequest,
+                                               nsresult aStatus,
+                                               const PRUnichar *aMessage)
 {
+  if (NS_SUCCEEDED(aStatus))
+    return NS_OK;
+
+  return NS_ERROR_FAILURE;
+}
+
+NS_IMETHODIMP ProgressListener::OnStateChange(nsIWebProgress *aWebProgress,
+                                              nsIRequest *aRequest, PRUint32 aStateFlags,
+                                              nsresult aStatus)
+{
+  if (NS_FAILED(aStatus))
+    return NS_ERROR_FAILURE;
+
+  if (aStateFlags & STATE_STOP)
+    gtk_signal_emit(GTK_OBJECT(mDownload->parent),
+                    moz_embed_download_signals[DOWNLOAD_COMPLETED_SIGNAL]);
+
   return NS_OK;
 }
 
-// nsIWebProgressListener Functions
-// all these methods must be here due to nsIWebProgressListenr/2 inheritance
-NS_IMETHODIMP ProgressListener::OnStatusChange (nsIWebProgress *aWebProgress,
-                                                    nsIRequest *aRequest, nsresult aStatus,
-                                                    const PRUnichar *aMessage)
+NS_IMETHODIMP ProgressListener::OnProgressChange(nsIWebProgress *aWebProgress,
+                                                 nsIRequest *aRequest, PRInt32 aCurSelfProgress,
+                                                 PRInt32 aMaxSelfProgress, PRInt32 aCurTotalProgress,
+                                                 PRInt32 aMaxTotalProgress)
 {
-  if (NS_SUCCEEDED (aStatus))
-    return NS_OK;
-  return NS_ERROR_FAILURE;
+  return OnProgressChange64(aWebProgress,
+                            aRequest,
+                            aCurSelfProgress,
+                            aMaxSelfProgress,
+                            aCurTotalProgress,
+                            aMaxTotalProgress);
 }
 
-NS_IMETHODIMP ProgressListener::OnStateChange (nsIWebProgress *aWebProgress,
-                                                    nsIRequest *aRequest, PRUint32 aStateFlags,
-                                                    nsresult aStatus)
-{
-  if (NS_SUCCEEDED (aStatus))
-    return NS_OK;
-  return NS_ERROR_FAILURE;
-}
-
-NS_IMETHODIMP ProgressListener::OnProgressChange (nsIWebProgress *aWebProgress,
-                                                    nsIRequest *aRequest, PRInt32 aCurSelfProgress,
-                                                    PRInt32 aMaxSelfProgress, PRInt32 aCurTotalProgress,
-                                                    PRInt32 aMaxTotalProgress)
-{
-  return OnProgressChange64 (aWebProgress, aRequest, aCurSelfProgress, aMaxSelfProgress, aCurTotalProgress, aMaxTotalProgress);
-}
-
-NS_IMETHODIMP ProgressListener::OnLocationChange (nsIWebProgress *aWebProgress,
-                                                    nsIRequest *aRequest, nsIURI *location)
+NS_IMETHODIMP ProgressListener::OnLocationChange(nsIWebProgress *aWebProgress,
+                                                 nsIRequest *aRequest, nsIURI *location)
 {
   return NS_ERROR_NOT_IMPLEMENTED;
 }
 
-NS_IMETHODIMP ProgressListener::OnSecurityChange (nsIWebProgress *aWebProgress,
-                                                    nsIRequest *aRequest, PRUint32 state)
+NS_IMETHODIMP ProgressListener::OnSecurityChange(nsIWebProgress *aWebProgress,
+                                                 nsIRequest *aRequest, PRUint32 state)
 {
   return NS_ERROR_NOT_IMPLEMENTED;
 }
 
-// nsIWebProgressListener 2
-NS_IMETHODIMP ProgressListener::OnProgressChange64 (nsIWebProgress *aWebProgress,
-                                                    nsIRequest *aRequest, PRInt64 aCurSelfProgress,
-                                                    PRInt64 aMaxSelfProgress, PRInt64 aCurTotalProgress,
-                                                    PRInt64 aMaxTotalProgress)
+/* nsIWebProgressListener2 method */
+NS_IMETHODIMP ProgressListener::OnProgressChange64(nsIWebProgress *aWebProgress,
+                                                   nsIRequest *aRequest, PRInt64 aCurSelfProgress,
+                                                   PRInt64 aMaxSelfProgress, PRInt64 aCurTotalProgress,
+                                                   PRInt64 aMaxTotalProgress)
 {
-  nsresult rv;
+  mDownload->request = aRequest;
 
-  if (!mDownload) return NS_OK;
-  if (mDownload->started == 0) {
-    mDownload->request = aRequest;
-    mDownload->started = 1;
-    // it might not work when there is more than one browser window opened
-    mDownload->file_size = aMaxSelfProgress;
-    nsCOMPtr<nsIDOMWindow> parentDOMWindow = do_GetInterface (mContext);
-    mDownload->gtkMozEmbedParentWidget = GetGtkWidgetForDOMWindow(parentDOMWindow);
-    if (mDownload->gtkMozEmbedParentWidget) {
-      gtk_signal_emit(GTK_OBJECT(mDownload->gtkMozEmbedParentWidget),
-                                    moz_embed_signals[DOWNLOAD_REQUEST],
-                                    mDownload->server,
-                                    mDownload->file_name,
-                                    mDownload->file_type,
-                                    (gulong) mDownload->file_size,
-                                    1);
-    }
-  }
-  if (mDownload->started == 1) {
-    // emit signal to get download progress and displays on download list dialog
-    gtk_signal_emit(GTK_OBJECT(mDownload->parent),
-                    moz_embed_download_signals[DOWNLOAD_STARTED_SIGNAL], &mDownload->file_name_with_path);
-    // in this case, user has canceled download from UI.
-    if (!mDownload->file_name_with_path) {
-      gtk_moz_embed_download_do_command (GTK_MOZ_EMBED_DOWNLOAD (mDownload->parent), GTK_MOZ_EMBED_DOWNLOAD_CANCEL);
-      return NS_OK;
-    }
-    // FIXME: Clean up this code bellow, please :)
-    gchar *localUrl = nsnull, *localFileName = nsnull;
-    // second step - the target file will be created
-    if (g_str_has_prefix (mDownload->file_name_with_path, FILE_SCHEME)) {
-      // if user has chosen to save file (contains file:// prefix)
-      gchar *localUrlWithFileName = (g_strsplit (mDownload->file_name_with_path, FILE_SCHEME, -1))[1];
-      gint i;
-      gchar **localUrlSplitted = (char **) (g_strsplit(localUrlWithFileName, SLASH, -1));
-      for(i = 0; localUrlSplitted[i]; i++);
-          localFileName = localUrlSplitted[i-1];
-      localUrl = (gchar *) (g_strsplit(localUrlWithFileName, localFileName, -1))[0];
-    } else {
-      // if user has chosen to open with application (in /var/tmp)
-      localUrl = (char *) (g_strsplit (mDownload->file_name_with_path, mFilename.get(), -1))[0];
-      localFileName = g_strdup ((gchar *) mFilename.get());
-    }
-    nsCAutoString localSavePath;
-    if (localUrl) {
-      localSavePath.Assign(localUrl);
-      g_free (localUrl);
-      localUrl = nsnull;
-    }
-    if (localFileName) {
-      mLocalSaveFileName.Assign(localFileName);
-      g_free (localFileName);
-      localFileName = nsnull;
-    }
-    // create the file where the download will be moved to
-    mDestFile = do_CreateInstance(NS_LOCAL_FILE_CONTRACTID);
-    mDestFile->InitWithNativePath(localSavePath);
-    mDestFile->Create(nsIFile::NORMAL_FILE_TYPE, 0777);
-    mDownload->started = 2;
-  }
-  // when download finishes (bytes downloaded = total file size), emit completed signal
-  // FIXME: if you don't have aMaxSelfProgress available, the signal won't be emitted
-  if (aCurSelfProgress == aMaxSelfProgress) {
-    // signal to confirm that download has finished
-    gtk_signal_emit(GTK_OBJECT(mDownload->parent),
-                    moz_embed_download_signals[DOWNLOAD_COMPLETED_SIGNAL]);
-  } else {
-    // emit signal to get download progress and displays on download list dialog
+  if (aMaxSelfProgress != UNKNOWN_FILE_SIZE) {
     gtk_signal_emit(GTK_OBJECT(mDownload->parent),
                     moz_embed_download_signals[DOWNLOAD_PROGRESS_SIGNAL],
                     (gulong) aCurSelfProgress, (gulong) aMaxSelfProgress, 1);
   }
-  // storing current downloaded size.
+  else {
+    gtk_signal_emit(GTK_OBJECT(mDownload->parent),
+                    moz_embed_download_signals[DOWNLOAD_PROGRESS_SIGNAL],
+                    (gulong) aCurSelfProgress, 0, 1);
+  }
+
+  /* storing current downloaded size. */
   mDownload->downloaded_size = (gulong) aCurSelfProgress;
-  // moving the target file to the right place.
-  rv = mDownload->file_target->MoveToNative (mDestFile, mLocalSaveFileName);
+
   return NS_OK;
 }
 
 NS_IMETHODIMP ProgressListener::OnRefreshAttempted(nsIWebProgress *aWebProgress,
                                                    nsIURI *aUri, PRInt32 aDelay,
                                                    PRBool aSameUri,
                                                    PRBool *allowRefresh)
 {
--- a/embedding/browser/gtk/src/EmbedDownloadMgr.h
+++ b/embedding/browser/gtk/src/EmbedDownloadMgr.h
@@ -34,63 +34,65 @@
  * the terms of any one of the MPL, the GPL or the LGPL.
  *
  * ***** END LICENSE BLOCK ***** */
 /**
  * Derived from GContentHandler http://landfill.mozilla.org/mxr-test/gnome/source/galeon/mozilla/ContentHandler.h
  */
 #ifndef __EmbedDownloadMgr_h
 #define __EmbedDownloadMgr_h
+
 #include "EmbedPrivate.h"
 #include "nsIHelperAppLauncherDialog.h"
 #include "nsIMIMEInfo.h"
 #include "nsCOMPtr.h"
 #include "nsIExternalHelperAppService.h"
 #include "nsIRequest.h"
 #include "nsILocalFile.h"
+
 #include "nsWeakReference.h"
 #define EMBED_DOWNLOADMGR_DESCRIPTION "MicroB Download Manager"
 #define EMBED_DOWNLOADMGR_CID {0x53df12a2, 0x1f4a, 0x4382, {0x99, 0x4e, 0xed, 0x62, 0xcf, 0x0d, 0x6b, 0x3a}}
-#define FILE_SCHEME "file://"
-#define SLASH "/"
+
 class nsIURI;
 class nsIFile;
 class nsIFactory;
+class nsExternalAppHandler;
+
 typedef struct _EmbedDownload EmbedDownload;
+
 struct _EmbedDownload
 {
-  GtkObject * parent;
-  GtkWidget* gtkMozEmbedParentWidget;/** Associated gtkmozembed widget */
-  char* file_name;                   /** < The file's name */
-  const char *file_name_with_path;        /** < The file's name */
+  GtkObject*  parent;
+  GtkWidget*  gtkMozEmbedParentWidget;/** Associated gtkmozembed widget */
+
+  char*       file_name;             /** < The file's name */
+  char*       file_name_with_path;   /** < The file's name */
   const char* server;                /** < The server's name */
-  PRInt64 file_size;                 /** < The file's size */
   const char* file_type;             /** < The file's type */
   const char* handler_app;           /** < The application's name */
-  PRInt64 downloaded_size;           /** < The download's size */
-  gboolean isPaused;                 /** < If download is paused or not */
-  gboolean open_with;                /** < If the file can be opened by other application */
-  gboolean started;                  /** < If the download has started or not */
+  PRInt64     file_size;             /** < The file's size */
+  PRInt64     downloaded_size;       /** < The download's size */
+  gboolean    is_paused;             /** < If download is paused or not */
+  gboolean    open_with;             /** < If the file can be opened by other application */
+
+  /* Pointer to mozilla interfaces */
   nsIHelperAppLauncher* launcher;    /** < The mozilla's download dialog */
   nsIRequest* request;               /** < The download request */
-  nsIFile* file_dest;                /** < The final file's name */
-  nsIFile* file_target;              /** < The target file's name */
 };
+
 class EmbedDownloadMgr : public nsIHelperAppLauncherDialog
 {
- public:
-  EmbedDownloadMgr();
-  virtual ~EmbedDownloadMgr();
-  nsresult Init(void);
-  NS_DECL_ISUPPORTS
-  NS_DECL_NSIHELPERAPPLAUNCHERDIALOG
- private:
-  /** Gets all informations about a file which is being downloaded.
-  */
-  NS_METHOD GetDownloadInfo (void);
-  nsCOMPtr<nsIHelperAppLauncher> mLauncher;  /** < Download dialog */
-  nsCOMPtr<nsISupports> mContext;            /** < The context object */
-  nsCOMPtr<nsIURI> mUri;                    /** < The source URL */
-  nsCOMPtr<nsIFile> mDestFileTemp;          /** < The temporary file (destiny) */
-  nsCOMPtr<nsIMIMEInfo> mMIMEInfo;           /** < MIME information */
-  nsCAutoString mSpec;                      /** < The URL without file name */
+  public:
+    EmbedDownloadMgr();
+    virtual ~EmbedDownloadMgr();
+
+    NS_DECL_ISUPPORTS
+    NS_DECL_NSIHELPERAPPLAUNCHERDIALOG
+
+  private:
+    /** Gets all informations about a file which is being downloaded.
+    */
+    NS_METHOD GetDownloadInfo(nsIHelperAppLauncher *aLauncher, nsISupports *aContext);
+
+    EmbedDownload *mDownload;
 };
 #endif /* __EmbedDownloadMgr_h */
--- a/embedding/browser/gtk/src/EmbedEventListener.cpp
+++ b/embedding/browser/gtk/src/EmbedEventListener.cpp
@@ -42,16 +42,19 @@
 #include "nsCOMPtr.h"
 #include "nsIDOMMouseEvent.h"
 
 #include "nsIDOMNSEvent.h"
 #include "nsIDOMKeyEvent.h"
 #include "nsIDOMUIEvent.h"
 #include "nsIDOMDocument.h"
 #include "nsIDocument.h"
+#include "nsIContent.h"
+#include "nsIPresShell.h"
+#include "nsIDOMNodeList.h"
 
 #include "EmbedEventListener.h"
 #include "EmbedPrivate.h"
 #include "gtkmozembed_internal.h"
 
 static PRInt32 sLongPressTimer = 0, mLongMPressDelay = 1000;
 static PRInt32 sX = 0, sY = 0;
 static PRBool  sMPressed = PR_FALSE, sIsScrolling = PR_FALSE;
@@ -84,145 +87,159 @@ nsresult
 EmbedEventListener::Init(EmbedPrivate *aOwner)
 {
   mOwner = aOwner;
   mCtxInfo = nsnull;
   mClickCount = 1;
 #ifdef MOZ_WIDGET_GTK2
   mCtxInfo = new EmbedContextMenuInfo(aOwner);
 #endif
+  mOwner->mNeedFav = PR_TRUE;
   return NS_OK;
 }
 
 NS_IMETHODIMP
-EmbedEventListener::HandleLink (nsIDOMNode* node)
+EmbedEventListener::HandleLink(nsIDOMNode* node)
 {
-  nsresult result;
+  nsresult rv;
 
   nsCOMPtr<nsIDOMElement> linkElement;
-  linkElement = do_QueryInterface (node);
+  linkElement = do_QueryInterface(node);
   if (!linkElement) return NS_ERROR_FAILURE;
 
   nsString name;
-  result = GetLinkAttribute(linkElement, "rel", &name);
-  if (NS_FAILED(result)) return NS_ERROR_FAILURE;
+  rv = linkElement->GetAttribute(NS_LITERAL_STRING("rel"), name);
+  if (NS_FAILED(rv)) return NS_ERROR_FAILURE;
 
   nsString link;
-  result = GetLinkAttribute(linkElement, "href", &link);
-  if (NS_FAILED(result) || link.IsEmpty()) return NS_ERROR_FAILURE;
+  rv = linkElement->GetAttribute(NS_LITERAL_STRING("href"), link);
+  if (NS_FAILED(rv) || link.IsEmpty()) return NS_ERROR_FAILURE;
 
   nsCOMPtr<nsIDOMDocument> domDoc;
-  result = node->GetOwnerDocument(getter_AddRefs(domDoc));
-  if (NS_FAILED(result) || !domDoc) return NS_ERROR_FAILURE;
+  rv = node->GetOwnerDocument(getter_AddRefs(domDoc));
+  if (NS_FAILED(rv) || !domDoc) return NS_ERROR_FAILURE;
 
   nsCOMPtr<nsIDOM3Node> domnode = do_QueryInterface(domDoc);
-  if(!domnode) return NS_ERROR_FAILURE;
+  if (!domnode) return NS_ERROR_FAILURE;
 
   nsString spec;
   domnode->GetBaseURI(spec);
 
-  nsCString cSpec;
-  NS_UTF16ToCString(spec, NS_CSTRING_ENCODING_UTF8, cSpec);
+  nsCOMPtr<nsIURI> baseURI;
+  rv = NewURI(getter_AddRefs(baseURI), NS_ConvertUTF16toUTF8(spec).get());
+  if (NS_FAILED(rv) || !baseURI) return NS_ERROR_FAILURE;
 
-  nsCOMPtr<nsIURI> baseURI;
-  result = NewURI(getter_AddRefs(baseURI), cSpec.get());
-  if (NS_FAILED(result) || !baseURI) return NS_ERROR_FAILURE;
-
-  nsCString linkstring;
-  NS_UTF16ToCString(link, NS_CSTRING_ENCODING_UTF8, linkstring);
   nsCString url;
-  result = baseURI->Resolve (linkstring, url);
-  if (NS_FAILED(result)) return NS_ERROR_FAILURE;
+  rv = baseURI->Resolve(NS_ConvertUTF16toUTF8(link), url);
+  if (NS_FAILED(rv)) return NS_ERROR_FAILURE;
 
   nsString type;
-  result = GetLinkAttribute(linkElement, "type", &type);
-  if (NS_FAILED(result)) return NS_ERROR_FAILURE;
-
-  nsCString cType;
-  NS_UTF16ToCString(type, NS_CSTRING_ENCODING_UTF8, cType);
+  rv = linkElement->GetAttribute(NS_LITERAL_STRING("type"), type);
+  if (NS_FAILED(rv)) return NS_ERROR_FAILURE;
 
   nsString title;
-  result = GetLinkAttribute(linkElement, "title", &title);
-  if (NS_FAILED(result)) return NS_ERROR_FAILURE;
-
-  nsCString cTitle;
-  NS_UTF16ToCString(title, NS_CSTRING_ENCODING_UTF8, cTitle);
-
-  nsCString cName;
-  NS_UTF16ToCString(name, NS_CSTRING_ENCODING_UTF8, cName);
+  rv = linkElement->GetAttribute(NS_LITERAL_STRING("title"), title);
+  if (NS_FAILED(rv)) return NS_ERROR_FAILURE;
 
   // XXX This does not handle |BLAH ICON POWER"
-  if (!cName.LowerCaseEqualsLiteral("icon")) {
-
+  if (mOwner->mNeedFav && (name.LowerCaseEqualsLiteral("icon") ||
+      name.LowerCaseEqualsLiteral("shortcut icon"))) {
     mOwner->mNeedFav = PR_FALSE;
     this->GetFaviconFromURI(url.get());
   }
-  else {
+  else if (name.LowerCaseEqualsLiteral("alternate") &&
+           type.LowerCaseEqualsLiteral("application/rss+xml")) {
 
-    const gchar *navi_title = cTitle.get();
-    if (*navi_title == '\0')
-      navi_title = NULL;
+    NS_ConvertUTF16toUTF8 narrowTitle(title);
 
-    const gchar *navi_type = cType.get();
-    if (*navi_type == '\0')
-      navi_type = NULL;
-
-    if (!cName.LowerCaseEqualsLiteral("alternate") &&
-        !cType.LowerCaseEqualsLiteral("application/rss+xml")) {
-    }
-    else {
-    }
+    gtk_signal_emit(GTK_OBJECT(mOwner->mOwningWidget),
+                    moz_embed_signals[RSS_REQUEST],
+                    (gchar *)url.get(),
+                    narrowTitle.get());
   }
   return NS_OK;
 }
 
 NS_IMETHODIMP
 EmbedEventListener::HandleEvent(nsIDOMEvent* aDOMEvent)
 {
   nsString eventType;
   aDOMEvent->GetType(eventType);
 #ifdef MOZ_WIDGET_GTK2
-  if (eventType.EqualsLiteral ("focus"))
+  if (eventType.EqualsLiteral("focus"))
     if (mCtxInfo->GetFormControlType(aDOMEvent)) {
       if (mCtxInfo->mEmbedCtxType & GTK_MOZ_EMBED_CTX_INPUT) {
         gint return_val = FALSE;
         gtk_signal_emit(GTK_OBJECT(mOwner->mOwningWidget),
                         moz_embed_signals[DOM_FOCUS],
                         (void *)aDOMEvent, &return_val);
         if (return_val) {
           aDOMEvent->StopPropagation();
           aDOMEvent->PreventDefault();
         }
       }
     }
 #endif
 
-  if (eventType.EqualsLiteral ("DOMLinkAdded") && mOwner->mNeedFav) {
+  if (eventType.EqualsLiteral("DOMLinkAdded")) {
 
-    nsresult result;
+    nsresult rv;
     nsCOMPtr<nsIDOMEventTarget> eventTarget;
 
     aDOMEvent->GetTarget(getter_AddRefs(eventTarget));
-    nsCOMPtr<nsIDOMNode> node = do_QueryInterface(eventTarget, &result);
-    if (NS_FAILED(result) || !node)
+    nsCOMPtr<nsIDOMNode> node = do_QueryInterface(eventTarget, &rv);
+    if (NS_FAILED(rv) || !node)
       return NS_ERROR_FAILURE;
-    HandleLink (node);
+    HandleLink(node);
+  } else if (eventType.EqualsLiteral("load")) {
+
+    nsIWebBrowser *webBrowser = nsnull;
+    gtk_moz_embed_get_nsIWebBrowser(mOwner->mOwningWidget, &webBrowser);
+    if (!webBrowser) return NS_ERROR_FAILURE;
+
+    nsCOMPtr<nsIDOMWindow> DOMWindow;
+    webBrowser->GetContentDOMWindow(getter_AddRefs(DOMWindow));
+    if (!DOMWindow) return NS_ERROR_FAILURE;
+
+    nsCOMPtr<nsIDOMDocument> doc;
+    DOMWindow->GetDocument(getter_AddRefs(doc));
+    if (!doc) return NS_ERROR_FAILURE;
+
+    nsCOMPtr<nsIDOMNodeList> nodelist = nsnull;
+    doc->GetElementsByTagName( NS_LITERAL_STRING( "rss" ), getter_AddRefs( nodelist ));
+    if (nodelist) {
+      PRUint32 length = 0;
+      nodelist->GetLength(&length);
+      if (length >= 1) {
+        char *url = gtk_moz_embed_get_location(mOwner->mOwningWidget);
+        char *title = gtk_moz_embed_get_title(mOwner->mOwningWidget);
+        gtk_signal_emit(GTK_OBJECT(mOwner->mOwningWidget),
+                        moz_embed_signals[RSS_REQUEST],
+                        (gchar*)url,
+                        (gchar*)title);
+        if (url)
+          NS_Free(url);
+        if (title)
+          NS_Free(title);
+      }
+    }
   }
   else if (mOwner->mNeedFav) {
     mOwner->mNeedFav = PR_FALSE;
-    nsCString favicon_url = mOwner->mPrePath + nsCString("/favicon.ico");
+    nsCString favicon_url = mOwner->mPrePath;
+	favicon_url.AppendLiteral("/favicon.ico");
     this->GetFaviconFromURI(favicon_url.get());
   }
   return NS_OK;
 }
 
 NS_IMETHODIMP
 EmbedEventListener::KeyDown(nsIDOMEvent* aDOMEvent)
 {
-  nsCOMPtr <nsIDOMKeyEvent> keyEvent;
+  nsCOMPtr<nsIDOMKeyEvent> keyEvent;
   keyEvent = do_QueryInterface(aDOMEvent);
   if (!keyEvent)
     return NS_OK;
   // Return FALSE to this function to mark the event as not
   // consumed...
   gint return_val = FALSE;
   gtk_signal_emit(GTK_OBJECT(mOwner->mOwningWidget),
                   moz_embed_signals[DOM_KEY_DOWN],
@@ -232,17 +249,17 @@ EmbedEventListener::KeyDown(nsIDOMEvent*
     aDOMEvent->PreventDefault();
   }
   return NS_OK;
 }
 
 NS_IMETHODIMP
 EmbedEventListener::KeyUp(nsIDOMEvent* aDOMEvent)
 {
-  nsCOMPtr <nsIDOMKeyEvent> keyEvent;
+  nsCOMPtr<nsIDOMKeyEvent> keyEvent;
   keyEvent = do_QueryInterface(aDOMEvent);
   if (!keyEvent)
     return NS_OK;
   // return FALSE to this function to mark this event as not
   // consumed...
   gint return_val = FALSE;
   gtk_signal_emit(GTK_OBJECT(mOwner->mOwningWidget),
                   moz_embed_signals[DOM_KEY_UP],
@@ -254,17 +271,17 @@ EmbedEventListener::KeyUp(nsIDOMEvent* a
     //mCtxInfo->UpdateContextData(aDOMEvent);
   }
   return NS_OK;
 }
 
 NS_IMETHODIMP
 EmbedEventListener::KeyPress(nsIDOMEvent* aDOMEvent)
 {
-  nsCOMPtr <nsIDOMKeyEvent> keyEvent;
+  nsCOMPtr<nsIDOMKeyEvent> keyEvent;
   keyEvent = do_QueryInterface(aDOMEvent);
   if (!keyEvent)
     return NS_OK;
   // Return TRUE from your signal handler to mark the event as consumed.
   gint return_val = FALSE;
   gtk_signal_emit(GTK_OBJECT(mOwner->mOwningWidget),
                   moz_embed_signals[DOM_KEY_PRESS],
                   (void *)keyEvent, &return_val);
@@ -290,33 +307,33 @@ sLongMPress(void *aOwningWidget)
     sMPressed = PR_FALSE;
   }
   return FALSE;
 }
 
 NS_IMETHODIMP
 EmbedEventListener::MouseDown(nsIDOMEvent* aDOMEvent)
 {
-  nsCOMPtr <nsIDOMMouseEvent> mouseEvent;
+  nsCOMPtr<nsIDOMMouseEvent> mouseEvent;
   mouseEvent = do_QueryInterface(aDOMEvent);
   if (!mouseEvent)
     return NS_OK;
 
   // Return TRUE from your signal handler to mark the event as consumed.
   sMPressed = PR_TRUE;
   gint return_val = FALSE;
   gtk_signal_emit(GTK_OBJECT(mOwner->mOwningWidget),
                   moz_embed_signals[DOM_MOUSE_DOWN],
                   (void *)mouseEvent, &return_val);
   if (return_val) {
     mClickCount = 2;
     sMPressed = PR_FALSE;
 #if 1
     if (sLongPressTimer)
-      g_source_remove (sLongPressTimer);
+      g_source_remove(sLongPressTimer);
 #else
     aDOMEvent->StopPropagation();
     aDOMEvent->PreventDefault();
 #endif
   } else {
     mClickCount = 1;
     sLongPressTimer = g_timeout_add(mLongMPressDelay, sLongMPress, mOwner->mOwningWidget);
     ((nsIDOMMouseEvent*)mouseEvent)->GetScreenX(&sX);
@@ -329,27 +346,27 @@ EmbedEventListener::MouseDown(nsIDOMEven
 #endif
 
   return NS_OK;
 }
 
 NS_IMETHODIMP
 EmbedEventListener::MouseUp(nsIDOMEvent* aDOMEvent)
 {
-  nsCOMPtr <nsIDOMMouseEvent> mouseEvent;
+  nsCOMPtr<nsIDOMMouseEvent> mouseEvent;
   mouseEvent = do_QueryInterface(aDOMEvent);
   if (!mouseEvent)
     return NS_OK;
 
   // handling event internally, first.
   HandleSelection(mouseEvent);
 
   // Return TRUE from your signal handler to mark the event as consumed.
   if (sLongPressTimer)
-    g_source_remove (sLongPressTimer);
+    g_source_remove(sLongPressTimer);
   sMPressed = PR_FALSE;
   mOwner->mOpenBlock = sIsScrolling;
   sIsScrolling = sMPressed;
   gint return_val = FALSE;
   gtk_signal_emit(GTK_OBJECT(mOwner->mOwningWidget),
                   moz_embed_signals[DOM_MOUSE_UP],
                   (void *)mouseEvent, &return_val);
   if (return_val) {
@@ -357,17 +374,17 @@ EmbedEventListener::MouseUp(nsIDOMEvent*
     aDOMEvent->PreventDefault();
   }
   return NS_OK;
 }
 
 NS_IMETHODIMP
 EmbedEventListener::MouseClick(nsIDOMEvent* aDOMEvent)
 {
-  nsCOMPtr <nsIDOMMouseEvent> mouseEvent;
+  nsCOMPtr<nsIDOMMouseEvent> mouseEvent;
   mouseEvent = do_QueryInterface(aDOMEvent);
   if (!mouseEvent)
     return NS_OK;
   // Return TRUE from your signal handler to mark the event as consumed.
   sMPressed = PR_FALSE;
   gint return_val = FALSE;
   gtk_signal_emit(GTK_OBJECT(mOwner->mOwningWidget),
                   moz_embed_signals[DOM_MOUSE_CLICK],
@@ -377,39 +394,39 @@ EmbedEventListener::MouseClick(nsIDOMEve
     aDOMEvent->PreventDefault();
   }
   return NS_OK;
 }
 
 NS_IMETHODIMP
 EmbedEventListener::MouseDblClick(nsIDOMEvent* aDOMEvent)
 {
-  nsCOMPtr <nsIDOMMouseEvent> mouseEvent;
+  nsCOMPtr<nsIDOMMouseEvent> mouseEvent;
   mouseEvent = do_QueryInterface(aDOMEvent);
   if (!mouseEvent)
     return NS_OK;
   // Return TRUE from your signal handler to mark the event as consumed.
   if (sLongPressTimer)
-    g_source_remove (sLongPressTimer);
+    g_source_remove(sLongPressTimer);
   sMPressed = PR_FALSE;
   gint return_val = FALSE;
   gtk_signal_emit(GTK_OBJECT(mOwner->mOwningWidget),
                   moz_embed_signals[DOM_MOUSE_DBL_CLICK],
                   (void *)mouseEvent, &return_val);
   if (return_val) {
     aDOMEvent->StopPropagation();
     aDOMEvent->PreventDefault();
   }
   return NS_OK;
 }
 
 NS_IMETHODIMP
 EmbedEventListener::MouseOver(nsIDOMEvent* aDOMEvent)
 {
-  nsCOMPtr <nsIDOMMouseEvent> mouseEvent;
+  nsCOMPtr<nsIDOMMouseEvent> mouseEvent;
   mouseEvent = do_QueryInterface(aDOMEvent);
   if (!mouseEvent)
     return NS_OK;
   // Return TRUE from your signal handler to mark the event as consumed.
   gint return_val = FALSE;
   gtk_signal_emit(GTK_OBJECT(mOwner->mOwningWidget),
                   moz_embed_signals[DOM_MOUSE_OVER],
                   (void *)mouseEvent, &return_val);
@@ -420,17 +437,17 @@ EmbedEventListener::MouseOver(nsIDOMEven
     //mCtxInfo->UpdateContextData(aDOMEvent);
   }
   return NS_OK;
 }
 
 NS_IMETHODIMP
 EmbedEventListener::MouseOut(nsIDOMEvent* aDOMEvent)
 {
-  nsCOMPtr <nsIDOMMouseEvent> mouseEvent;
+  nsCOMPtr<nsIDOMMouseEvent> mouseEvent;
   mouseEvent = do_QueryInterface(aDOMEvent);
   if (!mouseEvent)
     return NS_OK;
   // Return TRUE from your signal handler to mark the event as consumed.
   gint return_val = FALSE;
   gtk_signal_emit(GTK_OBJECT(mOwner->mOwningWidget),
                   moz_embed_signals[DOM_MOUSE_OUT],
                   (void *)mouseEvent, &return_val);
@@ -439,17 +456,17 @@ EmbedEventListener::MouseOut(nsIDOMEvent
     aDOMEvent->PreventDefault();
   }
   return NS_OK;
 }
 
 NS_IMETHODIMP
 EmbedEventListener::Activate(nsIDOMEvent* aDOMEvent)
 {
-  nsCOMPtr <nsIDOMUIEvent> uiEvent = do_QueryInterface(aDOMEvent);
+  nsCOMPtr<nsIDOMUIEvent> uiEvent = do_QueryInterface(aDOMEvent);
   if (!uiEvent)
     return NS_OK;
   // Return TRUE from your signal handler to mark the event as consumed.
   gint return_val = FALSE;
   gtk_signal_emit(GTK_OBJECT(mOwner->mOwningWidget),
                   moz_embed_signals[DOM_ACTIVATE],
                   (void *)uiEvent, &return_val);
   if (return_val) {
@@ -457,17 +474,17 @@ EmbedEventListener::Activate(nsIDOMEvent
     aDOMEvent->PreventDefault();
   }
   return NS_OK;
 }
 
 NS_IMETHODIMP
 EmbedEventListener::FocusIn(nsIDOMEvent* aDOMEvent)
 {
-  nsCOMPtr <nsIDOMUIEvent> uiEvent = do_QueryInterface(aDOMEvent);
+  nsCOMPtr<nsIDOMUIEvent> uiEvent = do_QueryInterface(aDOMEvent);
   if (!uiEvent)
     return NS_OK;
   // Return TRUE from your signal handler to mark the event as consumed.
   gint return_val = FALSE;
   gtk_signal_emit(GTK_OBJECT(mOwner->mOwningWidget),
                   moz_embed_signals[DOM_FOCUS_IN],
                   (void *)uiEvent, &return_val);
   if (return_val) {
@@ -475,17 +492,17 @@ EmbedEventListener::FocusIn(nsIDOMEvent*
     aDOMEvent->PreventDefault();
   }
   return NS_OK;
 }
 
 NS_IMETHODIMP
 EmbedEventListener::FocusOut(nsIDOMEvent* aDOMEvent)
 {
-  nsCOMPtr <nsIDOMUIEvent> uiEvent = do_QueryInterface(aDOMEvent);
+  nsCOMPtr<nsIDOMUIEvent> uiEvent = do_QueryInterface(aDOMEvent);
   if (!uiEvent)
     return NS_OK;
   // Return TRUE from your signal handler to mark the event as consumed.
   gint return_val = FALSE;
   gtk_signal_emit(GTK_OBJECT(mOwner->mOwningWidget),
                   moz_embed_signals[DOM_FOCUS_OUT],
                   (void *)uiEvent, &return_val);
   if (return_val) {
@@ -494,23 +511,23 @@ EmbedEventListener::FocusOut(nsIDOMEvent
   }
   return NS_OK;
 }
 
 NS_IMETHODIMP
 EmbedEventListener::MouseMove(nsIDOMEvent* aDOMEvent)
 {
   if (mCurSelCon)
-    mCurSelCon->SetDisplaySelection (nsISelectionController::SELECTION_ON);
+    mCurSelCon->SetDisplaySelection(nsISelectionController::SELECTION_ON);
 
   if (sMPressed &&
       gtk_signal_handler_pending(GTK_OBJECT(mOwner->mOwningWidget),
                                  moz_embed_signals[DOM_MOUSE_SCROLL], TRUE)) {
     // Return TRUE from your signal handler to mark the event as consumed.
-    nsCOMPtr <nsIDOMMouseEvent> mouseEvent = do_QueryInterface(aDOMEvent);
+    nsCOMPtr<nsIDOMMouseEvent> mouseEvent = do_QueryInterface(aDOMEvent);
     if (!mouseEvent)
       return NS_OK;
     PRInt32  newX, newY, subX, subY;
     ((nsIDOMMouseEvent*)mouseEvent)->GetScreenX(&newX);
     ((nsIDOMMouseEvent*)mouseEvent)->GetScreenY(&newY);
     subX = newX - sX;
     subY = newY - sY;
     nsresult rv = NS_OK;
@@ -529,24 +546,24 @@ EmbedEventListener::MouseMove(nsIDOMEven
         } else {
           sMPressed = PR_FALSE;
           sIsScrolling = PR_FALSE;
         }
       }
       if (sIsScrolling)
       {
         if (sLongPressTimer)
-          g_source_remove (sLongPressTimer);
+          g_source_remove(sLongPressTimer);
 #ifdef MOZ_WIDGET_GTK2
         if (mCtxInfo->mNSHHTMLElementSc) {
           PRInt32 x, y;
           mCtxInfo->mNSHHTMLElementSc->GetScrollTop(&y);
           mCtxInfo->mNSHHTMLElementSc->GetScrollLeft(&x);
 #ifdef MOZ_SCROLL_TOP_LEFT_HACK
-          rv = mCtxInfo->mNSHHTMLElementSc->ScrollTopLeft (y - subY, x - subX);
+          rv = mCtxInfo->mNSHHTMLElementSc->ScrollTopLeft(y - subY, x - subX);
 #endif
         } else
 #endif
         {
           rv = NS_ERROR_UNEXPECTED;
         }
         if (rv == NS_ERROR_UNEXPECTED) {
           nsCOMPtr<nsIDOMWindow> DOMWindow;
@@ -568,25 +585,67 @@ NS_IMETHODIMP
 EmbedEventListener::DragMove(nsIDOMEvent* aMouseEvent)
 {
   return NS_OK;
 }
 
 NS_IMETHODIMP
 EmbedEventListener::Focus(nsIDOMEvent* aEvent)
 {
+  nsString eventType;
+  aEvent->GetType(eventType);
+#ifdef MOZ_WIDGET_GTK2
+  if (eventType.EqualsLiteral("focus") &&
+      mCtxInfo->GetFormControlType(aEvent) &&
+      mCtxInfo->mEmbedCtxType & GTK_MOZ_EMBED_CTX_INPUT) {
+    gint return_val = FALSE;
+    gtk_signal_emit(GTK_OBJECT(mOwner->mOwningWidget),
+                    moz_embed_signals[DOM_FOCUS],
+                    (void *)aEvent, &return_val);
+    if (return_val) {
+      aEvent->StopPropagation();
+      aEvent->PreventDefault();
+    }
+  }
+#endif
+
   return NS_OK;
 }
 
+
 NS_IMETHODIMP
 EmbedEventListener::Blur(nsIDOMEvent* aEvent)
 {
+  gint return_val = FALSE;
   mFocusInternalFrame = PR_FALSE;
+
+  nsCOMPtr<nsIDOMNSEvent> nsevent(do_QueryInterface(aEvent));
+  nsCOMPtr<nsIDOMEventTarget> target;
+  nsevent->GetOriginalTarget(getter_AddRefs(target));
+
+  if (!target)
+    return NS_ERROR_FAILURE;
+
+  nsCOMPtr<nsIContent> targetContent = do_QueryInterface(target);
+
+  if (targetContent) {
+#ifdef MOZILLA_1_8_BRANCH
+    if (targetContent->IsContentOfType(nsIContent::eHTML_FORM_CONTROL)) {
+#else
+    if (targetContent->IsNodeOfType(nsIContent::eHTML_FORM_CONTROL)) {
+#endif
+      if (sLongPressTimer)
+        g_source_remove(sLongPressTimer);
+
+      sMPressed = sIsScrolling ? PR_FALSE : sMPressed;
+      sIsScrolling = PR_FALSE;
+    }
+  }
   return NS_OK;
- }
+}
 
 NS_IMETHODIMP
 EmbedEventListener::HandleSelection(nsIDOMMouseEvent* aDOMMouseEvent)
 {
   nsresult rv;
 #ifdef MOZ_WIDGET_GTK2
   /* This function gets called everytime that a mousedown or a mouseup
    * event occurs.
@@ -622,112 +681,100 @@ EmbedEventListener::HandleSelection(nsID
     return rv;
 
   /* Updates context to check which context is being clicked on */
   mCtxInfo->UpdateContextData(aDOMMouseEvent);
 
   /* If a mousedown after 1 click is done (and if clicked context is not a XUL
    * one (e.g. scrollbar), the selection is disabled for that context.
    */
-  if (!(mCtxInfo->mEmbedCtxType & GTK_MOZ_EMBED_CTX_XUL)) {
+  if (mCtxInfo->mEmbedCtxType & GTK_MOZ_EMBED_CTX_XUL || mCtxInfo->mEmbedCtxType & GTK_MOZ_EMBED_CTX_RICHEDIT)
+    return rv;
 
-    if (eventType.EqualsLiteral("mousedown")) {
+  if (eventType.EqualsLiteral("mousedown")) {
 
-      if (mClickCount == 1)
-        rv = mCurSelCon->SetDisplaySelection(nsISelectionController::SELECTION_OFF);
+    if (mClickCount == 1)
+      rv = mCurSelCon->SetDisplaySelection(nsISelectionController::SELECTION_OFF);
 
-    } // mousedown
+  } // mousedown
 
-    /* If a mouseup occurs, the selection for context is enabled again (despite of
-     * number of clicks). If this event occurs after 1 click, the selection of
-     * both last and current context is cleaned up.
-     */
-    if (eventType.EqualsLiteral("mouseup")) {
+  /* If a mouseup occurs, the selection for context is enabled again (despite of
+   * number of clicks). If this event occurs after 1 click, the selection of
+   * both last and current contexts are cleaned up.
+   */
+  if (eventType.EqualsLiteral("mouseup")) {
 
-      /* Selection controller of current event context */
-      if (mCurSelCon) {
-        rv = mCurSelCon->SetDisplaySelection(nsISelectionController::SELECTION_ON);
-        if (mClickCount == 1) {
-          nsCOMPtr<nsISelection> domSel;
-          mCurSelCon->GetSelection(nsISelectionController::SELECTION_NORMAL,
-                                   getter_AddRefs(domSel));
-          rv = domSel->RemoveAllRanges();
-        }
+    /* Selection controller of current event context */
+    if (mCurSelCon) {
+      rv = mCurSelCon->SetDisplaySelection(nsISelectionController::SELECTION_ON);
+      if (mClickCount == 1) {
+        nsCOMPtr<nsISelection> domSel;
+        mCurSelCon->GetSelection(nsISelectionController::SELECTION_NORMAL,
+                                 getter_AddRefs(domSel));
+        rv = domSel->RemoveAllRanges();
       }
-      /* Selection controller of previous event context */
-      if (mLastSelCon) {
-        rv = mLastSelCon->SetDisplaySelection(nsISelectionController::SELECTION_ON);
-        if (mClickCount == 1) {
-          nsCOMPtr<nsISelection> domSel;
-          mLastSelCon->GetSelection(nsISelectionController::SELECTION_NORMAL,
-                                    getter_AddRefs(domSel));
-          rv = domSel->RemoveAllRanges();
-        }
+    }
+    /* Selection controller of previous event context */
+    if (mLastSelCon) {
+      rv = mLastSelCon->SetDisplaySelection(nsISelectionController::SELECTION_ON);
+      if (mClickCount == 1) {
+        nsCOMPtr<nsISelection> domSel;
+        mLastSelCon->GetSelection(nsISelectionController::SELECTION_NORMAL,
+                                  getter_AddRefs(domSel));
+        rv = domSel->RemoveAllRanges();
       }
+    }
 
-      /* If 1 click was done (despite the event type), sets the last context's
-       * selection controller with current one
-       */
-      if (mClickCount == 1)
-        mLastSelCon = mCurSelCon;
-    } // mouseup
-  }
+    /* If 1 click was done (despite the event type), sets the last context's
+     * selection controller with current one
+     */
+    if (mClickCount == 1)
+      mLastSelCon = mCurSelCon;
+  } // mouseup
 #endif
   return rv;
 }
 
 nsresult
-EmbedEventListener::GetLinkAttribute (nsCOMPtr<nsIDOMElement>& linkElement,
-                                      const char *name,
-                                      nsString *value)
-{
-  nsString n_name;
-  nsCString c_name(name);
-  NS_CStringToUTF16(c_name, NS_CSTRING_ENCODING_UTF8, n_name);
-
-  return linkElement->GetAttribute(n_name, *value);
-}
-
-nsresult
-EmbedEventListener::NewURI (nsIURI **result,
+EmbedEventListener::NewURI(nsIURI **result,
                             const char *spec)
 {
   nsresult rv;
   nsCString cSpec(spec);
   nsCOMPtr<nsIIOService> ioService;
-  rv = GetIOService (getter_AddRefs (ioService));
+  rv = GetIOService(getter_AddRefs(ioService));
   if (NS_FAILED(rv))
     return rv;
 
-  rv = ioService->NewURI (cSpec, nsnull, nsnull, result);
+  rv = ioService->NewURI(cSpec, nsnull, nsnull, result);
   return rv;
 }
 
 nsresult
 EmbedEventListener::GetIOService(nsIIOService **ioService)
 {
   nsresult rv;
 
   nsCOMPtr<nsIServiceManager> mgr;
-  NS_GetServiceManager (getter_AddRefs (mgr));
+  NS_GetServiceManager(getter_AddRefs(mgr));
   if (!mgr) return NS_ERROR_FAILURE;
 
-  rv = mgr->GetServiceByContractID ("@mozilla.org/network/io-service;1",
-                                    NS_GET_IID (nsIIOService),
-                                    (void **)ioService);
+  rv = mgr->GetServiceByContractID("@mozilla.org/network/io-service;1",
+                                   NS_GET_IID(nsIIOService),
+                                   (void **)ioService);
   return rv;
 }
 
 #ifdef MOZ_WIDGET_GTK2
 void
 EmbedEventListener::GeneratePixBuf()
 {
   GdkPixbuf *pixbuf = NULL;
   pixbuf = gdk_pixbuf_new_from_file(::gFavLocation, NULL);
-  if(!pixbuf) {
+  if (!pixbuf) {
     gtk_signal_emit(GTK_OBJECT(mOwner->mOwningWidget),
                     moz_embed_signals[ICON_CHANGED],
                     NULL );
 
     // remove the wrong favicon
     // FIXME: need better impl...
     nsCOMPtr<nsILocalFile> faviconFile = do_CreateInstance(NS_LOCAL_FILE_CONTRACTID);
 
@@ -740,17 +787,16 @@ EmbedEventListener::GeneratePixBuf()
     nsCString faviconLocation(::gFavLocation);
     faviconFile->InitWithNativePath(faviconLocation);
     faviconFile->Remove(FALSE);
     NS_Free(::gFavLocation);
     gFavLocation = nsnull;
     return;
   }
 
-  // now send the signal to eal then eal send another signal to UI
   gtk_signal_emit(GTK_OBJECT(mOwner->mOwningWidget),
                   moz_embed_signals[ICON_CHANGED],
                   pixbuf );
   //mOwner->mNeedFav = PR_FALSE;
   NS_Free(::gFavLocation);
   gFavLocation = nsnull;
 }
 #endif
@@ -810,17 +856,17 @@ EmbedEventListener::GetFaviconFromURI(co
     return;
   }
   target_file->InitWithNativePath(favicon_path);
   target_file->Append(NS_ConvertUTF8toUTF16(fileName));
 
   nsString path;
   target_file->GetPath(path);
   ::gFavLocation = NS_strdup(NS_ConvertUTF16toUTF8(path).get());
-  nsCOMPtr<nsIIOService> ios (do_GetService(NS_IOSERVICE_CONTRACTID));
+  nsCOMPtr<nsIIOService> ios(do_GetService(NS_IOSERVICE_CONTRACTID));
   if (!ios) {
     NS_Free(file_name);
     NS_Free(favicon_uri);
     NS_Free(::gFavLocation);
     gFavLocation = nsnull;
     return;
   }
 
@@ -856,29 +902,23 @@ EmbedEventListener::GetFaviconFromURI(co
 NS_IMETHODIMP
 EmbedEventListener::OnStateChange(nsIWebProgress *aWebProgress,
                                   nsIRequest *aRequest,
                                   PRUint32 aStateFlags,
                                   nsresult aStatus)
 {
   /* if (!(aStateFlags & (STATE_STOP | STATE_IS_NETWORK | STATE_IS_DOCUMENT))){*/
 #ifdef MOZ_WIDGET_GTK2
-  if(aStateFlags & STATE_STOP)
-  {
+  if (aStateFlags & STATE_STOP)
     /* FINISH DOWNLOADING */
-    if (NS_SUCCEEDED(aStatus)) {
+    /* XXX sometimes this==0x0 and it cause crash in GeneratePixBuf, need workaround check for this */
+    if (NS_SUCCEEDED(aStatus) && this)
       GeneratePixBuf();
-      return NS_OK;
-    }
-  }
-  else {
-  }
 #endif
   return NS_OK;
-
 }
 
 NS_IMETHODIMP
 EmbedEventListener::OnProgressChange(nsIWebProgress *aWebProgress,
                                      nsIRequest *aRequest,
                                      PRInt32 aCurSelfProgress,
                                      PRInt32 aMaxSelfProgress,
                                      PRInt32 aCurTotalProgress,
--- a/embedding/browser/gtk/src/EmbedEventListener.h
+++ b/embedding/browser/gtk/src/EmbedEventListener.h
@@ -90,17 +90,17 @@ class EmbedEventListener : public nsIDOM
   nsresult Init(EmbedPrivate *aOwner);
 
   NS_DECL_ISUPPORTS
 
 //  NS_DECL_NSIDOMEVENTLISTENER
   // nsIDOMEventListener
   NS_DECL_NSIWEBPROGRESSLISTENER
   NS_IMETHOD HandleEvent(nsIDOMEvent* aEvent);
-  NS_IMETHOD HandleLink (nsIDOMNode* node);
+  NS_IMETHOD HandleLink(nsIDOMNode* node);
   // nsIDOMKeyListener
 
   NS_IMETHOD KeyDown(nsIDOMEvent* aDOMEvent);
   NS_IMETHOD KeyUp(nsIDOMEvent* aDOMEvent);
   NS_IMETHOD KeyPress(nsIDOMEvent* aDOMEvent);
 
   // nsIDOMMouseListener
 
@@ -122,32 +122,28 @@ class EmbedEventListener : public nsIDOM
   NS_IMETHOD DragMove(nsIDOMEvent* aMouseEvent);
   EmbedContextMenuInfo* GetContextInfo() { return mCtxInfo; };
 
   // nsIDOMFocusListener
   NS_IMETHOD Focus(nsIDOMEvent* aEvent);
   NS_IMETHOD Blur(nsIDOMEvent* aEvent);
   NS_IMETHOD HandleSelection(nsIDOMMouseEvent* aDOMMouseEvent);
 
-  // FIXME: dont not use nsCOMPtr<...> as param !! and how to ?
-  nsresult   GetLinkAttribute  (nsCOMPtr <nsIDOMElement>& linkElement,
-                                const char *name,
-                                nsString *value);
   nsresult   NewURI            (nsIURI **result,
                                 const char *spec);
   nsresult   GetIOService      (nsIIOService **ioService);
 
   void       GeneratePixBuf    ();
 
   void       GetFaviconFromURI (const char*  aURI);
  private:
 
   EmbedPrivate *mOwner;
   EmbedContextMenuInfo *mCtxInfo;
 
   // Selection and some clipboard stuff
-  nsCOMPtr <nsISelectionController> mCurSelCon;
-  nsCOMPtr <nsISelectionController> mLastSelCon;
+  nsCOMPtr<nsISelectionController> mCurSelCon;
+  nsCOMPtr<nsISelectionController> mLastSelCon;
   PRBool mFocusInternalFrame;
   PRInt32 mClickCount;
 };
 
 #endif /* __EmbedEventListener_h */
--- a/embedding/browser/gtk/src/EmbedFilePicker.cpp
+++ b/embedding/browser/gtk/src/EmbedFilePicker.cpp
@@ -17,66 +17,55 @@
  * The Original Code is mozilla.org code.
  *
  * The Initial Developer of the Original Code is
  * timeless <timeless@mozdev.org>.
  * Portions created by the Initial Developer are Copyright (C) 2006
  * the Initial Developer. All Rights Reserved.
  *
  * Contributor(s):
+ *   Antonio Gomes <tonikitoo@gmail.com>
+ *   Oleg Romashin <romaxa@gmail.com>
  *
  * Alternatively, the contents of this file may be used under the terms of
  * either the GNU General Public License Version 2 or later (the "GPL"), or
  * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
  * in which case the provisions of the GPL or the LGPL are applicable instead
  * of those above. If you wish to allow use of your version of this file only
  * under the terms of either the GPL or the LGPL, and not to allow others to
  * use your version of this file under the terms of the MPL, indicate your
  * decision by deleting the provisions above and replace them with the notice
  * and other provisions required by the GPL or the LGPL. If you do not delete
  * the provisions above, a recipient may use your version of this file under
  * the terms of any one of the MPL, the GPL or the LGPL.
  *
  * ***** END LICENSE BLOCK ***** */
 
-#ifdef HAVE_CONFIG_H
-#include "config.h"
-#endif
-// local includes
 #include "EmbedFilePicker.h"
 #include "EmbedGtkTools.h"
-#include "gtkmozembed.h"
-#include "nsCOMPtr.h"
-#include "nsIServiceManager.h"
-#include "nsIURI.h"
 #include "nsIFileURL.h"
 #include "nsILocalFile.h"
 #include "nsIDOMWindow.h"
-#include "nsNetCID.h"
-#include "nsIDOMWindowInternal.h"
-#ifndef MOZILLA_INTERNAL_API
-#include "nsComponentManagerUtils.h"
-#include "nsServiceManagerUtils.h"
-#endif
+#include "nsStringGlue.h"
+#include "nsNetUtil.h"
+#include "prenv.h"
+
 #ifdef MOZ_LOGGING
 #include <stdlib.h>
 #endif
 
 NS_IMPL_ISUPPORTS1(EmbedFilePicker, nsIFilePicker)
-EmbedFilePicker::EmbedFilePicker()
-: mParent (nsnull),
-  mMode(nsIFilePicker::modeOpen),
-  mFilename (nsnull)
+
+EmbedFilePicker::EmbedFilePicker(): mParent (nsnull),
+                                    mMode(nsIFilePicker::modeOpen)
 {
 }
 
 EmbedFilePicker::~EmbedFilePicker()
 {
-  if (mFilename)
-    g_free (mFilename);
 }
 
 /* void init (in nsIDOMWindowInternal parent, in wstring title, in short mode); */
 NS_IMETHODIMP EmbedFilePicker::Init(nsIDOMWindow *parent, const nsAString &title, PRInt16 mode)
 {
   mParent = parent;
   mMode = mode;
   return NS_OK;
@@ -136,85 +125,88 @@ NS_IMETHODIMP EmbedFilePicker::GetDispla
 NS_IMETHODIMP EmbedFilePicker::SetDisplayDirectory(nsILocalFile *aDisplayDirectory)
 {
   return NS_ERROR_NOT_IMPLEMENTED;
 }
 
 /* readonly attribute nsILocalFile file; */
 NS_IMETHODIMP EmbedFilePicker::GetFile(nsILocalFile **aFile)
 {
-  if (!mFilename) return NS_OK;
-  /* NOTE: we have to take out any prefix (file:// or obex://)
-   * from file name to make it work in mozilla.
-   */
-  gchar *strippedFileName = nsnull;
-  if (!strncmp (mFilename, GTK_MOZ_EMBED_COMMON_FILE_SCHEME, 7))
-    strippedFileName = (g_strsplit(mFilename, GTK_MOZ_EMBED_COMMON_FILE_SCHEME, -1))[1];
-  else if (!strncmp (mFilename, GTK_MOZ_EMBED_BLUETOOTH_FILE_SCHEME, 7))
-    strippedFileName = (g_strsplit(mFilename, GTK_MOZ_EMBED_BLUETOOTH_FILE_SCHEME, -1))[1];
-  else {
-    if (!mParent) return NS_OK;
-    GtkWidget* parentWidget = GetGtkWidgetForDOMWindow (mParent);
-    if (!parentWidget) return NS_OK;
-    g_signal_emit_by_name(GTK_OBJECT (parentWidget), "alert", "File protocol not supported." ,NULL);
-    // FIXME: clean/free parentWidget
+
+  NS_ENSURE_ARG_POINTER(aFile);
+
+  if (mFilename.IsEmpty())
+    return NS_OK;
+
+  nsCOMPtr<nsIURI> baseURI;
+  nsresult rv = NS_NewURI(getter_AddRefs(baseURI), mFilename);
+
+  nsCOMPtr<nsIFileURL> fileURL(do_QueryInterface(baseURI, &rv));
+  NS_ENSURE_SUCCESS(rv, rv);
+
+  nsCOMPtr<nsIFile> file;
+  rv = fileURL->GetFile(getter_AddRefs(file));
+
+  nsCOMPtr<nsILocalFile> localfile;
+  localfile = do_QueryInterface(file, &rv);
+
+  if (NS_SUCCEEDED(rv)) {
+    NS_ADDREF(*aFile = localfile);
     return NS_OK;
   }
-  if (strippedFileName)
-  {
-    nsCAutoString localSavePath (strippedFileName);
-    nsCOMPtr<nsILocalFile> file = do_CreateInstance (NS_LOCAL_FILE_CONTRACTID);
-    if (!file) return NS_OK;
-    file->InitWithNativePath (localSavePath);
-    NS_ADDREF (*aFile = file);
-    g_free (strippedFileName);
-    strippedFileName = nsnull;
-  }
+
+  NS_ENSURE_TRUE(mParent, NS_OK);
+  GtkWidget* parentWidget = GetGtkWidgetForDOMWindow(mParent);
+  NS_ENSURE_TRUE(parentWidget, NS_OK);
+  /* XXX this message isn't really sure what it's trying to say */
+  g_signal_emit_by_name(GTK_OBJECT(parentWidget), "alert", "File protocol not supported.", NULL);
   return NS_OK;
 }
 
 /* readonly attribute nsIFileURL fileURL; */
 NS_IMETHODIMP EmbedFilePicker::GetFileURL(nsIFileURL **aFileURL)
 {
+  NS_ENSURE_ARG_POINTER(aFileURL);
+  *aFileURL = nsnull;
+
   nsCOMPtr<nsILocalFile> file;
-  GetFile (getter_AddRefs(file));
-  if (!file) return NS_OK;
-  NS_ENSURE_TRUE (file, NS_ERROR_FAILURE);
-  nsCOMPtr<nsIFileURL> fileURL = do_CreateInstance (NS_STANDARDURL_CONTRACTID);
-  if (!fileURL) return NS_OK;
+  GetFile(getter_AddRefs(file));
+  NS_ENSURE_TRUE(file, NS_ERROR_FAILURE);
+  nsCOMPtr<nsIFileURL> fileURL = do_CreateInstance(NS_STANDARDURL_CONTRACTID);
+  NS_ENSURE_TRUE(fileURL, NS_ERROR_OUT_OF_MEMORY);
   fileURL->SetFile(file);
   NS_ADDREF(*aFileURL = fileURL);
   return NS_OK;
 }
 
 /* readonly attribute nsISimpleEnumerator files; */
 NS_IMETHODIMP EmbedFilePicker::GetFiles(nsISimpleEnumerator * *aFiles)
 {
   return NS_ERROR_NOT_IMPLEMENTED;
 }
 
 /* short show (); */
 NS_IMETHODIMP EmbedFilePicker::Show(PRInt16 *_retval)
 {
-  if (!mParent)
-    return NS_OK;
-  GtkWidget* parentWidget = GetGtkWidgetForDOMWindow (mParent);
-  if (!parentWidget)
-    return NS_OK;
-  if (mFilename) {
-    g_free (mFilename);
-    mFilename = nsnull;
-  }
-  int response;
-  g_signal_emit_by_name (
-    GTK_OBJECT (parentWidget),
-    "upload_dialog",
-    "/home/user", // XXX please use genenv("HOME") instead of this.
-    "",
-    &mFilename,
-    &response,
-    NULL);
-  if (response == 1 && mFilename != NULL)
-    *_retval = nsIFilePicker::returnOK;
-  else
-    *_retval = nsIFilePicker::returnCancel;
+  NS_ENSURE_ARG_POINTER(_retval);
+  NS_ENSURE_TRUE(mParent, NS_OK);
+
+  GtkWidget *parentWidget = GetGtkWidgetForDOMWindow(mParent);
+  NS_ENSURE_TRUE(parentWidget, NS_OK);
+
+  gboolean response = 0;
+  char *retname = nsnull;
+  g_signal_emit_by_name(GTK_OBJECT(parentWidget),
+                        "upload_dialog",
+                        PR_GetEnv("HOME"),
+                        "",
+                        &retname,
+                        &response,
+                        NULL);
+
+  *_retval = response ? nsIFilePicker::returnOK : nsIFilePicker::returnCancel;
+
+  mFilename = retname;
+  if (retname)
+    NS_Free(retname);
+
   return NS_OK;
 }
--- a/embedding/browser/gtk/src/EmbedFilePicker.h
+++ b/embedding/browser/gtk/src/EmbedFilePicker.h
@@ -37,16 +37,21 @@
  *
  * ***** END LICENSE BLOCK ***** */
 
 #ifndef __EmbedFilePicker_h
 #define __EmbedFilePicker_h
 
 #include "nsIFilePicker.h"
 #include "nsISupports.h"
+#include "nsNetCID.h"
+
+#include "gtkmozembed.h"
+#include "gtkmozembed_common.h"
+#include "EmbedPrivate.h"
 
 #define EMBED_FILEPICKER_CID           \
 { /* f097d33b-1c97-48a6-af4c-07022857eb7c */         \
     0xf097d33b,                                      \
     0x1c97,                                          \
     0x48a6,                                          \
     {0xaf, 0x4c, 0x07, 0x02, 0x28, 0x57, 0xeb, 0x7c} \
 }
@@ -54,16 +59,19 @@
 #define EMBED_FILEPICKER_CONTRACTID  "@mozilla.org/filepicker;1"
 #define EMBED_FILEPICKER_CLASSNAME  "File Picker Implementation"
 
 class EmbedFilePicker : public nsIFilePicker
 {
 public:
   NS_DECL_ISUPPORTS
   NS_DECL_NSIFILEPICKER
-  EmbedFilePicker ();
-  virtual ~EmbedFilePicker();
-private:
+  EmbedFilePicker();
+
+protected:
   nsIDOMWindow *mParent;
   PRInt16 mMode;
-  char *mFilename;
+  nsCString mFilename;
+
+private:
+  ~EmbedFilePicker();
 };
 #endif
--- a/embedding/browser/gtk/src/EmbedGlobalHistory.cpp
+++ b/embedding/browser/gtk/src/EmbedGlobalHistory.cpp
@@ -17,16 +17,17 @@
  *
  * The Initial Developer of the Original Code is
  * Netscape Communications Corporation.
  * Portions created by the Initial Developer are Copyright (C) 1998
  * the Initial Developer. All Rights Reserved.
  *
  * Contributor(s):
  *   Conrad Carlen <ccarlen@netscape.com>
+ *   Oleg Romashin <romaxa@gmail.com>
  *   (from original mozilla/embedding/lite/nsEmbedGlobalHistory.cpp)
  *
  * 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
@@ -67,203 +68,107 @@ static const PRInt64 kOneThousand = LL_I
 // The history list and the entries counter
 static GList *mURLList;                 /** < The history list */
 static PRInt64 mExpirationInterval;     /** < Expiration interval time */
 static EmbedGlobalHistory *sEmbedGlobalHistory = nsnull;
 
 //*****************************************************************************
 // HistoryEntryOld: an entry object and its methods
 //*****************************************************************************
-typedef struct _HistoryEntry {
+class HistoryEntry
+{
+public:
   PRInt64         mLastVisitTime;     // Millisecs
   PRPackedBool    mWritten;           // TRUE if ever persisted
   nsCString       mTitle;             // The entry title
-  char            *url;               // The url itself
-} HistoryEntry;
+  nsCString       mUrl;               // The url itself
+};
 
-#ifdef MOZ_ENABLE_GNOMEVFS
 #define CLOSE_FILE_HANDLE(file_handle) \
   PR_BEGIN_MACRO \
-    if (file_handle) {\
-      gnome_vfs_close(file_handle); \
-    } \
-  PR_END_MACRO
-#else
-#define CLOSE_FILE_HANDLE(file_handle) \
-  PR_BEGIN_MACRO \
-    if (file_handle) {\
+    if (file_handle) { \
       close_output_stream(file_handle); \
       NS_RELEASE(file_handle); \
     } \
   PR_END_MACRO
 
 static void close_output_stream(OUTPUT_STREAM *file_handle)
 {
   file_handle->Close();
   return;
 }
-#endif
 
 static bool file_handle_uri_exists(LOCAL_FILE *uri)
 {
   g_return_val_if_fail(uri, false);
-#ifndef MOZ_ENABLE_GNOMEVFS
   PRBool exists = PR_FALSE;
   uri->Exists(&exists);
-  return !!exists;
-#else
-  return gnome_vfs_uri_exists(uri);
-#endif
+  return exists;
 }
 
 static LOCAL_FILE* file_handle_uri_new(const char *uri)
 {
   g_return_val_if_fail(uri, nsnull);
-#ifndef MOZ_ENABLE_GNOMEVFS
   nsresult rv;
   LOCAL_FILE *historyFile = nsnull;
   rv = NS_NewNativeLocalFile(nsDependentCString(uri), 1, &historyFile);
   return historyFile;
-#else
-  return gnome_vfs_uri_new(uri);
-#endif
 }
 
 static void file_handle_uri_release(LOCAL_FILE *uri)
 {
   g_return_if_fail(uri);
-#ifndef MOZ_ENABLE_GNOMEVFS
   NS_RELEASE(uri);
-#else
-  gnome_vfs_uri_unref(uri);
-#endif
 }
 
 
 static bool file_handle_create_uri(OUTPUT_STREAM **file_handle, LOCAL_FILE *uri)
 {
   g_return_val_if_fail(file_handle, false);
-#ifndef MOZ_ENABLE_GNOMEVFS
   nsresult rv;
   rv = NS_NewLocalFileOutputStream(file_handle, uri, PR_RDWR | PR_APPEND | PR_CREATE_FILE, 0660);
 
   return NS_SUCCEEDED(rv);
-#else
-  return gnome_vfs_create_uri(
-    file_handle,
-    uri,
-    GNOME_VFS_OPEN_WRITE,
-    1,
-    0600
-  ) == GNOME_VFS_OK;
-#endif
 }
 
 static bool file_handle_open_uri(OUTPUT_STREAM **file_handle, LOCAL_FILE *uri)
 {
   g_return_val_if_fail(file_handle, false);
-#ifndef MOZ_ENABLE_GNOMEVFS
   nsresult rv;
-  rv = NS_NewLocalFileOutputStream(file_handle, uri, PR_RDWR | PR_APPEND, 0660);
+  rv = NS_NewLocalFileOutputStream(file_handle, uri, PR_RDWR, 0660);
 
   return NS_SUCCEEDED(rv);
-#else
-  return gnome_vfs_open_uri(
-    file_handle,
-    uri,
-    (GnomeVFSOpenMode)(GNOME_VFS_OPEN_WRITE
-                      | GNOME_VFS_OPEN_RANDOM
-                      | GNOME_VFS_OPEN_READ)) == GNOME_VFS_OK;
-#endif
 }
 
 static bool file_handle_seek(OUTPUT_STREAM *file_handle, gboolean end)
 {
   g_return_val_if_fail(file_handle, false);
-#ifndef MOZ_ENABLE_GNOMEVFS
   nsresult rv;
   nsCOMPtr<nsISeekableStream> seekable = do_QueryInterface(file_handle, &rv);
   rv = seekable->Seek(nsISeekableStream::NS_SEEK_SET, end ? -1 : 0);
   return NS_SUCCEEDED(rv);
-#else
-  return gnome_vfs_seek(file_handle,
-                        end ? GNOME_VFS_SEEK_END : GNOME_VFS_SEEK_START, 0) == GNOME_VFS_OK;
-#endif
 }
 
 static bool file_handle_truncate(OUTPUT_STREAM *file_handle)
 {
   g_return_val_if_fail(file_handle, false);
-#ifndef MOZ_ENABLE_GNOMEVFS
-  return true;
-#else
-  return gnome_vfs_truncate_handle (file_handle, 0) == GNOME_VFS_OK;
-#endif
-}
-
-static int file_handle_file_info_block_size(OUTPUT_STREAM *file_handle,  guint64 *size)
-{
-  g_return_val_if_fail(file_handle, 0);
-  int rtn = 0;
-#ifndef MOZ_ENABLE_GNOMEVFS
-  *size = 512;
-  return rtn;
-#else
-  GnomeVFSFileInfo * fi = gnome_vfs_file_info_new ();
-
-  if (gnome_vfs_get_file_info_from_handle (file_handle, fi,
-                                           GNOME_VFS_FILE_INFO_DEFAULT) == GNOME_VFS_OK)
-    *size = (int)fi->io_block_size;
-  else
-    rtn = -1;
-
-  gnome_vfs_file_info_unref (fi);
-#endif
-  return rtn;
-}
-
-static int64 file_handle_read(OUTPUT_STREAM *file_handle, gpointer buffer, guint64 bytes)
-{
-  g_return_val_if_fail(file_handle, -1);
-#ifndef MOZ_ENABLE_GNOMEVFS
-  PRUint32 amt = 0;
   nsresult rv;
-  nsCOMPtr<nsIInputStream> seekable = do_QueryInterface(file_handle, &rv);
-  if (NS_FAILED(rv))
-    return -1;
-  rv = seekable->Read(*(char**)buffer, bytes, &amt);
-  return NS_FAILED(rv) ? -1 : amt;
-#else
-  GnomeVFSResult vfs_result = GNOME_VFS_OK;
-  GnomeVFSFileSize read_bytes;
-  vfs_result = gnome_vfs_read(file_handle,
-  (gpointer) buffer, (GnomeVFSFileSize)bytes-1, &read_bytes);
-  if (vfs_result!=GNOME_VFS_OK)
-    return -1;
-
-  return (int64)read_bytes;
-#endif
+  nsCOMPtr<nsISeekableStream> seekable = do_QueryInterface(file_handle, &rv);
+  rv = seekable->SetEOF();
+  return NS_SUCCEEDED(rv);
 }
 
 static guint64 file_handle_write(OUTPUT_STREAM *file_handle, gpointer line)
 {
   g_return_val_if_fail(file_handle, 0);
-#ifndef MOZ_ENABLE_GNOMEVFS
   PRUint32 amt = 0;
   nsresult rv;
   rv = file_handle->Write((char*)line, strlen((char*)line), &amt);
+  /* XXX booleans are not equivalent to guint64 */
   return NS_SUCCEEDED(rv);
-#else
-  GnomeVFSFileSize written;
-  gnome_vfs_write (file_handle,
-                   (gpointer)line,
-                   strlen((const char*)line),
-                   &written);
-  return written;
-#endif
 }
 
 // Static Routine Prototypes
 //GnomeVFSHandle
 static nsresult writeEntry(OUTPUT_STREAM *file_handle, HistoryEntry *entry);
 // when an entry is visited
 nsresult OnVisited(HistoryEntry *entry)
 {
@@ -300,79 +205,70 @@ PRBool GetIsWritten(HistoryEntry *entry)
 nsresult SetIsWritten(HistoryEntry *entry)
 {
   NS_ENSURE_ARG(entry);
   entry->mWritten = PR_TRUE;
   return NS_OK;
 }
 
 // Change the entry title
-#define SET_TITLE(entry, aTitle) entry->mTitle.Assign (aTitle);
+#define SET_TITLE(entry, aTitle) (entry->mTitle.Assign(aTitle))
+
+// Return the entry title
+#define GET_TITLE(entry) (entry && !entry->mTitle.IsEmpty() ? entry->mTitle.get() : "")
 
 // Change the entry title
-nsresult SetURL(HistoryEntry *entry, const char *url)
+nsresult SET_URL(HistoryEntry *aEntry, const char *aUrl)
 {
-  NS_ENSURE_ARG(entry);
-  NS_ENSURE_ARG(url);
-  if (entry->url)
-    g_free(entry->url);
-  entry->url = g_strdup(url);
+  NS_ENSURE_ARG(aEntry);
+  NS_ENSURE_ARG(aUrl);
+  aEntry->mUrl.Assign(aUrl);
   return NS_OK;
 }
 
-// Return the entry title
-#define GET_TITLE(entry) (entry->mTitle)
-
 // Return the entry url
-char* GetURL(HistoryEntry *entry)
+const char* GET_URL(HistoryEntry *aEntry)
 {
-  return entry->url;
+  return (aEntry && !aEntry->mUrl.IsEmpty()) ? aEntry->mUrl.get() : "";
 }
 
 // Traverse the history list trying to find a frame
-int history_entry_find_exist (gconstpointer a, gconstpointer b)
+int history_entry_find_exist(gconstpointer a, gconstpointer b)
 {
-  return g_ascii_strcasecmp(GetURL((HistoryEntry *) a), (char *) b);
+  return g_ascii_strcasecmp((char*)GET_URL((HistoryEntry *)a), (char *) b);
 }
 
 // Traverse the history list looking for the correct place to add a new item
-int find_insertion_place (gconstpointer a, gconstpointer b)
+int find_insertion_place(gconstpointer a, gconstpointer b)
 {
   PRInt64 lastVisitTime = GetLastVisitTime((HistoryEntry *) a);
   PRInt64 tempTime = GetLastVisitTime((HistoryEntry *) b);
   return LL_CMP(lastVisitTime, <, tempTime);
 }
 
 // Check whether an entry has expired
 PRBool entryHasExpired(HistoryEntry *entry)
 {
   // convert "now" from microsecs to millisecs
   PRInt64 nowInMilliSecs = PR_Now();
   LL_DIV(nowInMilliSecs, nowInMilliSecs, kOneThousand);
   // determine when the entry would have expired
   PRInt64 expirationIntervalAgo;
   LL_SUB(expirationIntervalAgo, nowInMilliSecs, mExpirationInterval);
   PRInt64 lastVisitTime = GetLastVisitTime(entry);
-  return (LL_CMP(lastVisitTime, <, expirationIntervalAgo));
+  return LL_CMP(lastVisitTime, <, expirationIntervalAgo);
 }
 
 // Traverse the history list to get all the entry data
-void history_entry_foreach_to_remove (gpointer data, gpointer user_data)
+void history_entry_foreach_to_remove(gpointer data, gpointer user_data)
 {
   HistoryEntry *entry = (HistoryEntry *) data;
   if (entry) {
-    if (entry->url)
-      g_free(entry->url);
-    entry->url = NULL;
-    /* XXX data should be a class and we should use new/delete instead of
-     * g_crash_happy.
-     */
-    entry->mTitle.~nsCString();
     entry->mLastVisitTime = 0;
-    g_free(entry);
+    delete entry;
   }
 }
 
 //*****************************************************************************
 // EmbedGlobalHistory - Creation/Destruction
 //*****************************************************************************
 NS_IMPL_ISUPPORTS2(EmbedGlobalHistory, nsIGlobalHistory2, nsIObserver)
 /* static */
@@ -386,89 +282,86 @@ EmbedGlobalHistory::GetInstance()
       return nsnull;
     NS_ADDREF(sEmbedGlobalHistory);   // addref the global
     if (NS_FAILED(sEmbedGlobalHistory->Init()))
     {
       NS_RELEASE(sEmbedGlobalHistory);
       return nsnull;
     }
   }
-  NS_ADDREF(sEmbedGlobalHistory);   // addref the return result
+  else
+    NS_ADDREF(sEmbedGlobalHistory);   // addref the return result
   return sEmbedGlobalHistory;
 }
 
 /* static */
 void
 EmbedGlobalHistory::DeleteInstance()
 {
   if (sEmbedGlobalHistory)
   {
     delete sEmbedGlobalHistory;
-    sEmbedGlobalHistory = nsnull;
   }
 }
 
 // The global history component constructor
 EmbedGlobalHistory::EmbedGlobalHistory()
 : mFileHandle(nsnull)
 {
   if (!mURLList) {
     mDataIsLoaded = PR_FALSE;
+    mFlushModeFullWriteNeeded = PR_FALSE;
     mEntriesAddedSinceFlush = 0;
     mHistoryFile = nsnull;
     LL_I2L(mExpirationInterval, kDefaultExpirationIntervalDays);
     LL_MUL(mExpirationInterval, mExpirationInterval, kMSecsPerDay);
   }
 }
 
 // The global history component destructor
 EmbedGlobalHistory::~EmbedGlobalHistory()
 {
   LoadData();
-  FlushData();
+  FlushData(kFlushModeFullWrite);
   if (mURLList) {
     g_list_foreach(mURLList, (GFunc) history_entry_foreach_to_remove, NULL);
     g_list_free(mURLList);
     mURLList = NULL;
   }
   if (mFileHandle) {
     CLOSE_FILE_HANDLE(mFileHandle);
   }
   if (mHistoryFile) {
     g_free(mHistoryFile);
     mHistoryFile = nsnull;
   }
+  if (sEmbedGlobalHistory)
+    sEmbedGlobalHistory = nsnull;
 }
 
 // Initialize the global history component
 NS_IMETHODIMP EmbedGlobalHistory::Init()
 {
   if (mURLList) return NS_OK;
   // Get Pref and convert to millisecs
 
-#ifdef MOZ_ENABLE_GNOMEVFS
-  /*GnomeVFS */
-  if (!gnome_vfs_initialized()) {
-    if (!gnome_vfs_init())
-      NS_WARNING("Could not init GnomeVFS!\n");
-  }
-#endif
-
   PRInt32 expireDays;
   int success = gtk_moz_embed_common_get_pref(G_TYPE_INT, EMBED_HISTORY_PREF_EXPIRE_DAYS, &expireDays);
   if (success) {
     LL_I2L(mExpirationInterval, expireDays);
     LL_MUL(mExpirationInterval, mExpirationInterval, kMSecsPerDay);
   }
   // register to observe profile changes
   nsCOMPtr<nsIObserverService> observerService =
     do_GetService(NS_OBSERVERSERVICE_CONTRACTID);
   NS_ASSERTION(observerService, "failed to get observer service");
-  if (observerService)
+  if (observerService) {
     observerService->AddObserver(this, "quit-application", PR_FALSE);
+    observerService->AddObserver(this, "RemoveEntries", PR_FALSE);
+  }
   nsresult rv = InitFile();
   if (NS_FAILED(rv))
     return NS_ERROR_FAILURE;
   rv = LoadData();
   NS_ENSURE_SUCCESS(rv, rv);
   return rv;
 }
 
@@ -499,33 +392,41 @@ NS_IMETHODIMP EmbedGlobalHistory::Init()
    * used or malloc, or new (note that gecko /will/ be replacing  \
    * its operator new such that new will not throw exceptions).   \
    * XXX please fix me.                                           \
    */                                                             \
   if (!newed) {                                                   \
   }                                                               \
   PR_END_MACRO
 
+#define ALLOC_NOT_CHECKED(newed) PR_BEGIN_MACRO               \
+  /* This might not crash, but the code probably isn't really \
+   * designed to handle it, perhaps the code should be fixed? \
+   */                                                         \
+  if (!newed) {                                               \
+  }                                                           \
+  PR_END_MACRO
+
 //*****************************************************************************
 // EmbedGlobalHistory::nsIGlobalHistory
 //*****************************************************************************
 // Add a new URI to the history
 NS_IMETHODIMP EmbedGlobalHistory::AddURI(nsIURI *aURI, PRBool aRedirect, PRBool aToplevel, nsIURI *aReferrer)
 {
   NS_ENSURE_ARG(aURI);
   nsCAutoString URISpec;
   aURI->GetSpec(URISpec);
   const char *aURL = URISpec.get();
   if (!aToplevel)
     return NS_OK;
   PRBool isHTTP, isHTTPS;
   nsresult rv = NS_OK;
   rv |= aURI->SchemeIs("http", &isHTTP);
   rv |= aURI->SchemeIs("https", &isHTTPS);
-  NS_ENSURE_SUCCESS (rv, NS_ERROR_FAILURE);
+  NS_ENSURE_SUCCESS(rv, NS_ERROR_FAILURE);
   // Only get valid uri schemes
   if (!isHTTP && !isHTTPS)
   {
     /* the following blacklist is silly.
      * if there's some need to whitelist http(s) + ftp,
      * that's what we should do.
      */
     PRBool isAbout, isImap, isNews, isMailbox, isViewSource, isChrome, isData, isJavascript;
@@ -545,60 +446,59 @@ NS_IMETHODIMP EmbedGlobalHistory::AddURI
         isViewSource ||
         isChrome ||
         isData ||
         isJavascript) {
       return NS_OK;
     }
   }
 #ifdef DEBUG
-  g_print("[HISTORY] Visited URL: %s\n", aURL);
+  NS_WARNING("[HISTORY] Visited URL: %s\n", aURL);
 #endif
   rv = LoadData();
   NS_ENSURE_SUCCESS(rv, rv);
   GList *node = g_list_find_custom(mURLList, aURL, (GCompareFunc) history_entry_find_exist);
   HistoryEntry *entry = NULL;
   if (node && node->data)
     entry = (HistoryEntry *)(node->data);
   nsCAutoString hostname;
   aURI->GetHost(hostname);
 
   // It is not in the history
   if (!entry) {
-    entry = g_new0(HistoryEntry, 1);
-    UNACCEPTABLE_CRASHY_GLIB_ALLOCATION(entry);
+    entry = new HistoryEntry;
+    ALLOC_NOT_CHECKED(entry);
     rv |= OnVisited(entry);
     SET_TITLE(entry, hostname);
-    rv |= SetURL(entry, aURL);
+    rv |= SET_URL(entry, aURL);
     BROKEN_RV_HANDLING_CODE(rv);
     unsigned int listSize = g_list_length(mURLList);
     if (listSize+1 > kDefaultMaxSize) {
-      GList *last = g_list_last (mURLList);
-      mURLList = g_list_remove (mURLList, last->data);
-      mEntriesAddedSinceFlush++;
+      GList *last = g_list_last(mURLList);
+      mURLList = g_list_remove(mURLList, last->data);
     }
     mURLList = g_list_insert_sorted(mURLList, entry,
                                     (GCompareFunc) find_insertion_place);
     // Flush after kNewEntriesBetweenFlush changes
     BROKEN_RV_HANDLING_CODE(rv);
     if (++mEntriesAddedSinceFlush >= kNewEntriesBetweenFlush)
       rv |= FlushData(kFlushModeAppend);
-    // emit signal to let EAL knows a new item was added
-    //FIXME REIMP g_signal_emit_by_name (g_mozilla_get_current_web(),
-    //"global-history-item-added", aURL);
+    // At this point, something understands there's a new global history item
   } else {
     // update the last visited time
     rv |= OnVisited(entry);
     SET_TITLE(entry, hostname);
     // Move the element to the start of the list
     BROKEN_RV_HANDLING_CODE(rv);
-    mURLList = g_list_remove (mURLList, entry);
+    mURLList = g_list_remove(mURLList, entry);
     mURLList = g_list_insert_sorted(mURLList, entry, (GCompareFunc) find_insertion_place);
     // Flush after kNewEntriesBetweenFlush changes
     BROKEN_RV_HANDLING_CODE(rv);
+    
+    mFlushModeFullWriteNeeded = PR_TRUE;
     if (++mEntriesAddedSinceFlush >= kNewEntriesBetweenFlush)
       rv |= FlushData(kFlushModeFullWrite);
   }
   return rv;
 }
 
 // Return TRUE if the url is already in history
 NS_IMETHODIMP EmbedGlobalHistory::IsVisited(nsIURI *aURI, PRBool *_retval)
@@ -638,18 +538,20 @@ NS_IMETHODIMP EmbedGlobalHistory::SetPag
   GList *node = g_list_find_custom(mURLList, aURL,
                                    (GCompareFunc) history_entry_find_exist);
   HistoryEntry *entry = NULL;
   if (node)
     entry = (HistoryEntry *)(node->data);
   if (entry) {
     SET_TITLE(entry, NS_ConvertUTF16toUTF8(aTitle).get());
     BROKEN_RV_HANDLING_CODE(rv);
+    
+    mFlushModeFullWriteNeeded = PR_TRUE;
     if (++mEntriesAddedSinceFlush >= kNewEntriesBetweenFlush)
-      rv |= FlushData(kFlushModeAppend);
+      rv |= FlushData(kFlushModeFullWrite);
     BROKEN_RV_HANDLING_CODE(rv);
   }
   return rv;
 }
 
 nsresult EmbedGlobalHistory::RemoveEntries(const PRUnichar *url, int time)
 {
   nsresult rv = NS_ERROR_FAILURE;
@@ -657,62 +559,57 @@ nsresult EmbedGlobalHistory::RemoveEntri
     return rv;
 
   if (url) {
     GList *node = g_list_find_custom(mURLList, NS_ConvertUTF16toUTF8(url).get(), (GCompareFunc) history_entry_find_exist);
     if (!node) return rv;
     if (node->data) {
       HistoryEntry *entry = NS_STATIC_CAST(HistoryEntry *,
                                            node->data);
-      if (entry->url) {
-        NS_Free(entry->url);
-        entry->url = nsnull;
-        NS_Free(entry);
-      }
-      entry->mTitle.~nsCString();
+
       entry->mLastVisitTime = 0;
-      mURLList = g_list_remove (mURLList, entry);
+      delete entry;
+      mURLList = g_list_remove(mURLList, entry);
     }
-    // forcing flush.
-    mEntriesAddedSinceFlush = 1;
   } else {
     g_list_foreach (mURLList, (GFunc) history_entry_foreach_to_remove, NULL);
     g_list_free(mURLList);
     mURLList = NULL;
   }
-  mDataIsLoaded = PR_FALSE;
 
+  mFlushModeFullWriteNeeded = PR_TRUE;
+  mEntriesAddedSinceFlush++;
   rv = FlushData(kFlushModeFullWrite);
-  mEntriesAddedSinceFlush = 0;
+
   return rv;
 }
 
 //*****************************************************************************
 // EmbedGlobalHistory::nsIObserver
 //*****************************************************************************
 NS_IMETHODIMP EmbedGlobalHistory::Observe(nsISupports *aSubject,
                                           const char *aTopic,
                                           const PRUnichar *aData)
 {
   nsresult rv = NS_OK;
   // used when the browser is closed and the EmbedGlobalHistory destructor is not called
   if (strcmp(aTopic, "quit-application") == 0) {
     rv = LoadData();
     // we have to sort the list before flush it
-    rv |= FlushData();
+    rv |= FlushData(kFlushModeFullWrite);
     if (mURLList) {
       g_list_foreach(mURLList, (GFunc) history_entry_foreach_to_remove, NULL);
       g_list_free(mURLList);
       mURLList = NULL;
     }
     if (mFileHandle) {
       CLOSE_FILE_HANDLE(mFileHandle);
     }
   } else if (strcmp(aTopic, "RemoveEntries") == 0) {
-    RemoveEntries(aData);
+    rv |= RemoveEntries(aData, 0);
   }
   return rv;
 }
 
 static nsresult
 GetHistoryFileName(char **aHistoryFile)
 {
   NS_ENSURE_ARG_POINTER(aHistoryFile);
@@ -743,28 +640,28 @@ nsresult EmbedGlobalHistory::InitFile()
 
   LOCAL_FILE *uri = file_handle_uri_new(mHistoryFile);
   if (!uri)
     return NS_ERROR_FAILURE;
 
   gboolean rs = FALSE;
   if (!file_handle_uri_exists(uri)) {
     if (!file_handle_create_uri(&mFileHandle, uri)) {
-      printf("Could not create a history file\n");
+      NS_WARNING("Could not create a history file\n");
       file_handle_uri_release(uri);
       return NS_ERROR_FAILURE;
     }
     CLOSE_FILE_HANDLE(mFileHandle);
   }
   rs = file_handle_open_uri(&mFileHandle, uri);
 
   file_handle_uri_release(uri);
 
   if (!rs) {
-    printf("Could not open a history file\n");
+    NS_WARNING("Could not open a history file\n");
     return NS_ERROR_FAILURE;
   }
   return NS_OK;
 }
 
 // Get the data from history.dat file
 nsresult EmbedGlobalHistory::LoadData()
 {
@@ -831,33 +728,35 @@ nsresult EmbedGlobalHistory::FlushData(P
     return rv;
   }
   LOCAL_FILE *uri = file_handle_uri_new(mHistoryFile);
   if (!uri) return NS_ERROR_FAILURE;
 
   gboolean rs = file_handle_uri_exists(uri);
   file_handle_uri_release(uri);
 
-  if (!rs && NS_FAILED(InitFile()))
+  if (!rs && NS_FAILED(rv))
     return NS_ERROR_FAILURE;
 
-  if (mode == kFlushModeAppend)
+  if (mode == kFlushModeFullWrite || mFlushModeFullWriteNeeded == PR_TRUE)
+  {
+    if (!file_handle_seek(mFileHandle, FALSE))
+      return NS_ERROR_FAILURE;
+    if (!file_handle_truncate(mFileHandle))
+      return NS_ERROR_FAILURE;
+    WriteEntryIfWritten(mURLList, mFileHandle);
+    mFlushModeFullWriteNeeded = PR_FALSE;
+  }
+  else
   {
     if (!file_handle_seek(mFileHandle, TRUE))
       return NS_ERROR_FAILURE;
     WriteEntryIfUnwritten(mURLList, mFileHandle);
   }
-  else
-  {
-    if (!file_handle_seek(mFileHandle, FALSE))
-      return NS_ERROR_FAILURE;
-    if (!file_handle_truncate (mFileHandle))
-      return NS_ERROR_FAILURE;
-    WriteEntryIfWritten(mURLList, mFileHandle);
-  }
+
   mEntriesAddedSinceFlush = 0;
   return NS_OK;
 }
 
 // Split an entry in last visit time, title and url.
 // Add a stored entry in the history.dat file in the history hash table
 nsresult EmbedGlobalHistory::GetEntry(const char *entry)
 {
@@ -893,26 +792,25 @@ nsresult EmbedGlobalHistory::GetEntry(co
       url[urlLength++] = entry[pos];
     } else {
       title[titleLength++] = entry[pos];
   }
   pos++;
   }
   url[urlLength]='\0';
   title[titleLength]='\0';
-  HistoryEntry *newEntry = g_new0(HistoryEntry, 1);
-  UNACCEPTABLE_CRASHY_GLIB_ALLOCATION(newEntry);
+  HistoryEntry *newEntry = new HistoryEntry;
   if (!newEntry)
     return NS_ERROR_OUT_OF_MEMORY;
 
   nsresult rv = NS_OK;
   SET_TITLE(newEntry, title);
   rv |= SetLastVisitTime(newEntry, outValue);
   rv |= SetIsWritten(newEntry);
-  rv |= SetURL(newEntry, url);
+  rv |= SET_URL(newEntry, url);
   BROKEN_RV_HANDLING_CODE(rv);
   // Check wheter the entry has expired
   if (!entryHasExpired(newEntry)) {
     mURLList = g_list_prepend(mURLList, newEntry);
   }
   return rv;
 }
 
@@ -920,17 +818,16 @@ nsresult EmbedGlobalHistory::GetEntry(co
 // Get the history entries from history.dat file
 nsresult EmbedGlobalHistory::ReadEntries(LOCAL_FILE *file_uri)
 {
   if (!file_uri)
     return NS_ERROR_FAILURE;
 
   nsresult rv = NS_OK;
 
-#ifndef MOZ_ENABLE_GNOMEVFS
   nsCOMPtr<nsIInputStream> fileStream;
   NS_NewLocalFileInputStream(getter_AddRefs(fileStream), file_uri);
   if (!fileStream)
     return NS_ERROR_OUT_OF_MEMORY;
   nsCOMPtr<nsILineInputStream> lineStream = do_QueryInterface(fileStream, &rv);
   NS_ASSERTION(lineStream, "File stream is not an nsILineInputStream");
   // Read the header
   nsCString utf8Buffer;
@@ -944,64 +841,16 @@ nsresult EmbedGlobalHistory::ReadEntries
       return NS_OK;
 
     if (utf8Buffer.IsEmpty())
       continue;
     rv = GetEntry(utf8Buffer.get());
   } while (moreData && safe_limit < kMaxSafeReadEntriesCount);
   fileStream->Close();
 
-#else
-  bool exists = file_handle_uri_exists(file_uri);
-  if (exists && !mFileHandle) {
-    rv = InitFile();
-    if (NS_FAILED(rv))
-      return NS_ERROR_FAILURE;
-  }
-  if (!file_handle_seek(mFileHandle, FALSE))
-    return NS_ERROR_FAILURE;
-
-  guint64 bytes;
-  int64 read_bytes;
-  char separator = (char) defaultSeparator;
-  int pos = 0;
-  int numStrings = 0;
-  file_handle_file_info_block_size (mFileHandle, &bytes);
-  /* Optimal buffer size for reading/writing the file. */
-  nsAutoArrayPtr<char> line(new char[bytes]);
-  nsAutoArrayPtr<char> buffer(new char[bytes]);
-  if (!line || !buffer)
-    return NS_ERROR_OUT_OF_MEMORY;
-
-  do {
-    read_bytes = file_handle_read(mFileHandle, (gpointer) buffer, bytes-1);
-    if (read_bytes < 0)
-      break;
-    buffer[read_bytes] = '\0';
-    unsigned int buf_pos = 0;
-    while (buf_pos< read_bytes) {
-      if (buffer[buf_pos]== separator)
-        numStrings++;
-      if (buffer[buf_pos]!= '\n')
-        line[pos] = buffer[buf_pos];
-      else
-        buf_pos++;
-      if (numStrings==3) {
-        line[pos+1] = '\0';
-        rv = GetEntry(line);
-        if (NS_FAILED(rv))
-          return NS_ERROR_FAILURE;
-        pos = -1;
-        numStrings = 0;
-      }
-      pos++;
-      buf_pos++;
-    }
-  } while (read_bytes != -1);
-#endif
   return rv;
 }
 
 //*****************************************************************************
 // Static Functions
 //*****************************************************************************
 // Get last visit time from a string
 static nsresult writePRInt64(char time[14], const PRInt64& inValue)
@@ -1023,19 +872,19 @@ static nsresult writePRInt64(char time[1
 
 // Write an entry in the history.dat file
 nsresult writeEntry(OUTPUT_STREAM *file_handle, HistoryEntry *entry)
 {
   nsresult rv = NS_OK;
   char sep = (char) defaultSeparator;
   char time[14];
   writePRInt64(time, GetLastVisitTime(entry));
-  char *line = g_strdup_printf("%s%c%s%c%s%c\n", time, sep, GetURL(entry), sep, GET_TITLE(entry).get(), sep);
+  char *line = g_strdup_printf("%s%c%s%c%s%c\n", time, sep, GET_URL(entry), sep, GET_TITLE(entry), sep);
   BROKEN_STRING_BUILDER(line);
-  guint64 size = file_handle_write (file_handle, (gpointer)line);
+  guint64 size = file_handle_write(file_handle, (gpointer)line);
   if (size != strlen(line))
     rv = NS_ERROR_FAILURE;
   rv |= SetIsWritten(entry);
   g_free(line);
   return rv;
 }
 
 nsresult EmbedGlobalHistory::GetContentList(GtkMozHistoryItem **GtkHI, int *count)
@@ -1053,19 +902,19 @@ nsresult EmbedGlobalHistory::GetContentL
     if (entryHasExpired(entry)) {
       break;
     }
     glong accessed;
     PRInt64 temp, outValue;
     LL_MUL(outValue, GetLastVisitTime(entry), kOneThousand);
     LL_DIV(temp, outValue, PR_USEC_PER_SEC);
     LL_L2I(accessed, temp);
-    // Set the EAL history list
-    item[num_items].title = GET_TITLE(entry).get();
+    // Set the External history list
+    item[num_items].title = GET_TITLE(entry);
     BROKEN_STRING_BUILDER(item[num_items].title);
-    item[num_items].url = GetURL(entry);
+    item[num_items].url = GET_URL(entry);
     item[num_items].accessed = accessed;
     num_items++;
   }
   *count = num_items;
   return NS_OK;
 }
 
--- a/embedding/browser/gtk/src/EmbedGlobalHistory.h
+++ b/embedding/browser/gtk/src/EmbedGlobalHistory.h
@@ -40,24 +40,18 @@
 #define __EMBEDGLOBALHISTORY_h
 #include "nsIGlobalHistory2.h"
 #include "nsIObserver.h"
 #include "EmbedPrivate.h"
 #include <prenv.h>
 #include <gtk/gtk.h>
 #include "nsDocShellCID.h"
 
-#ifdef MOZ_ENABLE_GNOMEVFS
-#include <libgnomevfs/gnome-vfs.h>
-#define OUTPUT_STREAM GnomeVFSHandle
-#define LOCAL_FILE GnomeVFSURI
-#else
 #define OUTPUT_STREAM nsIOutputStream
 #define LOCAL_FILE nsILocalFile
-#endif
 
 //#include "gtkmozembed_common.h"
 /* {2f977d51-5485-11d4-87e2-0010a4e75ef2} */
 #define NS_EMBEDGLOBALHISTORY_CID \
   { 0x2f977d51, 0x5485, 0x11d4, \
   { 0x87, 0xe2, 0x00, 0x10, 0xa4, 0xe7, 0x5e, 0xf2 } }
 #define EMBED_HISTORY_PREF_EXPIRE_DAYS      "browser.history_expire_days"
 /** The Mozilla History Class
@@ -118,16 +112,17 @@ class EmbedGlobalHistory: public nsIGlob
   */
     nsresult          ReadEntries(LOCAL_FILE *file_uri);
 /** Gets a history entry 
   * @param name The history entry name.
   * @return NS_OK if the history entry name was gotten.
   */
     nsresult          GetEntry(const char *);
     protected:
-    OUTPUT_STREAM    *mFileHandle;             /** < The History File handle */
-    PRBool            mDataIsLoaded;           /** < If the data is loaded */
-    PRInt32           mEntriesAddedSinceFlush; /** < Number of entries added since flush */
-    gchar*            mHistoryFile;            /** < The history file path */
+    OUTPUT_STREAM    *mFileHandle;              /** < The History File handle */
+    PRBool            mDataIsLoaded;            /** < If the data is loaded */
+    PRBool            mFlushModeFullWriteNeeded;/** < If needs a full flush */
+    PRInt32           mEntriesAddedSinceFlush;  /** < Number of entries added since flush */
+    gchar*            mHistoryFile;             /** < The history file path */
 };
 // Default maximum history entries
 static const PRUint32 kDefaultMaxSize = 1000;
 #endif
--- a/embedding/browser/gtk/src/EmbedGtkTools.cpp
+++ b/embedding/browser/gtk/src/EmbedGtkTools.cpp
@@ -74,32 +74,15 @@ GtkWindow * GetGtkWindowForDOMWindow(nsI
   if (!parentWidget)
     return NULL;
   GtkWidget* gtkWin = gtk_widget_get_toplevel(parentWidget);
   if (GTK_WIDGET_TOPLEVEL(gtkWin))
     return GTK_WINDOW(gtkWin);
   return NULL;
 }
 
-nsresult GetContentViewer (nsIWebBrowser *webBrowser, nsIContentViewer **aViewer)
+nsresult GetContentViewer(nsIWebBrowser *webBrowser, nsIContentViewer **aViewer)
 {
   g_return_val_if_fail(webBrowser, NS_ERROR_FAILURE);
   nsCOMPtr<nsIDocShell> docShell(do_GetInterface((nsISupports*)webBrowser));
   NS_ENSURE_TRUE(docShell, NS_ERROR_FAILURE);
   return docShell->GetContentViewer(aViewer);
 }
-
-PRUnichar *LocaleToUnicode (const char *locStr)
-{
-  if (!locStr)
-    return NULL;
-
-  nsAutoString autoStr;
-#ifdef MOZILLA_INTERNAL_API //FIXME?
-
-  autoStr.AssignWithConversion (locStr);
-#else
-  autoStr.AssignLiteral (locStr);
-#endif
-  PRUnichar *uniStr = ToNewUnicode(autoStr);
-
-  return uniStr;
-}
--- a/embedding/browser/gtk/src/EmbedGtkTools.h
+++ b/embedding/browser/gtk/src/EmbedGtkTools.h
@@ -57,14 +57,11 @@
 
 GtkWidget*
 GetGtkWidgetForDOMWindow(nsIDOMWindow* aDOMWindow);
 
 GtkWindow*
 GetGtkWindowForDOMWindow(nsIDOMWindow* aDOMWindow);
 
 nsresult
-GetContentViewer (nsIWebBrowser *webBrowser, nsIContentViewer **aViewer);
-
-PRUnichar*
-LocaleToUnicode (const char *locStr);
+GetContentViewer(nsIWebBrowser *webBrowser, nsIContentViewer **aViewer);
 
 #endif /* __EmbedTools_h */
--- a/embedding/browser/gtk/src/EmbedPasswordMgr.cpp
+++ b/embedding/browser/gtk/src/EmbedPasswordMgr.cpp
@@ -73,42 +73,38 @@
 #include "nsIDOMEventTarget.h"
 #include "nsIDOMHTMLFormElement.h"
 #include "nsIPK11TokenDB.h"
 #include "nsIPK11Token.h"
 #include "nsUnicharUtils.h"
 #include "nsCOMArray.h"
 #include "nsIServiceManager.h"
 #include "nsIIDNService.h"
-
 #include "nsIAuthInformation.h"
 #include "nsIChannel.h"
-#include "nsIPromptService2.h"
+
 #include "nsIProxiedChannel.h"
 #include "nsIProxyInfo.h"
 #include "nsIURI.h"
 #include "nsNetUtil.h"
 #include "nsEmbedCID.h"
-#include "nsPromptUtils.h"
-
+#include "nsIPromptService2.h"
 #include "EmbedPrivate.h"
 #include "gtkmozembedprivate.h"
 #ifdef MOZILLA_INTERNAL_API
 #include "nsString.h"
 #include "nsXPIDLString.h"
-#include "nsIForm.h"
 #else
 #include "nsDirectoryServiceUtils.h"
-//FIXME
-typedef char* nsXPIDLCString;
-typedef PRUnichar* nsXPIDLString;
-#define getter_Copies(str) &str
 #include "nsComponentManagerUtils.h"
+#include "nsStringAPI.h"
+#endif
+#if defined(FIXED_BUG347731) || !defined(MOZ_ENABLE_LIBXUL)
+#include "nsPromptUtils.h"
 #include "nsIForm.h"
-#include "nsStringAPI.h"
 #endif
 #include "nsIPassword.h"
 #include "nsIPasswordInternal.h"
 #include <string.h>
 
 
 static const char kPMPropertiesURL[] = "chrome://passwordmgr/locale/passwordmgr.properties";
 static PRBool sRememberPasswords = PR_FALSE;
@@ -291,30 +287,23 @@ EmbedPasswordMgr::Init()
   // prefill passwords.
   nsCOMPtr<nsIObserverService> obsService = do_GetService(NS_OBSERVERSERVICE_CONTRACTID);
   NS_ASSERTION(obsService, "No observer service");
   obsService->AddObserver(this, NS_FORMSUBMIT_SUBJECT, PR_TRUE);
   nsCOMPtr<nsIWebProgress> progress = do_GetService(NS_DOCUMENTLOADER_SERVICE_CONTRACTID);
   NS_ASSERTION(progress, "No web progress service");
   progress->AddProgressListener(this, nsIWebProgress::NOTIFY_STATE_DOCUMENT);
   // Now read in the signon file
-  nsXPIDLCString signonFile;
-  mPrefBranch->GetCharPref("SignonFileName", getter_Copies(signonFile));
-#ifdef MOZILLA_INTERNAL_API
-  NS_ASSERTION(!signonFile.IsEmpty(), "Fallback for signon filename not present");
-#endif
+  char* signonFile = nsnull;
+  mPrefBranch->GetCharPref("SignonFileName", &signonFile);
+  NS_ASSERTION(signonFile, "Fallback for signon filename not present");
   NS_GetSpecialDirectory(NS_APP_USER_PROFILE_50_DIR, getter_AddRefs(mSignonFile));
   NS_ENSURE_TRUE(mSignonFile, NS_ERROR_FAILURE);
-#ifdef MOZILLA_INTERNAL_API
-  mSignonFile->AppendNative(signonFile);
-#else
-  nsCString cSignonFile(signonFile);
-  mSignonFile->AppendNative(cSignonFile);
-#endif
-  nsCAutoString path;
+  mSignonFile->AppendNative(nsCString(signonFile));
+  nsCString path;
   mSignonFile->GetNativePath(path);
   ReadPasswords(mSignonFile);
   return NS_OK;
 }
 
 /* static */ PRBool
 EmbedPasswordMgr::SingleSignonEnabled()
 {
@@ -333,30 +322,30 @@ EmbedPasswordMgr::Register(nsIComponentM
                            const nsModuleComponentInfo* aInfo)
 {
   // By registering in NS_PASSWORDMANAGER_CATEGORY, an instance of the password
   // manager will be created when a password input is added to a form.  We
   // can then register that singleton instance as a form submission observer.
   nsresult rv;
   nsCOMPtr<nsICategoryManager> catman = do_GetService(NS_CATEGORYMANAGER_CONTRACTID, &rv);
   NS_ENSURE_SUCCESS(rv, rv);
-  nsXPIDLCString prevEntry;
+  char* prevEntry;
   catman->AddCategoryEntry(NS_PASSWORDMANAGER_CATEGORY,
                            "MicroB Password Manager",
                            NS_PASSWORDMANAGER_CONTRACTID,
                            PR_TRUE,
                            PR_TRUE,
-                           getter_Copies(prevEntry));
+                           &prevEntry);
 
   catman->AddCategoryEntry("app-startup",
                            "MicroB Password Manager",
                            NS_PASSWORDMANAGER_CONTRACTID,
                            PR_TRUE,
                            PR_TRUE,
-                           getter_Copies(prevEntry));
+                           &prevEntry);
 
   return NS_OK;
 }
 
 /* static */ NS_METHOD
 EmbedPasswordMgr::Unregister(nsIComponentManager* aCompMgr,
                              nsIFile* aPath,
                              const char* aRegistryLocation,
@@ -412,102 +401,102 @@ EmbedPasswordMgr::AddUser(const nsACStri
   WritePasswords(mSignonFile);
   return NS_OK;
 }
 
 NS_IMETHODIMP
 EmbedPasswordMgr::InsertLogin(const char* username, const char* password)
 {
   if (username && mGlobalUserField)
-    mGlobalUserField->SetValue (NS_ConvertUTF8toUTF16(username));
+    mGlobalUserField->SetValue(NS_ConvertUTF8toUTF16(username));
   else
     return NS_ERROR_FAILURE;
 
   if (password && mGlobalPassField)
-    mGlobalPassField->SetValue (NS_ConvertUTF8toUTF16(password));
+    mGlobalPassField->SetValue(NS_ConvertUTF8toUTF16(password));
   else
     FillPassword();
 
   return NS_OK;
 }
 
 NS_IMETHODIMP
 EmbedPasswordMgr::RemovePasswordsByIndex(PRUint32 aIndex)
 {
   nsCOMPtr<nsIPasswordManager> passwordManager = do_GetService(NS_PASSWORDMANAGER_CONTRACTID);
   if (!passwordManager)
     return NS_ERROR_NULL_POINTER;
-  nsCOMPtr<nsIIDNService> idnService (do_GetService ("@mozilla.org/network/idn-service;1"));
+  nsCOMPtr<nsIIDNService> idnService(do_GetService("@mozilla.org/network/idn-service;1"));
   if (!idnService)
     return NS_ERROR_NULL_POINTER;
-  nsresult result = NS_ERROR_FAILURE;
   nsCOMPtr<nsISimpleEnumerator> passwordEnumerator;
-  result = passwordManager->GetEnumerator(getter_AddRefs(passwordEnumerator));
-  if (NS_FAILED(result))
-    return result;
+  nsresult rv = passwordManager->GetEnumerator(getter_AddRefs(passwordEnumerator));
+  if (NS_FAILED(rv))
+    return rv;
   PRBool enumResult;
   PRUint32 i = 0;
   nsCOMPtr<nsIPassword> nsPassword;
   for (passwordEnumerator->HasMoreElements(&enumResult);
        enumResult == PR_TRUE && i <= aIndex;
        passwordEnumerator->HasMoreElements(&enumResult)) {
 
-    result = passwordEnumerator->GetNext (getter_AddRefs(nsPassword));
-    if (NS_FAILED(result) || !nsPassword)
-      return result;
+    rv = passwordEnumerator->GetNext(getter_AddRefs(nsPassword));
+    if (NS_FAILED(rv) || !nsPassword)
+      return rv;
 
     nsCString host;
-    nsPassword->GetHost (host);
+    nsPassword->GetHost(host);
 
-    if (StringBeginsWith (host, mLastHostQuery))
+    if (StringBeginsWith(host, mLastHostQuery))
       i++;
   }
 
   // if we found the right object to delete
   if (nsPassword) {
 
     nsCString host, idn_host;
     nsString unicodeName;
 
-    nsPassword->GetHost (host);
-    nsPassword->GetUser (unicodeName);
-    result = idnService->ConvertUTF8toACE (host, idn_host);
+    nsPassword->GetHost(host);
+    nsPassword->GetUser(unicodeName);
+    rv = idnService->ConvertUTF8toACE(host, idn_host);
 
-    result = passwordManager->RemoveUser(idn_host, unicodeName);
+    rv = passwordManager->RemoveUser(idn_host, unicodeName);
   }
   return NS_OK;
 }
 
 NS_IMETHODIMP
 EmbedPasswordMgr::RemovePasswords(const char *aHostName, const char *aUserName)
 {
   nsCOMPtr<nsIPasswordManager> passwordManager = do_GetService(NS_PASSWORDMANAGER_CONTRACTID);
   if (!passwordManager)
     return NS_ERROR_NULL_POINTER;
-  nsCOMPtr<nsIIDNService> idnService (do_GetService ("@mozilla.org/network/idn-service;1"));
+  nsCOMPtr<nsIIDNService> idnService(do_GetService("@mozilla.org/network/idn-service;1"));
   if (!idnService)
     return NS_ERROR_NULL_POINTER;
-  nsresult result = NS_ERROR_FAILURE;
   nsCOMPtr<nsISimpleEnumerator> passwordEnumerator;
-  result = passwordManager->GetEnumerator(getter_AddRefs(passwordEnumerator));
-  if (NS_FAILED(result))
-    return result;
+  nsresult rv = passwordManager->GetEnumerator(getter_AddRefs(passwordEnumerator));
+  if (NS_FAILED(rv))
+    return rv;
   PRBool enumResult;
   for (passwordEnumerator->HasMoreElements(&enumResult);
-       enumResult == PR_TRUE ; passwordEnumerator->HasMoreElements(&enumResult)) {
+       enumResult;
+       passwordEnumerator->HasMoreElements(&enumResult)) {
     nsCOMPtr<nsIPassword> nsPassword;
-    result = passwordEnumerator->GetNext (getter_AddRefs(nsPassword));
-    if (NS_FAILED(result)) return FALSE;
+    rv = passwordEnumerator->GetNext(getter_AddRefs(nsPassword));
+    /* XXX XXX FALSE = NS_OK this is almost certainly wrong */
+    if (NS_FAILED(rv)) return FALSE;
     nsCString host, idn_host;
 
-    nsPassword->GetHost (host);
+    nsPassword->GetHost(host);
     nsString unicodeName;
-    nsPassword->GetUser (unicodeName);
-    result = idnService->ConvertUTF8toACE (host, idn_host);
-    result = passwordManager->RemoveUser(idn_host, unicodeName);
+    nsPassword->GetUser(unicodeName);
+    rv = idnService->ConvertUTF8toACE(host, idn_host);
+    rv = passwordManager->RemoveUser(idn_host, unicodeName);
   }
   return NS_OK;
 }
 
 NS_IMETHODIMP
 EmbedPasswordMgr::RemoveUser(const nsACString& aHost, const nsAString& aUser)
 {
   SignonDataEntry* entry, *prevEntry = nsnull;
@@ -549,17 +538,17 @@ EmbedPasswordMgr::RemoveReject(const nsA
   mRejectTable.Remove(aHost);
   WritePasswords(mSignonFile);
   return NS_OK;
 }
 
 NS_IMETHODIMP
 EmbedPasswordMgr::IsEqualToLastHostQuery(nsCString& aHost)
 {
-  return StringBeginsWith (aHost, mLastHostQuery);
+  return StringBeginsWith(aHost, mLastHostQuery);
 }
 
 /* static */ PLDHashOperator PR_CALLBACK
 EmbedPasswordMgr::BuildArrayEnumerator(const nsACString& aKey,
                                        SignonHashEntry* aEntry,
                                        void* aUserData)
 {
   nsIMutableArray* array = NS_STATIC_CAST(nsIMutableArray*, aUserData);
@@ -876,31 +865,32 @@ EmbedPasswordMgr::OnStateChange(nsIWebPr
     return NS_OK;
   nsCOMPtr<nsIDOMHTMLCollection> forms;
   htmlDoc->GetForms(getter_AddRefs(forms));
   nsCOMPtr<nsIDocument> doc = do_QueryInterface(domDoc);
   nsCAutoString realm;
   if (!GetPasswordRealm(doc->GetDocumentURI(), realm))
     return NS_OK;
 
-  mLastHostQuery.Assign (realm);
+  mLastHostQuery.Assign(realm);
 
   SignonHashEntry* hashEnt;
   if (!mSignonTable.Get(realm, &hashEnt))
     return NS_OK;
   PRUint32 formCount;
   forms->GetLength(&formCount);
   // check to see if we should formfill.  failure is non-fatal
   PRBool prefillForm = PR_TRUE;
   mPrefBranch->GetBoolPref("autofillForms", &prefillForm);
 
   // We can auto-prefill the username and password if there is only
   // one stored login that matches the username and password field names
   // on the form in question.  Note that we only need to worry about a
   // single login per form.
+#if defined(FIXED_BUG347731) || !defined(MOZ_ENABLE_LIBXUL)
   for (PRUint32 i = 0; i < formCount; ++i) {
     nsCOMPtr<nsIDOMNode> formNode;
     forms->Item(i, getter_AddRefs(formNode));
     nsCOMPtr<nsIForm> form = do_QueryInterface(formNode);
     SignonDataEntry* firstMatch = nsnull;
     PRBool attachedToInput = PR_FALSE;
     PRBool prefilledUser = PR_FALSE;
     nsCOMPtr<nsIDOMHTMLInputElement> userField, passField;
@@ -1018,17 +1008,17 @@ EmbedPasswordMgr::OnStateChange(nsIWebPr
         if (userField) {
           if (NS_FAILED(DecryptData(firstMatch->userValue, buffer)))
             goto done;
         }
 
         if (!prefilledUser) {
           GList * logins = nsnull;
           NS_ConvertUTF16toUTF8 login(buffer);
-          logins = g_list_append(logins, login.get());
+          logins = g_list_append(logins, login.BeginWriting());
           gint retval = -1;
           gtk_signal_emit(GTK_OBJECT(mCommonObject->mCommon),
                           moz_embed_common_signals[COMMON_SELECT_LOGIN],
                           logins, &retval);
 
           g_list_free(logins);
 
           if (retval != -1) {
@@ -1038,16 +1028,17 @@ EmbedPasswordMgr::OnStateChange(nsIWebPr
             passField->SetValue(buffer);
           }
         }
       }
     }
     mGlobalUserField = userField;
     mGlobalPassField = passField;
   }
+#endif
 done:
   nsCOMPtr<nsIDOMEventTarget> targ = do_QueryInterface(domDoc);
   targ->AddEventListener(
       NS_LITERAL_STRING("unload"),
       NS_STATIC_CAST(nsIDOMLoadListener*, this),
       PR_FALSE);
   return NS_OK;
 }
@@ -1107,16 +1098,17 @@ EmbedPasswordMgr::Notify(nsIContent* aFo
   // XXX at a problem with document teardown while a modal dialog is posted.
   if (!GetPasswordRealm(aFormNode->GetOwnerDoc()->GetDocumentURI(), realm))
     return NS_OK;
   PRInt32 rejectValue;
   if (mRejectTable.Get(realm, &rejectValue)) {
     // The user has opted to never save passwords for this site.
     return NS_OK;
   }
+#if defined(FIXED_BUG347731) || !defined(MOZ_ENABLE_LIBXUL)
   nsCOMPtr<nsIForm> formElement = do_QueryInterface(aFormNode);
   PRUint32 numControls;
   formElement->GetElementCount(&numControls);
   // Count the number of password fields in the form.
   nsCOMPtr<nsIDOMHTMLInputElement> userField;
   nsCOMArray<nsIDOMHTMLInputElement> passFields;
   PRUint32 i, firstPasswordIndex = numControls;
   for (i = 0; i < numControls; ++i) {
@@ -1142,44 +1134,32 @@ EmbedPasswordMgr::Notify(nsIContent* aFo
         if (control->GetType() == NS_FORM_INPUT_TEXT) {
           userField = do_QueryInterface(control);
           break;
         }
       }
       // If the username field or the form has autocomplete=off,
       // we don't store the login
       if (!sForceAutocompletion) {
-        nsAutoString autocomplete;
+        nsString autocomplete;
         if (userField) {
           nsCOMPtr<nsIDOMElement> userFieldElement = do_QueryInterface(userField);
           userFieldElement->GetAttribute(NS_LITERAL_STRING("autocomplete"),
                                          autocomplete);
-#ifdef MOZILLA_INTERNAL_API
-          if (autocomplete.EqualsIgnoreCase("off"))
-#else
-            if (autocomplete.LowerCaseEqualsLiteral("off"))
-#endif
-              return NS_OK;
+          if (autocomplete.LowerCaseEqualsLiteral("off"))
+            return NS_OK;
         }
         nsCOMPtr<nsIDOMElement> formDOMEl = do_QueryInterface(aFormNode);
         formDOMEl->GetAttribute(NS_LITERAL_STRING("autocomplete"), autocomplete);
-#ifdef MOZILLA_INTERNAL_API
-        if (autocomplete.EqualsIgnoreCase("off"))
-#else
-          if (autocomplete.LowerCaseEqualsLiteral("off"))
-#endif
+        if (autocomplete.LowerCaseEqualsLiteral("off"))
             return NS_OK;
         nsCOMPtr<nsIDOMElement> passFieldElement = do_QueryInterface(passFields.ObjectAt(0));
         passFieldElement->GetAttribute(NS_LITERAL_STRING("autocomplete"), autocomplete);
-#ifdef MOZILLA_INTERNAL_API
-        if (autocomplete.EqualsIgnoreCase("off"))
-#else
-          if (autocomplete.LowerCaseEqualsLiteral("off"))
-#endif
-            return NS_OK;
+        if (autocomplete.LowerCaseEqualsLiteral("off"))
+          return NS_OK;
       }
       // Check whether this signon is already stored.
       // Note that we don't prompt the user if only the password doesn't match;
       // we instead just silently change the stored password.
       nsAutoString userValue, passValue, userFieldName, passFieldName;
       if (userField) {
         userField->GetValue(userValue);
         userField->GetName(userFieldName);
@@ -1213,26 +1193,22 @@ EmbedPasswordMgr::Notify(nsIContent* aFo
       }
       nsresult rv;
       nsCOMPtr<nsIStringBundleService> bundleService =
         do_GetService(NS_STRINGBUNDLE_CONTRACTID, &rv);
       nsCOMPtr<nsIStringBundle> brandBundle;
       rv = bundleService->CreateBundle("chrome://branding/locale/brand.properties",
                                        getter_AddRefs(brandBundle));
       NS_ENSURE_SUCCESS(rv, rv);
-      nsXPIDLString brandShortName;
+      nsString brandShortName;
       rv = brandBundle->GetStringFromName(NS_LITERAL_STRING("brandShortName").get(),
                                           getter_Copies(brandShortName));
       NS_ENSURE_SUCCESS(rv, rv);
       const PRUnichar* formatArgs[1] = {
-#ifdef MOZILLA_INTERNAL_API
-        brandShortName.get()
-#else
-          brandShortName
-#endif
+          brandShortName.get()
       };
       nsAutoString dialogText;
       GetLocalizedString(NS_LITERAL_STRING("savePasswordText"),
                          dialogText,
                          PR_TRUE,
                          formatArgs,
                          1);
       nsAutoString dialogTitle, neverButtonText, rememberButtonText,
@@ -1240,21 +1216,21 @@ EmbedPasswordMgr::Notify(nsIContent* aFo
       GetLocalizedString(NS_LITERAL_STRING("savePasswordTitle"), dialogTitle);
       GetLocalizedString(NS_LITERAL_STRING("neverForSiteButtonText"),
                          neverButtonText);
       GetLocalizedString(NS_LITERAL_STRING("rememberButtonText"),
                          rememberButtonText);
       GetLocalizedString(NS_LITERAL_STRING("notNowButtonText"),
                          notNowButtonText);
       PRInt32 selection;
-      nsCOMPtr<nsIDOMWindow> domWindow (do_QueryInterface (aWindow));
+      nsCOMPtr<nsIDOMWindow> domWindow(do_QueryInterface(aWindow));
       GtkWidget *parentWidget = GetGtkWidgetForDOMWindow(domWindow);
       if (parentWidget)
-        gtk_signal_emit (GTK_OBJECT (GTK_MOZ_EMBED(parentWidget)->common),
-                         moz_embed_common_signals[COMMON_REMEMBER_LOGIN], &selection);
+        gtk_signal_emit(GTK_OBJECT(GTK_MOZ_EMBED(parentWidget)->common),
+                        moz_embed_common_signals[COMMON_REMEMBER_LOGIN], &selection);
       // FIXME These values (0,1,2,3,4) need constant variable.
       if (selection == GTK_MOZ_EMBED_LOGIN_REMEMBER_FOR_THIS_SITE ) {
         SignonDataEntry* entry = new SignonDataEntry();
         entry->userField.Assign(userFieldName);
         entry->passField.Assign(passFieldName);
         if (NS_FAILED(EncryptDataUCS2(userValue, entry->userValue)) ||
             NS_FAILED(EncryptDataUCS2(passValue, entry->passValue))) {
           delete entry;
@@ -1375,16 +1351,17 @@ EmbedPasswordMgr::Notify(nsIContent* aFo
                 return NS_OK;
               WritePasswords(mSignonFile);
             }
           }
           break;
   default:  // no passwords or something odd; be safe and just don't store anything
           break;
   }
+#endif // FIXED_BUG347731 || MOZ_ENABLE_LIBXUL
   return NS_OK;
 }
 
 // nsIDOMFocusListener implementation
 NS_IMETHODIMP
 EmbedPasswordMgr::Focus(nsIDOMEvent* aEvent)
 {
   return NS_OK;
@@ -1727,25 +1704,27 @@ EmbedPasswordMgr::FillPassword(nsIDOMEve
   FindPasswordEntryInternal(hashEnt->head, userValue, EmptyString(),
                             fieldName, &foundEntry);
   if (!foundEntry)
     return NS_OK;
   nsCOMPtr<nsIDOMHTMLFormElement> formEl;
   userField->GetForm(getter_AddRefs(formEl));
   if (!formEl)
     return NS_OK;
+#if defined(FIXED_BUG347731) || !defined(MOZ_ENABLE_LIBXUL)
   nsCOMPtr<nsIForm> form = do_QueryInterface(formEl);
   nsCOMPtr<nsISupports> foundNode;
   form->ResolveName(foundEntry->passField, getter_AddRefs(foundNode));
   nsCOMPtr<nsIDOMHTMLInputElement> passField = do_QueryInterface(foundNode);
   if (!passField)
     return NS_OK;
   nsAutoString passValue;
   if (NS_SUCCEEDED(DecryptData(foundEntry->passValue, passValue)))
     passField->SetValue(passValue);
+#endif
   return NS_OK;
 }
 
 void
 EmbedPasswordMgr::AttachToInput(nsIDOMHTMLInputElement* aElement)
 {
   nsCOMPtr<nsIDOMEventTarget> targ = do_QueryInterface(aElement);
   nsIDOMEventListener* listener = NS_STATIC_CAST(nsIDOMFocusListener*, this);
@@ -1786,17 +1765,17 @@ EmbedPasswordMgr::GetLocalizedString(con
     nsCOMPtr<nsIStringBundleService> bundleService = do_GetService(NS_STRINGBUNDLE_CONTRACTID);
     bundleService->CreateBundle(kPMPropertiesURL,
                                 &sPMBundle);
     if (!sPMBundle) {
       NS_ERROR("string bundle not present");
       return;
     }
   }
-  nsXPIDLString str;
+  nsString str;
   if (aIsFormatted)
     sPMBundle->FormatStringFromName(PromiseFlatString(key).get(),
                                     aFormatArgs, aFormatArgsLength,
                                     getter_Copies(str));
   else
     sPMBundle->GetStringFromName(PromiseFlatString(key).get(),
                                  getter_Copies(str));
   aResult.Assign(str);
@@ -2015,17 +1994,19 @@ NS_IMPL_ISUPPORTS1(EmbedSignonPrompt2, n
 
 NS_IMETHODIMP
 EmbedSignonPrompt2::PromptAuth(nsIChannel* aChannel,
                                PRUint32 aLevel,
                                nsIAuthInformation* aAuthInfo,
                                PRBool* aConfirm)
 {
   nsCAutoString key;
+#if defined(FIXED_BUG347731) || !defined(MOZ_ENABLE_LIBXUL)
   NS_GetAuthKey(aChannel, aAuthInfo, key);
+#endif
 
   nsAutoString checkMsg;
   PRBool checkValue = PR_FALSE;
   PRBool *checkPtr = nsnull;
   nsCOMPtr<nsIPasswordManagerInternal> mgrInternal;
 
   if (EmbedPasswordMgr::SingleSignonEnabled()) {
     EmbedPasswordMgr::GetLocalizedString(NS_LITERAL_STRING("rememberPassword"),
@@ -2039,17 +2020,19 @@ EmbedSignonPrompt2::PromptAuth(nsIChanne
     const nsString& emptyString = EmptyString();
     mgrInternal->FindPasswordEntry(key,
                                    emptyString,
                                    emptyString,
                                    outHost,
                                    outUser,
                                    outPassword);
 
+#if defined(FIXED_BUG347731) || !defined(MOZ_ENABLE_LIBXUL)
     NS_SetAuthInfo(aAuthInfo, outUser, outPassword);
+#endif
 
     if (!outUser.IsEmpty() || !outPassword.IsEmpty())
       checkValue = PR_TRUE;
   }
 
   mService->PromptAuth(mParent, aChannel, aLevel, aAuthInfo,
                        checkMsg.get(), checkPtr, aConfirm);
 
--- a/embedding/browser/gtk/src/EmbedPrivate.cpp
+++ b/embedding/browser/gtk/src/EmbedPrivate.cpp
@@ -38,16 +38,17 @@
  * ***** END LICENSE BLOCK ***** */
 
 #include "nsIDocShell.h"
 #include "nsIWebProgress.h"
 #include "nsIWidget.h"
 #include "nsCRT.h"
 #include "nsNetUtil.h"
 #include "nsIWebBrowserStream.h"
+#include "nsIHistoryEntry.h"
 #include "nsIWebBrowserFocus.h"
 #include "nsIDirectoryService.h"
 #include "nsAppDirectoryServiceDefs.h"
 
 // for do_GetInterface
 #include "nsIInterfaceRequestor.h"
 // for do_CreateInstance
 #include "nsIComponentManager.h"
@@ -59,16 +60,18 @@
 
 #include "nsXULAppAPI.h"
 
 // all of the crap that we need for event listeners
 // and when chrome windows finish loading
 #include "nsIDOMWindow.h"
 #include "nsPIDOMWindow.h"
 #include "nsIDOMWindowInternal.h"
+#include "nsIDOMAbstractView.h"
+#include "nsIDOMDocumentView.h"
 
 // For seting scrollbar visibilty
 #include "nsIDOMBarProp.h"
 
 // for the focus hacking we need to do
 #include "nsIFocusController.h"
 
 #include "nsIFormControl.h"
@@ -157,17 +160,17 @@ EmbedCommon::DeleteInstance()
     sEmbedCommon = nsnull;
 
     EmbedGlobalHistory::DeleteInstance();
 
   }
 }
 
 nsresult
-EmbedCommon::Init (void)
+EmbedCommon::Init(void)
 {
     mCommon = NULL;
     return NS_OK;
 }
 #endif
 
 PRUint32     EmbedPrivate::sWidgetCount = 0;
 char        *EmbedPrivate::sPath        = nsnull;
@@ -408,17 +411,17 @@ EmbedPrivate::EmbedPrivate(void)
   mIsChrome         = PR_FALSE;
   mChromeLoaded     = PR_FALSE;
   mLoadFinished     = PR_TRUE;
   mListenersAttached = PR_FALSE;
   mMozWindowWidget  = 0;
   mIsDestroyed      = PR_FALSE;
   mDoResizeEmbed    = PR_TRUE;
   mOpenBlock        = PR_FALSE;
-  mNeedFav          = PR_FALSE;
+  mNeedFav          = PR_TRUE;
 
   PushStartup();
   if (!sWindowList) {
     sWindowList = new nsVoidArray();
   }
   sWindowList->AppendElement(this);
 }
 
@@ -547,16 +550,18 @@ EmbedPrivate::Realize(PRBool *aAlreadyRe
   tmp_window = gdk_window_get_parent(tmp_window);
   // save the widget ID - it should be the mozarea of the window.
   gpointer data = nsnull;
   gdk_window_get_user_data(tmp_window, &data);
   mMozWindowWidget = NS_STATIC_CAST(GtkWidget *, data);
 
   // Apply the current chrome mask
   ApplyChromeMask();
+  // Initialize focus for window, help for WINDOWWATCHER Service
+  ChildFocusIn();
 
   return NS_OK;
 }
 
 void
 EmbedPrivate::Unrealize(void)
 {
   // reparent to our offscreen window
@@ -567,16 +572,20 @@ void
 EmbedPrivate::Show(void)
 {
   // Get the nsIWebBrowser object for our embedded window.
   nsCOMPtr<nsIWebBrowser> webBrowser;
   mWindow->GetWebBrowser(getter_AddRefs(webBrowser));
 
   // and set the visibility on the thing
   nsCOMPtr<nsIBaseWindow> baseWindow = do_QueryInterface(webBrowser);
+
+  // XXX hack around problem. probably widget/gtk2 window initialization.
+  baseWindow->SetVisibility(PR_FALSE);
+
   baseWindow->SetVisibility(PR_TRUE);
 }
 
 void
 EmbedPrivate::Hide(void)
 {
   // Get the nsIWebBrowser object for our embedded window.
   nsCOMPtr<nsIWebBrowser> webBrowser;
@@ -586,47 +595,42 @@ EmbedPrivate::Hide(void)
   nsCOMPtr<nsIBaseWindow> baseWindow = do_QueryInterface(webBrowser);
   baseWindow->SetVisibility(PR_FALSE);
 }
 
 #include "nsIDOMScreen.h"
 void
 EmbedPrivate::Resize(PRUint32 aWidth, PRUint32 aHeight)
 {
-  if (mDoResizeEmbed) {
-    mWindow->SetDimensions(nsIEmbeddingSiteWindow::DIM_FLAGS_POSITION |
-                           nsIEmbeddingSiteWindow::DIM_FLAGS_SIZE_INNER,
-                           0, 0, aWidth, aHeight);
-  } else {
 #ifdef MOZ_WIDGET_GTK2
-    PRInt32 X, Y, W, H;
-    mWindow->GetDimensions(nsIEmbeddingSiteWindow::DIM_FLAGS_POSITION, &X, &Y, &W, &H);
-    if (Y < 0) {
-      mWindow->SetDimensions(nsIEmbeddingSiteWindow::DIM_FLAGS_POSITION, 0, 0, nsnull, nsnull);
-      return;
-    }
+  PRInt32 sub   = 0;
+  PRInt32 diff  = 0;
+
+  if (mDoResizeEmbed){
     EmbedContextMenuInfo * ctx_menu = mEventListener->GetContextInfo();
     gint x, y, width, height, depth;
-    gdk_window_get_geometry(gtk_widget_get_parent_window(GTK_WIDGET(mOwningWidget)),
-                            &x,
-                            &y,
-                            &width,
-                            &height,
-                            &depth);
+    gdk_window_get_geometry(gtk_widget_get_parent_window(GTK_WIDGET(mOwningWidget)),&x,&y,&width,&height,&depth);
+
     if (ctx_menu) {
       if (height < ctx_menu->mFormRect.y + ctx_menu->mFormRect.height) {
-        PRInt32 sub = ctx_menu->mFormRect.y - height + ctx_menu->mFormRect.height;
-        PRInt32 diff = ctx_menu->mFormRect.y - sub;
-//        printf("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!height: %i, Form.y: %i, Form.Height: %i, sub: %i, diff: %i\n", height, ctx_menu->mFormRect.y, ctx_menu->mFormRect.height, sub, diff);
-        if (sub > 0 && diff >= 0)
-          mWindow->SetDimensions(nsIEmbeddingSiteWindow::DIM_FLAGS_POSITION, 0, -sub, nsnull, nsnull);
+        sub = ctx_menu->mFormRect.y - height + ctx_menu->mFormRect.height;
+        diff = height - aHeight;
       }
     }
+  }
 #endif
+  mWindow->SetDimensions(nsIEmbeddingSiteWindow::DIM_FLAGS_POSITION |
+                          nsIEmbeddingSiteWindow::DIM_FLAGS_SIZE_INNER,
+                          0, 0, aWidth, aHeight);
+
+#ifdef MOZ_WIDGET_GTK2
+  if (sub > 0 && diff >= 0){
+    SetScrollTop(sub + diff);
   }
+#endif
 }
 
 void
 EmbedPrivate::Destroy(void)
 {
   // This flag might have been set from
   // EmbedWindow::DestroyBrowserWindow() as well if someone used a
   // window.close() or something or some other script action to close
@@ -669,34 +673,30 @@ EmbedPrivate::Destroy(void)
   mNavigation = nsnull;
 
   // release session history
   mSessionHistory = nsnull;
 
   mOwningWidget = nsnull;
 
   mMozWindowWidget = 0;
-  mNeedFav = PR_FALSE;
+  mNeedFav = PR_TRUE;
 }
 
 void
 EmbedPrivate::SetURI(const char *aURI)
 {
 #ifdef MOZ_WIDGET_GTK
   // XXX: Even though NS_CopyNativeToUnicode is not designed for non-filenames,
   // we know that it will do "the right thing" on UNIX.
   NS_CopyNativeToUnicode(nsDependentCString(aURI), mURI);
 #endif
 
 #ifdef MOZ_WIDGET_GTK2
-#ifdef MOZILLA_INTERNAL_API
-  CopyUTF8toUTF16(aURI, mURI);
-#else
-  mURI.AssignLiteral(aURI);
-#endif
+  mURI.Assign(NS_ConvertUTF8toUTF16(aURI));
 #endif
 }
 
 void
 EmbedPrivate::LoadCurrentURI(void)
 {
   if (!mURI.IsEmpty()) {
     nsCOMPtr<nsPIDOMWindow> piWin;
@@ -854,18 +854,20 @@ EmbedPrivate::PopStartup(void)
   }
 }
 
 /* static */
 void EmbedPrivate::SetPath(const char *aPath)
 {
   if (sPath)
     free(sPath);
-  if (aPath)
+  if (aPath) {
     sPath = strdup(aPath);
+    setenv("MOZILLA_FIVE_HOME", sPath, 0);
+  }
   else
     sPath = nsnull;
 }
 
 /* static */
 void
 EmbedPrivate::SetCompPath(const char *aPath)
 {
@@ -1267,16 +1269,18 @@ EmbedPrivate::AttachListeners(void)
          eventListener,
          NS_GET_IID(nsIDOMMouseMotionListener));
   if (NS_FAILED(rv)) {
     NS_WARNING("Failed to add Mouse Motion listener\n");
     return;
   }
   rv = mEventReceiver->AddEventListener(NS_LITERAL_STRING("focus"), eventListener, PR_TRUE);
   rv = mEventReceiver->AddEventListener(NS_LITERAL_STRING("blur"), eventListener, PR_TRUE);
+  rv = mEventReceiver->AddEventListener(NS_LITERAL_STRING("DOMLinkAdded"), eventListener, PR_TRUE);
+  rv = mEventReceiver->AddEventListener(NS_LITERAL_STRING("load"), eventListener, PR_TRUE);
   if (NS_FAILED(rv)) {
     NS_WARNING("Failed to add Mouse Motion listener\n");
     return;
   }
   // ok, all set.
   mListenersAttached = PR_TRUE;
 }
 
@@ -1320,16 +1324,18 @@ EmbedPrivate::DetachListeners(void)
          eventListener,
          NS_GET_IID(nsIDOMMouseMotionListener));
   if (NS_FAILED(rv)) {
     NS_WARNING("Failed to remove Mouse Motion listener\n");
     return;
   }
   rv = mEventReceiver->RemoveEventListener(NS_LITERAL_STRING("focus"), eventListener, PR_TRUE);
   rv = mEventReceiver->RemoveEventListener(NS_LITERAL_STRING("blur"), eventListener, PR_TRUE);
+  rv = mEventReceiver->RemoveEventListener(NS_LITERAL_STRING("DOMLinkAdded"), eventListener, PR_TRUE);
+  rv = mEventReceiver->RemoveEventListener(NS_LITERAL_STRING("load"), eventListener, PR_TRUE);
   mListenersAttached = PR_FALSE;
 }
 
 nsresult
 EmbedPrivate::GetFocusController(nsIFocusController * *controller)
 {
   nsresult rv;
   if (!controller) {
@@ -1416,18 +1422,18 @@ EmbedPrivate::GetAtkObjectForCurrentDocu
 nsresult
 EmbedPrivate::RegisterAppComponents(void)
 {
   nsCOMPtr<nsIComponentRegistrar> cr;
   nsresult rv = NS_GetComponentRegistrar(getter_AddRefs(cr));
   NS_ENSURE_SUCCESS(rv, rv);
 
   nsCOMPtr<nsIComponentManager> cm;
-  rv = NS_GetComponentManager (getter_AddRefs (cm));
-  NS_ENSURE_SUCCESS (rv, rv);
+  rv = NS_GetComponentManager(getter_AddRefs(cm));
+  NS_ENSURE_SUCCESS(rv, rv);
 
   for (int i = 0; i < sNumAppComps; ++i) {
     nsCOMPtr<nsIGenericFactory> componentFactory;
     rv = NS_NewGenericFactory(getter_AddRefs(componentFactory),
                               &(sAppComps[i]));
     if (NS_FAILED(rv)) {
       NS_WARNING("Unable to create factory for component");
       continue;  // don't abort registering other components
@@ -1476,17 +1482,17 @@ PRBool
 EmbedPrivate::ClipBoardAction(GtkMozEmbedClipboard type)
 {
   nsresult rv = NS_OK;
   PRBool canDo = PR_TRUE;
   nsCOMPtr<nsIWebBrowser> webBrowser;
   rv = mWindow->GetWebBrowser(getter_AddRefs(webBrowser));
   if (NS_FAILED(rv))
     return PR_FALSE;
-  nsCOMPtr<nsIClipboardCommands> clipboard (do_GetInterface(webBrowser));
+  nsCOMPtr<nsIClipboardCommands> clipboard(do_GetInterface(webBrowser));
   if (!clipboard)
     return PR_FALSE;
   switch (type) {
     case GTK_MOZ_EMBED_SELECT_ALL:
     {
       rv = clipboard->SelectAll();
       break;
     }
@@ -1507,100 +1513,121 @@ EmbedPrivate::ClipBoardAction(GtkMozEmbe
     }
     case GTK_MOZ_EMBED_PASTE:
     {
       rv = clipboard->Paste();
       break;
     }
     case GTK_MOZ_EMBED_CAN_CUT:
     {
-      rv = clipboard->CanCutSelection (&canDo);
+      rv = clipboard->CanCutSelection(&canDo);
       break;
     }
     case GTK_MOZ_EMBED_CAN_PASTE:
     {
-      rv = clipboard->CanPaste (&canDo);
+      rv = clipboard->CanPaste(&canDo);
       break;
     }
     case GTK_MOZ_EMBED_CAN_COPY:
     {
-      rv = clipboard->CanCopySelection (&canDo);
+      rv = clipboard->CanCopySelection(&canDo);
       break;
     }
     default:
     break;
   }
   if (NS_FAILED(rv))
     return PR_FALSE;
   return canDo;
 }
 
 char*
-EmbedPrivate::GetEncoding ()
+EmbedPrivate::GetEncoding()
 {
   char *encoding;
   nsCOMPtr<nsIWebBrowser> webBrowser;
   mWindow->GetWebBrowser(getter_AddRefs(webBrowser));
-  nsCOMPtr<nsIDocCharset> docCharset = do_GetInterface (webBrowser);
-  docCharset->GetCharset (&encoding);
+  nsCOMPtr<nsIDocCharset> docCharset = do_GetInterface(webBrowser);
+  docCharset->GetCharset(&encoding);
   return encoding;
 }
 
 nsresult
-EmbedPrivate::SetEncoding (const char *encoding)
+EmbedPrivate::SetEncoding(const char *encoding)
 {
   nsCOMPtr<nsIWebBrowser> webBrowser;
   mWindow->GetWebBrowser(getter_AddRefs(webBrowser));
   nsCOMPtr<nsIContentViewer> contentViewer;
-  GetContentViewer (webBrowser, getter_AddRefs(contentViewer));
+  GetContentViewer(webBrowser, getter_AddRefs(contentViewer));
   NS_ENSURE_TRUE (contentViewer, NS_ERROR_FAILURE);
   nsCOMPtr<nsIMarkupDocumentViewer> mDocViewer = do_QueryInterface(contentViewer);
   NS_ENSURE_TRUE (mDocViewer, NS_ERROR_FAILURE);
-  nsAutoString mCharset;
-#ifdef MOZILLA_INTERNAL_API
-  mCharset.AssignWithConversion (encoding);
-#else
-  mCharset.AssignLiteral (encoding);
-#endif
-  return mDocViewer->SetForceCharacterSet(NS_LossyConvertUTF16toASCII(ToNewUnicode(mCharset)));
+  return mDocViewer->SetForceCharacterSet(nsDependentCString(encoding));
 }
 
 PRBool
 EmbedPrivate::FindText(const char *exp, PRBool  reverse,
                        PRBool  whole_word, PRBool  case_sensitive,
                        PRBool  restart)
 {
   PRUnichar *text;
   PRBool match;
   nsresult rv;
   nsCOMPtr<nsIWebBrowser> webBrowser;
   mWindow->GetWebBrowser(getter_AddRefs(webBrowser));
-  nsCOMPtr<nsIWebBrowserFind> finder(do_GetInterface (webBrowser));
+  nsCOMPtr<nsIWebBrowserFind> finder(do_GetInterface(webBrowser));
   g_return_val_if_fail(finder != NULL, FALSE);
-  text = LocaleToUnicode (exp);
-  finder->SetSearchString (text);
-  finder->SetFindBackwards (reverse);
-  finder->SetWrapFind(TRUE); //DoWrapFind
-  finder->SetEntireWord (whole_word);
+  text = ToNewUnicode(NS_ConvertUTF8toUTF16(exp));
+  finder->SetSearchString(text);
+  finder->SetFindBackwards(reverse);
+  finder->SetWrapFind(restart); //DoWrapFind
+  finder->SetEntireWord(whole_word);
   finder->SetSearchFrames(TRUE); //SearchInFrames
-  finder->SetMatchCase (case_sensitive);
-  rv = finder->FindNext (&match);
+  finder->SetMatchCase(case_sensitive);
+  rv = finder->FindNext(&match);
   NS_Free(text);
   if (NS_FAILED(rv))
     return FALSE;
 
   return match;
 }
 
+void
+EmbedPrivate::SetScrollTop(PRUint32 aTop)
+{
+  EmbedContextMenuInfo * ctx_menu = mEventListener->GetContextInfo();
+  if (ctx_menu->mEmbedCtxType & GTK_MOZ_EMBED_CTX_IFRAME){
+    if (ctx_menu) {
+      nsIDOMWindow *ctxDomWindows = ctx_menu->mCtxDomWindow;
+      if (ctxDomWindows)
+      {
+        nsCOMPtr<nsIDOMDocument> domDoc;
+        ctxDomWindows->GetDocument(getter_AddRefs(domDoc));
+        if (domDoc) {
+          ctx_menu->GetElementForScroll(domDoc);
+          if (ctx_menu->mNSHHTMLElementSc)
+            ctx_menu->mNSHHTMLElementSc->SetScrollTop(aTop);
+        }
+      }
+    }
+  } else {
+    nsCOMPtr<nsIDOMWindow> window;
+    nsCOMPtr<nsIWebBrowser> webBrowser;
+    mWindow->GetWebBrowser(getter_AddRefs(webBrowser));
+    webBrowser->GetContentDOMWindow(getter_AddRefs(window));
+    window->ScrollBy(0, aTop);
+  }
+} 
+
 nsresult
 EmbedPrivate::ScrollToSelectedNode(nsIDOMNode *aDOMNode)
 {
   nsresult rv = NS_ERROR_FAILURE;
   if (aDOMNode) {
-    nsCOMPtr <nsIDOMNSHTMLElement> nodeElement = do_QueryInterface(aDOMNode, &rv);
+    nsCOMPtr<nsIDOMNSHTMLElement> nodeElement = do_QueryInterface(aDOMNode, &rv);
     if (NS_SUCCEEDED(rv) && nodeElement) {
       nodeElement->ScrollIntoView(PR_FALSE);
     }
   }
   return rv;
 }
 
 nsresult
@@ -1618,90 +1645,71 @@ EmbedPrivate::InsertTextToNode(nsIDOMNod
     return NS_ERROR_FAILURE;
 
   nsString nodeName;
   targetNode->GetNodeName(nodeName);
   PRInt32 selectionStart = 0, selectionEnd = 0, textLength = 0;
   nsString buffer;
 
   if (ctx_menu->mCtxFormType == NS_FORM_TEXTAREA) {
-    nsCOMPtr <nsIDOMHTMLTextAreaElement> input;
+    nsCOMPtr<nsIDOMHTMLTextAreaElement> input;
     input = do_QueryInterface(targetNode, &rv);
     NS_ENSURE_SUCCESS(rv, rv);
     PRBool rdonly = PR_FALSE;
     input->GetReadOnly(&rdonly);
     if (rdonly)
       return NS_ERROR_FAILURE;
 
-    nsCOMPtr <nsIDOMNSHTMLTextAreaElement> nsinput;
+    nsCOMPtr<nsIDOMNSHTMLTextAreaElement> nsinput;
     nsinput = do_QueryInterface(targetNode, &rv);
     NS_ENSURE_SUCCESS(rv, rv);
     nsinput->GetTextLength(&textLength);
     if (textLength > 0) {
       NS_ENSURE_SUCCESS(rv, rv);
       rv = input->GetValue(buffer);
-      nsinput->GetSelectionStart (&selectionStart);
-      nsinput->GetSelectionEnd (&selectionEnd);
+      nsinput->GetSelectionStart(&selectionStart);
+      nsinput->GetSelectionEnd(&selectionEnd);
 
       if (selectionStart != selectionEnd)
         buffer.Cut(selectionStart, selectionEnd - selectionStart);
-#ifdef MOZILLA_INTERNAL_API
-      buffer.Insert(UTF8ToNewUnicode(nsDependentCString(string)), selectionStart);
-#else
-      nsString nsstr;
-      nsstr.AssignLiteral(string);
-      buffer.Insert(nsstr, selectionStart);
-#endif
+      buffer.Insert(NS_ConvertUTF8toUTF16(string), selectionStart);
     } else {
-#ifdef MOZILLA_INTERNAL_API
-      CopyUTF8toUTF16(string, buffer);
-#else
-      buffer.AssignLiteral(string);
-#endif
+      buffer.Assign(NS_ConvertUTF8toUTF16(string));
     }
 
     input->SetValue(buffer);
     int len = strlen(string);
     nsinput->SetSelectionRange(selectionStart + len, selectionStart + len);
   }
   else if (ctx_menu->mCtxFormType) {
-    nsCOMPtr <nsIDOMHTMLInputElement> input;
+    nsCOMPtr<nsIDOMHTMLInputElement> input;
     input = do_QueryInterface(targetNode, &rv);
     NS_ENSURE_SUCCESS(rv, rv);
     PRBool rdonly = PR_FALSE;
     input->GetReadOnly(&rdonly);
     if (rdonly)
       return NS_ERROR_FAILURE;
 
-    nsCOMPtr <nsIDOMNSHTMLInputElement> nsinput;
+    nsCOMPtr<nsIDOMNSHTMLInputElement> nsinput;
     nsinput = do_QueryInterface(targetNode, &rv);
     NS_ENSURE_SUCCESS(rv, rv);
     nsinput->GetTextLength(&textLength);
 
     if (textLength > 0) {
       NS_ENSURE_SUCCESS(rv, rv);
       rv = input->GetValue(buffer);
-      nsinput->GetSelectionStart (&selectionStart);
-      nsinput->GetSelectionEnd (&selectionEnd);
+      nsinput->GetSelectionStart(&selectionStart);
+      nsinput->GetSelectionEnd(&selectionEnd);
 
       if (selectionStart != selectionEnd) {
         buffer.Cut(selectionStart, selectionEnd - selectionStart);
       }
-#ifdef MOZILLA_INTERNAL_API
-      buffer.Insert(UTF8ToNewUnicode(nsDependentCString(string)), selectionStart);
-#else
-      nsString nsstr;
-      buffer.Insert(nsstr, selectionStart);
-#endif
+      buffer.Insert(NS_ConvertUTF8toUTF16(string), selectionStart);
     } else {
-#ifdef MOZILLA_INTERNAL_API
-      CopyUTF8toUTF16(string, buffer);
-#else
-      buffer.AssignLiteral(string);
-#endif
+      buffer.Assign(NS_ConvertUTF8toUTF16(string));
     }
 
     input->SetValue(buffer);
     int len = strlen(string);
     nsinput->SetSelectionRange(selectionStart + len, selectionStart + len);
   }
   else {
     nsIWebBrowser *retval = nsnull;
@@ -1720,84 +1728,54 @@ EmbedPrivate::InsertTextToNode(nsIDOMNod
     if (!theEditor) {
       return NS_ERROR_FAILURE;
     }
 
     nsCOMPtr<nsIHTMLEditor> htmlEditor;
     htmlEditor = do_QueryInterface(theEditor, &rv);
     if (!htmlEditor)
       return NS_ERROR_FAILURE;
-
-#ifdef MOZILLA_INTERNAL_API
-    CopyUTF8toUTF16(string, buffer);
-#else
-    buffer.AssignLiteral(string);
-#endif
+    buffer.Assign(NS_ConvertUTF8toUTF16(string));
     htmlEditor->InsertHTML(buffer);
   }
   return NS_OK;
 }
 
 nsresult
 EmbedPrivate::GetDOMWindowByNode(nsIDOMNode *aNode, nsIDOMWindow * *aDOMWindow)
 {
   nsresult rv;
-  nsCOMPtr <nsIDOMDocument> nodeDoc;
+  nsCOMPtr<nsIDOMDocument> nodeDoc;
   rv = aNode->GetOwnerDocument(getter_AddRefs(nodeDoc));
   NS_ENSURE_SUCCESS(rv, rv);
-
-  nsCOMPtr<nsIWebBrowser> webBrowser;
-  rv = mWindow->GetWebBrowser(getter_AddRefs(webBrowser));
+  nsCOMPtr<nsIDOMDocumentView> docView = do_QueryInterface(nodeDoc, &rv);
   NS_ENSURE_SUCCESS(rv, rv);
-
-  nsCOMPtr <nsIDOMWindow> mainWindow;
-  rv = webBrowser->GetContentDOMWindow(getter_AddRefs(mainWindow));
+  nsCOMPtr<nsIDOMAbstractView> absView;
   NS_ENSURE_SUCCESS(rv, rv);
-
-  nsCOMPtr<nsIDOMDocument> mainDoc;
-  rv = mainWindow->GetDocument (getter_AddRefs(mainDoc));
-  if (mainDoc == nodeDoc) {
-    *aDOMWindow = mainWindow;
-    NS_IF_ADDREF(*aDOMWindow);
-    return NS_OK;
-  }
-
-  nsCOMPtr <nsIDOMWindowCollection> frames;
-  rv = mainWindow->GetFrames(getter_AddRefs (frames));
+  rv = docView->GetDefaultView(getter_AddRefs(absView));
   NS_ENSURE_SUCCESS(rv, rv);
-  PRUint32 frameCount = 0;
-  rv = frames->GetLength (&frameCount);
-  nsCOMPtr <nsIDOMWindow> curWindow;
-  for (unsigned int i= 0; i < frameCount; i++) {
-    rv = frames->Item(i, getter_AddRefs (curWindow));
-    if (!curWindow)
-      continue;
-    nsCOMPtr <nsIDOMDocument> currentDoc;
-    curWindow->GetDocument (getter_AddRefs(currentDoc));
-    if (currentDoc == nodeDoc) {
-      *aDOMWindow = curWindow;
-      NS_IF_ADDREF(*aDOMWindow);
-      break;
-    }
-  }
+  nsCOMPtr<nsIDOMWindow> window = do_QueryInterface(absView, &rv);
+  NS_ENSURE_SUCCESS(rv, rv);
+  *aDOMWindow = window;
+  NS_IF_ADDREF(*aDOMWindow);
   return rv;
 }
 
 nsresult
-EmbedPrivate::GetZoom (PRInt32 *aZoomLevel, nsISupports *aContext)
+EmbedPrivate::GetZoom(PRInt32 *aZoomLevel, nsISupports *aContext)
 {
 
   NS_ENSURE_ARG_POINTER(aZoomLevel);
 
   nsresult rv;
   *aZoomLevel = 100;
 
-  nsCOMPtr <nsIDOMWindow> DOMWindow;
+  nsCOMPtr<nsIDOMWindow> DOMWindow;
   if (aContext) {
-    nsCOMPtr <nsIDOMNode> node = do_QueryInterface(aContext, &rv);
+    nsCOMPtr<nsIDOMNode> node = do_QueryInterface(aContext, &rv);
     NS_ENSURE_SUCCESS(rv, rv);
 
     rv = GetDOMWindowByNode(node, getter_AddRefs(DOMWindow));
   } else {
     nsCOMPtr<nsIWebBrowser> webBrowser;
     rv = mWindow->GetWebBrowser(getter_AddRefs(webBrowser));
     NS_ENSURE_SUCCESS(rv, rv);
 
@@ -1805,27 +1783,27 @@ EmbedPrivate::GetZoom (PRInt32 *aZoomLev
     NS_ENSURE_SUCCESS(rv, rv);
   }
 
   float zoomLevelFloat;
   if (DOMWindow)
     rv = DOMWindow->GetTextZoom(&zoomLevelFloat);
   NS_ENSURE_SUCCESS(rv, rv);
 
-  *aZoomLevel = (int)round (zoomLevelFloat * 100.);
+  *aZoomLevel = (int)round(zoomLevelFloat * 100.);
   return rv;
 }
 nsresult
-EmbedPrivate::SetZoom (PRInt32 aZoomLevel, nsISupports *aContext)
+EmbedPrivate::SetZoom(PRInt32 aZoomLevel, nsISupports *aContext)
 {
   nsresult rv;
-  nsCOMPtr <nsIDOMWindow> DOMWindow;
+  nsCOMPtr<nsIDOMWindow> DOMWindow;
 
   if (aContext) {
-    nsCOMPtr <nsIDOMNode> node = do_QueryInterface(aContext, &rv);
+    nsCOMPtr<nsIDOMNode> node = do_QueryInterface(aContext, &rv);
     NS_ENSURE_SUCCESS(rv, rv);
 
     rv = GetDOMWindowByNode(node, getter_AddRefs(DOMWindow));
   } else {
     nsCOMPtr<nsIWebBrowser> webBrowser;
     rv = mWindow->GetWebBrowser(getter_AddRefs(webBrowser));
     NS_ENSURE_SUCCESS(rv, rv);
 
@@ -1846,34 +1824,34 @@ nsresult
 EmbedPrivate::HasFrames  (PRUint32 *numberOfFrames)
 {
   // setting default value.
   *numberOfFrames = 0;
   nsCOMPtr<nsIWebBrowser> webBrowser;
   nsresult rv = mWindow->GetWebBrowser(getter_AddRefs(webBrowser));
   if (NS_FAILED(rv)) return NS_ERROR_FAILURE;
   // get main dom window
-  nsCOMPtr <nsIDOMWindow> DOMWindow;
+  nsCOMPtr<nsIDOMWindow> DOMWindow;
   rv = webBrowser->GetContentDOMWindow(getter_AddRefs(DOMWindow));
   if (NS_FAILED(rv)) return NS_ERROR_FAILURE;
   // get frames.
-  nsCOMPtr <nsIDOMWindowCollection> frameCollection;
-  rv = DOMWindow->GetFrames (getter_AddRefs (frameCollection));
+  nsCOMPtr<nsIDOMWindowCollection> frameCollection;
+  rv = DOMWindow->GetFrames(getter_AddRefs(frameCollection));
   if (NS_FAILED(rv)) return NS_ERROR_FAILURE;
   // comparing frames' zoom level
-  rv = frameCollection->GetLength (numberOfFrames);
+  rv = frameCollection->GetLength(numberOfFrames);
   return rv;
 }
 
 nsresult
-EmbedPrivate::GetMIMEInfo (const char **aMime, nsIDOMNode *aDOMNode)
+EmbedPrivate::GetMIMEInfo(const char **aMime, nsIDOMNode *aDOMNode)
 {
   NS_ENSURE_ARG_POINTER(aMime);
   nsresult rv;
-#ifdef MOZ_ENABLE_GTK2
+#ifdef MOZ_WIDGET_GTK2
   if (aDOMNode && mEventListener) {
     EmbedContextMenuInfo * ctx = mEventListener->GetContextInfo();
     if (!ctx)
       return NS_ERROR_FAILURE;
     nsCOMPtr<imgIRequest> request;
     rv = ctx->GetImageRequest(getter_AddRefs(request), aDOMNode);
     if (request)
       rv = request->GetMimeType((char**)aMime);
@@ -1883,17 +1861,17 @@ EmbedPrivate::GetMIMEInfo (const char **
 
   nsCOMPtr<nsIWebBrowser> webBrowser;
   rv = mWindow->GetWebBrowser(getter_AddRefs(webBrowser));
 
   nsCOMPtr<nsIDOMWindow> DOMWindow;
   rv = webBrowser->GetContentDOMWindow(getter_AddRefs(DOMWindow));
 
   nsCOMPtr<nsIDOMDocument> doc;
-  rv = DOMWindow->GetDocument (getter_AddRefs(doc));
+  rv = DOMWindow->GetDocument(getter_AddRefs(doc));
 
   nsCOMPtr<nsIDOMNSDocument> nsDoc = do_QueryInterface(doc);
 
   nsString nsmime;
   if (nsDoc)
     rv = nsDoc->GetContentType(nsmime);
   if (!NS_FAILED(rv) && !nsmime.IsEmpty())
     *aMime = g_strdup((char*)NS_LossyConvertUTF16toASCII(nsmime).get());
@@ -1931,8 +1909,75 @@ EmbedPrivate::GetCacheEntry(const char *
                                nsICache::ACCESS_READ,
                                PR_FALSE,
                                aDescriptor);
 
   if (rv != NS_ERROR_CACHE_KEY_NOT_FOUND)
     NS_WARNING("OpenCacheEntry(ACCESS_READ) returned error for non-existent entry\n");
   return rv;
 }
+
+nsresult
+EmbedPrivate::GetSHistoryList(GtkMozHistoryItem **GtkHI,
+                              GtkMozEmbedSessionHistory type, gint *count)
+{
+   if (!mSessionHistory)
+     return NS_ERROR_FAILURE;
+
+   PRInt32 curIndex, totalCount, navIndex=0, maxItems=0;
+
+   //Get the current index at session History
+   mSessionHistory->GetIndex(&curIndex);
+   //Gets the number of toplevel documents available in session history.
+   mSessionHistory->GetCount(&totalCount);
+
+   if (type == GTK_MOZ_EMBED_BACK_SHISTORY) {
+     navIndex =  curIndex - 1;
+     maxItems = curIndex;
+   } else if (type == GTK_MOZ_EMBED_FORWARD_SHISTORY) {
+     navIndex = curIndex + 1;
+     maxItems = totalCount - navIndex;
+   }
+
+   if (maxItems <= 0)
+     return NS_ERROR_FAILURE;
+
+   *GtkHI = g_new0(GtkMozHistoryItem, maxItems);
+   GtkMozHistoryItem * item = (GtkMozHistoryItem *)*GtkHI;
+
+   nsresult rv;
+   for (PRInt32 numItems = 0; numItems < maxItems; numItems++) {
+     // Get the HistoryEntry at a given index.
+     nsCOMPtr<nsIHistoryEntry> curEntry;
+     rv = mSessionHistory->GetEntryAtIndex((navIndex), PR_FALSE,
+         getter_AddRefs(curEntry));
+     if (NS_FAILED(rv) || (!curEntry))
+       continue;
+
+     // Get the URI of the HistoryEntry
+     nsCOMPtr<nsIURI> uri;
+     rv = curEntry->GetURI(getter_AddRefs(uri));
+     if (NS_FAILED(rv) || (!uri))
+       continue;
+
+     nsCString uriString;
+     rv = uri->GetSpec(uriString);
+     if (NS_FAILED(rv) || uriString.IsEmpty())
+       continue;
+
+     // Get the title of the HistoryEntry
+     PRUnichar* title;
+     rv = curEntry->GetTitle (&title);
+     if (NS_FAILED(rv) || (!title))
+       continue;
+
+     item[numItems].url = NS_strdup(uriString.get());
+     item[numItems].title = NS_strdup(NS_ConvertUTF16toUTF8(title).get());
+     item[numItems].accessed = 0;
+
+     if (type == GTK_MOZ_EMBED_BACK_SHISTORY)
+       navIndex--;
+     else if (type == GTK_MOZ_EMBED_FORWARD_SHISTORY)
+       navIndex++;
+   }
+   *count = maxItems;
+   return NS_OK;
+}
--- a/embedding/browser/gtk/src/EmbedPrivate.h
+++ b/embedding/browser/gtk/src/EmbedPrivate.h
@@ -40,16 +40,18 @@
 #ifndef __EmbedPrivate_h
 #define __EmbedPrivate_h
 
 #include "nsCOMPtr.h"
 #ifdef MOZILLA_INTERNAL_API
 #include "nsString.h"
 #else
 #include "nsStringAPI.h"
+#include "nsComponentManagerUtils.h"
+#include "nsServiceManagerUtils.h"
 #endif
 #include "nsIWebNavigation.h"
 #include "nsISHistory.h"
 // for our one function that gets the EmbedPrivate via the chrome
 // object.
 #include "nsIWebBrowserChrome.h"
 #include "nsIAppShell.h"
 #include "nsIDOMEventReceiver.h"
@@ -82,17 +84,17 @@ class nsIDirectoryServiceProvider;
 
 class EmbedCommon {
  public:
   EmbedCommon() {
   };
   ~EmbedCommon() { };
   static EmbedCommon* GetInstance();
   static void DeleteInstance();
-  nsresult    Init (void);
+  nsresult    Init(void);
   GtkObject   *mCommon;
   static GtkMozEmbed* GetAnyLiveWidget();
 };
 class EmbedPrivate {
 
  public:
 
   EmbedPrivate();
@@ -153,29 +155,33 @@ class EmbedPrivate {
   void        ChildFocusIn (void);
   void        ChildFocusOut(void);
   PRBool      ClipBoardAction(GtkMozEmbedClipboard type);
   char*       GetEncoding ();
   nsresult    SetEncoding (const char *encoding);
   PRBool      FindText(const char *exp, PRBool  reverse,
                        PRBool  whole_word, PRBool  case_sensitive,
                        PRBool  restart);
+  void        SetScrollTop(PRUint32 aTop);
   nsresult    ScrollToSelectedNode(nsIDOMNode *aDOMNode);
   nsresult    InsertTextToNode(nsIDOMNode *aDOMNode, const char *string);
   nsresult    GetFocusController(nsIFocusController **controller);
   nsresult    GetDOMWindowByNode(nsIDOMNode *aNode, nsIDOMWindow * *aDOMWindow);
-  nsresult    GetZoom (PRInt32 *aZoomLevel, nsISupports *aContext = nsnull);
-  nsresult    SetZoom (PRInt32 aZoomLevel, nsISupports *aContext = nsnull);
-  nsresult    HasFrames  (PRUint32 *numberOfFrames);
-  nsresult    GetMIMEInfo (const char **aMime, nsIDOMNode *aDOMNode = nsnull);
-  nsresult    GetCacheEntry (const char *aStorage,
-                             const char *aKeyName,
-                             PRUint32 aAccess,
-                             PRBool aIsBlocking,
-                             nsICacheEntryDescriptor **aDescriptor);
+  nsresult    GetZoom(PRInt32 *aZoomLevel, nsISupports *aContext = nsnull);
+  nsresult    SetZoom(PRInt32 aZoomLevel, nsISupports *aContext = nsnull);
+  nsresult    HasFrames(PRUint32 *numberOfFrames);
+  nsresult    GetMIMEInfo(const char **aMime, nsIDOMNode *aDOMNode = nsnull);
+  nsresult    GetCacheEntry(const char *aStorage,
+                            const char *aKeyName,
+                            PRUint32 aAccess,
+                            PRBool aIsBlocking,
+                            nsICacheEntryDescriptor **aDescriptor);
+  nsresult    GetSHistoryList(GtkMozHistoryItem **GtkHI,
+                               GtkMozEmbedSessionHistory type, gint *count);
+
 
 #ifdef MOZ_ACCESSIBILITY_ATK
   void *GetAtkObjectForCurrentDocument();
 #endif
 
   GtkMozEmbed                   *mOwningWidget;
 
   // all of the objects that we own
--- a/embedding/browser/gtk/src/EmbedProgress.cpp
+++ b/embedding/browser/gtk/src/EmbedProgress.cpp
@@ -121,59 +121,45 @@ EmbedProgress::OnStateChange(nsIWebProgr
     if (mOwner->mLoadFinished) {
       mOwner->mLoadFinished = PR_FALSE;
       mStopLevel = 0;
       gtk_signal_emit(GTK_OBJECT(mOwner->mOwningWidget),
                       moz_embed_signals[NET_START]);
     }
   }
   // get the uri for this request
-  nsString tmpString;
-#ifdef MOZILLA_INTERNAL_API
-  nsXPIDLCString uriString;
-  RequestToURIString(aRequest, getter_Copies(uriString));
-  CopyUTF8toUTF16(uriString, tmpString);
-#else
-  char *uriString = NULL;
-  RequestToURIString(aRequest, &uriString);
-  tmpString.AssignLiteral(uriString);
-#endif
-
-  PRBool succeeded = PR_TRUE;
-  HandleHTTPStatus(aRequest, (const char*)uriString, succeeded);
-  if (!succeeded) {
-    mOwner->mNeedFav = PR_FALSE;
-  }
+  nsCString tmpString;
+  RequestToURIString(aRequest, tmpString);
 
   // FIXME: workaround for broken progress values.
   if (mOwner->mOwningWidget) {
     if (aStateFlags & GTK_MOZ_EMBED_FLAG_IS_REQUEST) {
       if (aStateFlags & GTK_MOZ_EMBED_FLAG_START)
         mOwner->mOwningWidget->total_number_of_requests ++;
       else if (aStateFlags & GTK_MOZ_EMBED_FLAG_STOP)
         mOwner->mOwningWidget->current_number_of_requests++;
     }
 
     gtk_signal_emit(GTK_OBJECT(mOwner->mOwningWidget),
                     moz_embed_signals[PROGRESS_ALL],
-                    (const gchar *) uriString,
+                    (const gchar *) tmpString.get(),
                     mOwner->mOwningWidget->current_number_of_requests,
                     mOwner->mOwningWidget->total_number_of_requests);
   }
   // is it the same as the current URI?
-  if (mOwner->mURI.Equals(tmpString)) {
+  if (mOwner->mURI.Equals(NS_ConvertUTF8toUTF16(tmpString))) {
     // for people who know what they are doing
     gtk_signal_emit(GTK_OBJECT(mOwner->mOwningWidget),
                     moz_embed_signals[NET_STATE],
                     aStateFlags, aStatus);
   }
 
   gtk_signal_emit(GTK_OBJECT(mOwner->mOwningWidget),
                   moz_embed_signals[NET_STATE_ALL],
-                  (const gchar *)uriString,
+                  (const gchar *)tmpString.get(),
                   (gint)aStateFlags, (gint)aStatus);
 
   // and for stop, too
   if (aStateFlags & GTK_MOZ_EMBED_FLAG_STOP) {
     if (aStateFlags & GTK_MOZ_EMBED_FLAG_IS_REQUEST)
       mStopLevel = 1;
     if (aStateFlags & GTK_MOZ_EMBED_FLAG_IS_DOCUMENT)
        mStopLevel = mStopLevel == 1 ? 2 : 0;
@@ -203,29 +189,21 @@ EmbedProgress::OnStateChange(nsIWebProgr
 NS_IMETHODIMP
 EmbedProgress::OnProgressChange(nsIWebProgress *aWebProgress,
                                 nsIRequest     *aRequest,
                                 PRInt32         aCurSelfProgress,
                                 PRInt32         aMaxSelfProgress,
                                 PRInt32         aCurTotalProgress,
                                 PRInt32         aMaxTotalProgress)
 {
-  nsString tmpString;
-#ifdef MOZILLA_INTERNAL_API
-  nsXPIDLCString uriString;
-  RequestToURIString(aRequest, getter_Copies(uriString));
-  CopyUTF8toUTF16(uriString, tmpString);
-#else
-  gchar *uriString = NULL;
-  RequestToURIString(aRequest, &uriString);
-  tmpString.AssignLiteral(uriString);
-#endif
+  nsCString tmpString;
+  RequestToURIString(aRequest, tmpString);
 
   // is it the same as the current uri?
-  if (mOwner->mURI.Equals(tmpString)) {
+  if (mOwner->mURI.Equals(NS_ConvertUTF8toUTF16(tmpString))) {
     gtk_signal_emit(GTK_OBJECT(mOwner->mOwningWidget),
                     moz_embed_signals[PROGRESS],
                     aCurTotalProgress, aMaxTotalProgress);
   }
 
   return NS_OK;
 }
 
@@ -260,21 +238,16 @@ EmbedProgress::OnLocationChange(nsIWebPr
   if (!isSubFrameLoad) {
     mOwner->SetURI(newURI.get());
     mOwner->mPrePath.Assign(prePath.get());
     gtk_signal_emit(GTK_OBJECT(mOwner->mOwningWidget),
                     moz_embed_signals[LOCATION]);
   }
   mOwner->mNeedFav = PR_TRUE;
 
-  PRBool succeeded = PR_TRUE;
-  HandleHTTPStatus(aRequest, newURI.get(), succeeded);
-  if (!succeeded)
-    mOwner->mNeedFav = PR_FALSE;
-
   return NS_OK;
 }
 
 NS_IMETHODIMP
 EmbedProgress::OnStatusChange(nsIWebProgress  *aWebProgress,
                               nsIRequest      *aRequest,
                               nsresult         aStatus,
                               const PRUnichar *aMessage)
@@ -302,33 +275,30 @@ EmbedProgress::OnSecurityChange(nsIWebPr
                   moz_embed_signals[SECURITY_CHANGE],
                   NS_STATIC_CAST(void *, aRequest),
                   aState);
   return NS_OK;
 }
 
 /* static */
 void
-EmbedProgress::RequestToURIString(nsIRequest *aRequest, gchar **aString)
+EmbedProgress::RequestToURIString(nsIRequest *aRequest, nsCString& aString)
 {
   // is it a channel
   nsCOMPtr<nsIChannel> channel;
   channel = do_QueryInterface(aRequest);
   if (!channel)
     return;
 
   nsCOMPtr<nsIURI> uri;
   channel->GetURI(getter_AddRefs(uri));
   if (!uri)
     return;
 
-  nsCAutoString uriString;
-  uri->GetSpec(uriString);
-
-  *aString = g_strdup(uriString.get());
+  uri->GetSpec(aString);
 }
 
 nsresult
 EmbedProgress::HandleHTTPStatus(nsIRequest *aRequest, const char *aUri, PRBool &aSucceeded)
 {
   nsresult rv;
   nsCOMPtr<nsIHttpChannel> httpChannel(do_QueryInterface(aRequest, &rv));
   aSucceeded = PR_FALSE;
--- a/embedding/browser/gtk/src/EmbedProgress.h
+++ b/embedding/browser/gtk/src/EmbedProgress.h
@@ -54,16 +54,16 @@ class EmbedProgress : public nsIWebProgr
   nsresult Init(EmbedPrivate *aOwner);
 
   NS_DECL_ISUPPORTS
 
   NS_DECL_NSIWEBPROGRESSLISTENER
 
  private:
 
-  static void RequestToURIString (nsIRequest *aRequest, char **aString);
-  nsresult HandleHTTPStatus (nsIRequest *aRequest, const char *aUri, PRBool &aSucceeded);
+  static void RequestToURIString(nsIRequest *aRequest, nsCString& aString);
+  nsresult HandleHTTPStatus(nsIRequest *aRequest, const char *aUri, PRBool &aSucceeded);
 
   EmbedPrivate *mOwner;
   PRBool mStopLevel;
 };
 
 #endif /* __EmbedProgress_h */
--- a/embedding/browser/gtk/src/EmbedPrompter.cpp
+++ b/embedding/browser/gtk/src/EmbedPrompter.cpp
@@ -33,17 +33,24 @@
  * decision by deleting the provisions above and replace them with the notice
  * and other provisions required by the GPL or the LGPL. If you do not delete
  * the provisions above, a recipient may use your version of this file under
  * the terms of any one of the MPL, the GPL or the LGPL.
  *
  * ***** END LICENSE BLOCK ***** */
 
 #include "EmbedPrompter.h"
-#include "nsReadableUtils.h"
+
+#define ALLOC_NOT_CHECKED(newed) PR_BEGIN_MACRO               \
+  /* This might not crash, but the code probably isn't really \
+   * designed to handle it, perhaps the code should be fixed? \
+   */                                                         \
+  if (!newed) {                                               \
+  }                                                           \
+  PR_END_MACRO
 
 enum {
   INCLUDE_USERNAME = 1 << 0,
   INCLUDE_PASSWORD = 1 << 1,
   INCLUDE_CHECKBOX = 1 << 2,
   INCLUDE_CANCEL   = 1 << 3
 };
 
@@ -104,17 +111,17 @@ EmbedPrompter::Create(PromptType aType, 
   mWindow = gtk_dialog_new_with_buttons(
     mTitle.get(),
     aParentWindow,
     (GtkDialogFlags)0,
     NULL);
   // only add the dialog to the window group if the parent already has a window group,
   // so as not to break app's expectations about modal dialogs.
   if (aParentWindow && aParentWindow->group) {
-    gtk_window_group_add_window (aParentWindow->group, GTK_WINDOW (mWindow));
+    gtk_window_group_add_window(aParentWindow->group, GTK_WINDOW(mWindow));
   }
 
   // gtk will resize this for us as necessary
   gtk_window_set_default_size(GTK_WINDOW(mWindow), 100, 50);
 
   // this HBox will contain the icon, and a vbox which contains the
   // dialog text and other widgets.
   GtkWidget* dialogHBox = gtk_hbox_new(FALSE, 12);
@@ -275,75 +282,76 @@ EmbedPrompter::Create(PromptType aType, 
     FALSE,
     0);
   return NS_OK;
 }
 
 void
 EmbedPrompter::SetTitle(const PRUnichar *aTitle)
 {
-  CopyUTF16toUTF8(aTitle, mTitle);
+  mTitle.Assign(NS_ConvertUTF16toUTF8(aTitle));
 }
 
 void
 EmbedPrompter::SetTextValue(const PRUnichar *aTextValue)
 {
-  CopyUTF16toUTF8(aTextValue, mTextValue);
+  mTextValue.Assign(NS_ConvertUTF16toUTF8(aTextValue));
 }
 
 void
 EmbedPrompter::SetCheckMessage(const PRUnichar *aMessage)
 {
-  CopyUTF16toUTF8(aMessage, mCheckMessage);
+  mCheckMessage.Assign(NS_ConvertUTF16toUTF8(aMessage));
 }
 
 void
 EmbedPrompter::SetMessageText(const PRUnichar *aMessageText)
 {
-  CopyUTF16toUTF8(aMessageText, mMessageText);
+  mMessageText.Assign(NS_ConvertUTF16toUTF8(aMessageText));
 }
 
 void
 EmbedPrompter::SetUser(const PRUnichar *aUser)
 {
-  CopyUTF16toUTF8(aUser, mUser);
+  mUser.Assign(NS_ConvertUTF16toUTF8(aUser));
 }
 
 void
 EmbedPrompter::SetPassword(const PRUnichar *aPass)
 {
-  CopyUTF16toUTF8(aPass, mPass);
+  mPass.Assign(NS_ConvertUTF16toUTF8(aPass));
 }
 
 void
 EmbedPrompter::SetCheckValue(const PRBool aValue)
 {
   mCheckValue = aValue;
 }
 
 void
 EmbedPrompter::SetItems(const PRUnichar** aItemArray, PRUint32 aCount)
 {
   if (mItemList)
     delete[] mItemList;
 
   mItemCount = aCount;
   mItemList = new nsCString[aCount];
+  ALLOC_NOT_CHECKED(mItemList);
   for (PRUint32 i = 0; i < aCount; ++i)
-    CopyUTF16toUTF8(aItemArray[i], mItemList[i]);
+    mItemList[i].Assign(NS_ConvertUTF16toUTF8(aItemArray[i]));
 }
 
 void
 EmbedPrompter::SetButtons(const PRUnichar* aButton0Label,
               const PRUnichar* aButton1Label,
               const PRUnichar* aButton2Label)
 {
-  CopyUTF16toUTF8(aButton0Label, mButtonLabels[0]);
-  CopyUTF16toUTF8(aButton1Label, mButtonLabels[1]);
-  CopyUTF16toUTF8(aButton2Label, mButtonLabels[2]);
+  mButtonLabels[0].Assign(NS_ConvertUTF16toUTF8(aButton0Label));
+  mButtonLabels[1].Assign(NS_ConvertUTF16toUTF8(aButton1Label));
+  mButtonLabels[2].Assign(NS_ConvertUTF16toUTF8(aButton2Label));
 }
 
 void
 EmbedPrompter::GetCheckValue(PRBool *aValue)
 {
   *aValue = mCheckValue;
 }
 
@@ -351,29 +359,29 @@ void
 EmbedPrompter::GetConfirmValue(PRBool *aConfirmValue)
 {
   *aConfirmValue = mConfirmResult;
 }
 
 void
 EmbedPrompter::GetTextValue(PRUnichar **aTextValue)
 {
-  *aTextValue = UTF8ToNewUnicode(mTextValue);
+  *aTextValue = ToNewUnicode(NS_ConvertUTF8toUTF16(mTextValue));
 }
 
 void
 EmbedPrompter::GetUser(PRUnichar **aUser)
 {
-  *aUser = UTF8ToNewUnicode(mUser);
+  *aUser = ToNewUnicode(NS_ConvertUTF8toUTF16(mUser));
 }
 
 void
 EmbedPrompter::GetPassword(PRUnichar **aPass)
 {
-  *aPass = UTF8ToNewUnicode(mPass);
+  *aPass = ToNewUnicode(NS_ConvertUTF8toUTF16(mPass));
 }
 
 void
 EmbedPrompter::GetSelectedItem(PRInt32 *aIndex)
 {
   *aIndex = mSelectedItem;
 }
 
--- a/embedding/browser/gtk/src/EmbedPrompter.h
+++ b/embedding/browser/gtk/src/EmbedPrompter.h
@@ -35,16 +35,17 @@
  * 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 ***** */
 
 #ifdef MOZILLA_INTERNAL_API
 #include "nsString.h"
+#include "nsReadableUtils.h"
 #else
 #include "nsStringAPI.h"
 #endif
 #include <gtk/gtk.h>
 
 #include <stdlib.h>
 #define EMBED_MAX_BUTTONS 3
 
@@ -64,17 +65,17 @@ public:
         TYPE_PROMPT_USER_PASS,
         TYPE_PROMPT_PASS,
         TYPE_SELECT,
         TYPE_UNIVERSAL
     };
 
     nsresult Create(PromptType aType, GtkWindow* aParentWindow);
     void     SetTitle(const PRUnichar *aTitle);
-    void     SetTextValue (const PRUnichar *aTextValue);
+    void     SetTextValue(const PRUnichar *aTextValue);
     void     SetCheckMessage(const PRUnichar *aCheckMessage);
     void     SetCheckValue(const PRBool aValue);
     void     SetMessageText(const PRUnichar *aMessageText);
     void     SetUser(const PRUnichar *aUser);
     void     SetPassword(const PRUnichar *aPass);
     void     SetButtons(const PRUnichar* aButton0Label,
                         const PRUnichar* aButton1Label,
                         const PRUnichar* aButton2Label);
--- a/embedding/browser/gtk/src/EmbedWindow.cpp
+++ b/embedding/browser/gtk/src/EmbedWindow.cpp
@@ -349,17 +349,17 @@ EmbedWindow::SetTitle(const PRUnichar *a
   gtk_signal_emit(GTK_OBJECT(mOwner->mOwningWidget),
       moz_embed_signals[TITLE]);
   return NS_OK;
 }
 
 NS_IMETHODIMP
 EmbedWindow::GetSiteWindow(void **aSiteWindow)
 {
-  GtkWidget *ownerAsWidget (GTK_WIDGET(mOwner->mOwningWidget));
+  GtkWidget *ownerAsWidget(GTK_WIDGET(mOwner->mOwningWidget));
   *aSiteWindow = NS_STATIC_CAST(void *, ownerAsWidget);
   return NS_OK;
 }
 
 NS_IMETHODIMP
 EmbedWindow::GetVisibility(PRBool *aVisibility)
 {
   *aVisibility = mVisibility ||
@@ -402,17 +402,17 @@ tooltips_paint_window(GtkWidget *window)
 
   return FALSE;
 }
 
 NS_IMETHODIMP
 EmbedWindow::OnShowTooltip(PRInt32 aXCoords, PRInt32 aYCoords,
          const PRUnichar *aTipText)
 {
-  nsAutoString tipText (aTipText);
+  nsAutoString tipText(aTipText);
 
 #ifdef MOZ_WIDGET_GTK
   const char* tipString = ToNewCString(tipText);
 #endif
 
 #ifdef MOZ_WIDGET_GTK2
   const char* tipString = ToNewUTF8String(tipText);
 #endif
--- a/embedding/browser/gtk/src/GtkPromptService.cpp
+++ b/embedding/browser/gtk/src/GtkPromptService.cpp
@@ -80,22 +80,20 @@ NS_IMPL_ISUPPORTS2(GtkPromptService, nsI
 NS_IMETHODIMP
 GtkPromptService::Alert(
   nsIDOMWindow* aParent,
   const PRUnichar* aDialogTitle,
   const PRUnichar* aDialogText)
 {
   GtkWidget* parentWidget = GetGtkWidgetForDOMWindow(aParent);
   if (parentWidget && gtk_signal_handler_pending(parentWidget, moz_embed_signals[ALERT], TRUE)) {
-    nsCString dialogTitle, dialogText;
-    CopyUTF16toUTF8(aDialogTitle, dialogTitle);
-    CopyUTF16toUTF8(aDialogText, dialogText);
     gtk_signal_emit(GTK_OBJECT(parentWidget),
       moz_embed_signals[ALERT],
-      (const gchar *) dialogTitle.get(), (const gchar *) dialogText.get());
+      (const gchar *) NS_ConvertUTF16toUTF8(aDialogTitle).get(),
+      (const gchar *) NS_ConvertUTF16toUTF8(aDialogText).get());
     return NS_OK;
   }
 #ifndef MOZ_NO_GECKO_UI_FALLBACK_1_8_COMPAT
   EmbedPrompter prompter;
   prompter.SetTitle(aDialogTitle ? aDialogTitle : NS_LITERAL_STRING("Alert").get());
   prompter.SetMessageText(aDialogText);
   prompter.Create(EmbedPrompter::TYPE_ALERT,
           GetGtkWindowForDOMWindow(aParent));
@@ -111,23 +109,22 @@ GtkPromptService::AlertCheck(
   const PRUnichar* aDialogText,
   const PRUnichar* aCheckMsg,
   PRBool* aCheckValue)
 {
   NS_ENSURE_ARG_POINTER(aCheckValue);
 
   GtkWidget* parentWidget = GetGtkWidgetForDOMWindow(aParent);
   if (parentWidget && gtk_signal_handler_pending(parentWidget, moz_embed_signals[ALERT_CHECK], TRUE)) {
-    nsCString dialogTitle, dialogText, checkMsg;
-    CopyUTF16toUTF8(aDialogTitle, dialogTitle);
-    CopyUTF16toUTF8(aDialogText, dialogText);
-    CopyUTF16toUTF8(aCheckMsg, checkMsg);
     gtk_signal_emit(GTK_OBJECT(parentWidget),
                     moz_embed_signals[ALERT_CHECK],
-                    dialogTitle.get(), dialogTitle.get(), checkMsg.get(), aCheckValue);
+                    NS_ConvertUTF16toUTF8(aDialogTitle).get(),
+                    NS_ConvertUTF16toUTF8(aDialogTitle).get(),
+                    NS_ConvertUTF16toUTF8(aCheckMsg).get(),
+                    aCheckValue);
     return NS_OK;
   }
 #ifndef MOZ_NO_GECKO_UI_FALLBACK_1_8_COMPAT
   EmbedPrompter prompter;
   prompter.SetTitle(aDialogTitle ? aDialogTitle : NS_LITERAL_STRING("Alert").get());
   prompter.SetMessageText(aDialogText);
   prompter.SetCheckMessage(aCheckMsg);
   prompter.SetCheckValue(*aCheckValue);
@@ -138,26 +135,24 @@ GtkPromptService::AlertCheck(
 #endif
   return NS_OK;
 }
 
 NS_IMETHODIMP
 GtkPromptService::Confirm(
   nsIDOMWindow* aParent,
   const PRUnichar* aDialogTitle,
-  const PRUnichar* aDialogText, PRBool* aConfirm)
+  const PRUnichar* aDialogText, 
+  PRBool* aConfirm)
 {
   GtkWidget* parentWidget = GetGtkWidgetForDOMWindow(aParent);
   if (parentWidget && gtk_signal_handler_pending(parentWidget, moz_embed_signals[CONFIRM], TRUE)) {
-    nsCString dialogTitle, dialogText;
-    CopyUTF16toUTF8(aDialogTitle, dialogTitle);
-    CopyUTF16toUTF8(aDialogText, dialogText);
     gtk_signal_emit(GTK_OBJECT(parentWidget),
                     moz_embed_signals[CONFIRM],
-                    dialogTitle.get(), dialogText.get(), aConfirm);
+                    NS_ConvertUTF16toUTF8(aDialogTitle).get(), NS_ConvertUTF16toUTF8(aDialogText).get(), aConfirm);
     return NS_OK;
   }
 #ifndef MOZ_NO_GECKO_UI_FALLBACK_1_8_COMPAT
   EmbedPrompter prompter;
   prompter.SetTitle(aDialogTitle ? aDialogTitle : NS_LITERAL_STRING("Confirm").get());
   prompter.SetMessageText(aDialogText);
   prompter.Create(EmbedPrompter::TYPE_CONFIRM,
                   GetGtkWindowForDOMWindow(aParent));
@@ -175,25 +170,21 @@ GtkPromptService::ConfirmCheck(
   const PRUnichar* aCheckMsg,
   PRBool* aCheckValue,
   PRBool* aConfirm)
 {
   NS_ENSURE_ARG_POINTER(aCheckValue);
 
   GtkWidget* parentWidget = GetGtkWidgetForDOMWindow(aParent);
   if (parentWidget && gtk_signal_handler_pending(parentWidget, moz_embed_signals[CONFIRM_CHECK], TRUE)) {
-    nsCString dialogTitle, dialogText, checkMsg;
-    CopyUTF16toUTF8(aDialogTitle, dialogTitle);
-    CopyUTF16toUTF8(aDialogText, dialogText);
-    CopyUTF16toUTF8(aCheckMsg, checkMsg);
     gtk_signal_emit(GTK_OBJECT(parentWidget),
                     moz_embed_signals[CONFIRM_CHECK],
-                    dialogTitle.get(),
-                    dialogTitle.get(),
-                    checkMsg.get(),
+                    NS_ConvertUTF16toUTF8(aDialogTitle).get(),
+                    NS_ConvertUTF16toUTF8(aDialogTitle).get(),
+                    NS_ConvertUTF16toUTF8(aCheckMsg).get(),
                     aCheckValue,
                     aConfirm);
     return NS_OK;
   }
 #ifndef MOZ_NO_GECKO_UI_FALLBACK_1_8_COMPAT
   EmbedPrompter prompter;
   prompter.SetTitle(aDialogTitle ? aDialogTitle : NS_LITERAL_STRING("Confirm").get());
   prompter.SetMessageText(aDialogText);
@@ -218,33 +209,25 @@ GtkPromptService::ConfirmEx(
   const PRUnichar* aButton1Title,
   const PRUnichar* aButton2Title,
   const PRUnichar* aCheckMsg,
   PRBool* aCheckValue,
   PRInt32* aRetVal)
 {
   GtkWidget* parentWidget = GetGtkWidgetForDOMWindow(aParent);
   if (parentWidget && gtk_signal_handler_pending(parentWidget, moz_embed_signals[CONFIRM_EX], TRUE)) {
-    nsCString dialogTitle, dialogText, checkMsg;
-    nsCString button0,button1,button2;
-    CopyUTF16toUTF8(aDialogTitle, dialogTitle);
-    CopyUTF16toUTF8(aDialogText, dialogText);
-    CopyUTF16toUTF8(aCheckMsg, checkMsg);
-    CopyUTF16toUTF8(aButton0Title, button0);
-    CopyUTF16toUTF8(aButton1Title, button1);
-    CopyUTF16toUTF8(aButton2Title, button2);
     gtk_signal_emit(GTK_OBJECT(parentWidget),
                     moz_embed_signals[CONFIRM_EX],
-                    dialogTitle.get(),
-                    dialogTitle.get(),
+                    NS_ConvertUTF16toUTF8(aDialogTitle).get(),
+                    NS_ConvertUTF16toUTF8(aDialogText).get(),
                     aButtonFlags,
-                    button0.get(),
-                    button1.get(),
-                    button2.get(),
-                    checkMsg.get(),
+                    NS_ConvertUTF16toUTF8(aButton0Title).get(),
+                    NS_ConvertUTF16toUTF8(aButton1Title).get(),
+                    NS_ConvertUTF16toUTF8(aButton2Title).get(),
+                    NS_ConvertUTF16toUTF8(aCheckMsg).get(),
                     aCheckValue,
                     aRetVal);
     return NS_OK;
   }
 #ifndef MOZ_NO_GECKO_UI_FALLBACK_1_8_COMPAT
   EmbedPrompter prompter;
   prompter.SetTitle(aDialogTitle ? aDialogTitle : NS_LITERAL_STRING("Confirm").get());
   prompter.SetMessageText(aDialogText);
@@ -270,50 +253,59 @@ GtkPromptService::ConfirmEx(
     prompter.GetCheckValue(aCheckValue);
 
   prompter.GetButtonPressed(aRetVal);
 #endif
 
   return NS_OK;
 }
 
+#define XXX_ALLOCATOR_MISMATCH_XPCOM_GLIB(confused) PR_BEGIN_MACRO \
+  /* There is no way that this unforunate and confused object can  \
+   * possibly be handled correctly. It started its life as an      \
+   * XPCOM allocated pointer.                                      \
+   * Then someone called it a gchar which confused it.             \
+   * Then it was passed to a random function which probably        \
+   * assumed it had ownership.                                     \
+   * Finally it was freed using g_free.                            \
+   * This pointer is seriously confused.                           \
+   * XXX please please please help this pointer find some way to   \
+   * rest in peace.                                                \
+   */                                                              \
+  PR_END_MACRO
+
 NS_IMETHODIMP
 GtkPromptService::Prompt(
   nsIDOMWindow* aParent,
   const PRUnichar* aDialogTitle,
   const PRUnichar* aDialogText,
   PRUnichar** aValue,
   const PRUnichar* aCheckMsg,
   PRBool* aCheckValue,
   PRBool* aConfirm)
 {
   GtkWidget* parentWidget = GetGtkWidgetForDOMWindow(aParent);
   if (parentWidget && gtk_signal_handler_pending(parentWidget, moz_embed_signals[PROMPT], TRUE)) {
-    nsCString dialogTitle, dialogText, checkMsg, retValue;
-    CopyUTF16toUTF8(aDialogTitle, dialogTitle);
-    CopyUTF16toUTF8(aDialogText, dialogText);
-    CopyUTF16toUTF8(aCheckMsg, checkMsg);
-    CopyUTF16toUTF8(*aValue, retValue);
-    gchar * aGValue = g_strdup(retValue.get());
+    gchar * value = ToNewCString(NS_ConvertUTF16toUTF8(*aValue));
+    XXX_ALLOCATOR_MISMATCH_XPCOM_GLIB(value);
     gtk_signal_emit(GTK_OBJECT(parentWidget),
                     moz_embed_signals[PROMPT],
-                    dialogTitle.get(),
-                    dialogText.get(),
-                    &aGValue,
-                    checkMsg.get(),
+                    NS_ConvertUTF16toUTF8(aDialogTitle).get(),
+                    NS_ConvertUTF16toUTF8(aDialogText).get(),
+                    &value,
+                    NS_ConvertUTF16toUTF8(aCheckMsg).get(),
                     aCheckValue,
                     aConfirm,
                     NULL);
     if (*aConfirm) {
       if (*aValue)
         NS_Free(*aValue);
-      retValue.Assign(aGValue);
-      *aValue = UTF8ToNewUnicode(retValue);
+      *aValue = ToNewUnicode(NS_ConvertUTF8toUTF16(value));
     }
-    g_free(aGValue);
+    g_free(value);
     return NS_OK;
   }
 #ifndef MOZ_NO_GECKO_UI_FALLBACK_1_8_COMPAT
   EmbedPrompter prompter;
   prompter.SetTitle(aDialogTitle ? aDialogTitle : NS_LITERAL_STRING("Prompt").get());
   prompter.SetMessageText(aDialogText);
   prompter.SetTextValue(*aValue);
   if (aCheckMsg)
@@ -344,42 +336,39 @@ GtkPromptService::PromptUsernameAndPassw
   PRUnichar** aUsername,
   PRUnichar** aPassword,
   const PRUnichar* aCheckMsg,
   PRBool* aCheckValue,
   PRBool* aConfirm)
 {
   GtkWidget* parentWidget = GetGtkWidgetForDOMWindow(aParent);
   if (parentWidget && gtk_signal_handler_pending(parentWidget, moz_embed_signals[PROMPT_AUTH], TRUE)) {
-    nsCString dialogTitle, dialogText, checkMsg, retUsername, retPassword;
-    CopyUTF16toUTF8(aDialogTitle, dialogTitle);
-    CopyUTF16toUTF8(aDialogText, dialogText);
-    CopyUTF16toUTF8(aCheckMsg, checkMsg);
-    CopyUTF16toUTF8(*aUsername, retUsername);
-    CopyUTF16toUTF8(*aPassword, retPassword);
-    gchar * aGUsername = g_strdup(retUsername.get());
-    gchar * aGPassword = g_strdup(retPassword.get());
+    gchar * username = ToNewCString(NS_ConvertUTF16toUTF8(*aUsername));
+    XXX_ALLOCATOR_MISMATCH_XPCOM_GLIB(username);
+    gchar * password = ToNewCString(NS_ConvertUTF16toUTF8(*aPassword));
+    XXX_ALLOCATOR_MISMATCH_XPCOM_GLIB(password);
 
     gtk_signal_emit(GTK_OBJECT(parentWidget),
                     moz_embed_signals[PROMPT_AUTH],
-                    dialogTitle.get(), dialogText.get(), &aGUsername,
-                    &aGPassword, checkMsg.get(), aCheckValue, aConfirm);
+                    NS_ConvertUTF16toUTF8(aDialogTitle).get(),
+                    NS_ConvertUTF16toUTF8(aDialogText).get(),
+                    &username, &password,
+                    NS_ConvertUTF16toUTF8(aCheckMsg).get(),
+                    aCheckValue, aConfirm);
 
     if (*aConfirm) {
-        if (*aUsername)
-            NS_Free(*aUsername);
-        retUsername.Assign(aGUsername);
-        *aUsername = UTF8ToNewUnicode(retUsername);
-        if (*aPassword)
-            NS_Free(*aPassword);
-        retPassword.Assign(aGPassword);
-        *aPassword = UTF8ToNewUnicode(retPassword);
+      if (*aUsername)
+        NS_Free(*aUsername);
+      *aUsername = ToNewUnicode(NS_ConvertUTF8toUTF16(username));
+      if (*aPassword)
+        NS_Free(*aPassword);
+      *aPassword = ToNewUnicode(NS_ConvertUTF8toUTF16(password));
     }
-    g_free(aGUsername);
-    g_free(aGPassword);
+    g_free(username);
+    g_free(password);
     return NS_OK;
   }
 #ifndef MOZ_NO_GECKO_UI_FALLBACK_1_8_COMPAT
   EmbedPrompter prompter;
   prompter.SetTitle(aDialogTitle ? aDialogTitle : NS_LITERAL_STRING("Prompt").get());
   prompter.SetMessageText(aDialogText);
   prompter.SetUser(*aUsername);
   prompter.SetPassword(*aPassword);
@@ -413,39 +402,33 @@ GtkPromptService::PromptPassword(
   const PRUnichar* aDialogTitle,
   const PRUnichar* aDialogText,
   PRUnichar** aPassword,
   const PRUnichar* aCheckMsg,
   PRBool* aCheckValue, PRBool* aConfirm)
 {
   GtkWidget* parentWidget = GetGtkWidgetForDOMWindow(aParent);
   if (parentWidget && gtk_signal_handler_pending(parentWidget, moz_embed_signals[PROMPT_AUTH], TRUE)) {
-    nsCString dialogTitle, dialogText, checkMsg, retPassword;
-    CopyUTF16toUTF8(aDialogTitle, dialogTitle);
-    CopyUTF16toUTF8(aDialogText, dialogText);
-    CopyUTF16toUTF8(aCheckMsg, checkMsg);
-    CopyUTF16toUTF8(*aPassword, retPassword);
-    gchar * aGPassword = g_strdup(retPassword.get());
-    gtk_signal_emit(
-      GTK_OBJECT(parentWidget),
-      moz_embed_signals[PROMPT_AUTH],
-      dialogTitle.get(),
-      dialogText.get(),
-      NULL,
-      &aGPassword,
-      checkMsg.get(),
-      aCheckValue,
-      aConfirm);
+    gchar * password = ToNewCString(NS_ConvertUTF16toUTF8(*aPassword));
+    XXX_ALLOCATOR_MISMATCH_XPCOM_GLIB(password);
+    gtk_signal_emit(GTK_OBJECT(parentWidget),
+                    moz_embed_signals[PROMPT_AUTH],
+                    NS_ConvertUTF16toUTF8(aDialogTitle).get(),
+                    NS_ConvertUTF16toUTF8(aDialogText).get(),
+                    NULL,
+                    &password,
+                    NS_ConvertUTF16toUTF8(aCheckMsg).get(),
+                    aCheckValue,
+                    aConfirm);
     if (*aConfirm) {
       if (*aPassword)
         NS_Free(*aPassword);
-      retPassword.Assign(aGPassword);
-      *aPassword = UTF8ToNewUnicode(retPassword);
+      *aPassword = ToNewUnicode(NS_ConvertUTF8toUTF16(password));
     }
-    g_free(aGPassword);
+    g_free(password);
     return NS_OK;
   }
 #ifndef MOZ_NO_GECKO_UI_FALLBACK_1_8_COMPAT
   EmbedPrompter prompter;
   prompter.SetTitle(aDialogTitle ? aDialogTitle : NS_LITERAL_STRING("Prompt").get());
   prompter.SetMessageText(aDialogText);
   prompter.SetPassword(*aPassword);
   if (aCheckMsg)
@@ -475,34 +458,30 @@ GtkPromptService::Select(
   const PRUnichar* aDialogText,
   PRUint32 aCount,
   const PRUnichar** aSelectList,
   PRInt32* outSelection,
   PRBool* aConfirm)
 {
   GtkWidget* parentWidget = GetGtkWidgetForDOMWindow(aParent);
   if (parentWidget && gtk_signal_handler_pending(parentWidget, moz_embed_signals[SELECT], TRUE)) {
-    nsCString dialogTitle, dialogText;
-    CopyUTF16toUTF8(aDialogTitle, dialogTitle);
-    CopyUTF16toUTF8(aDialogText, dialogText);
     GList * list = NULL;
     nsCString *itemList = new nsCString[aCount];
     NS_ENSURE_TRUE(itemList, NS_ERROR_OUT_OF_MEMORY);
     for (PRUint32 i = 0; i < aCount; ++i) {
-      CopyUTF16toUTF8(aSelectList[i], itemList[i]);
+      itemList[i] = ToNewCString(NS_ConvertUTF16toUTF8(aSelectList[i]));
       list = g_list_append(list, (gpointer)itemList[i].get());
     }
-    gtk_signal_emit(
-      GTK_OBJECT(parentWidget),
-      moz_embed_signals[SELECT],
-      dialogTitle.get(),
-      dialogText.get(),
-      (const GList**)&list,
-      outSelection,
-      aConfirm);
+    gtk_signal_emit(GTK_OBJECT(parentWidget),
+                    moz_embed_signals[SELECT],
+                    NS_ConvertUTF16toUTF8(aDialogTitle).get(),
+                    NS_ConvertUTF16toUTF8(aDialogText).get(),
+                    (const GList**)&list,
+                    outSelection,
+                    aConfirm);
     delete[] itemList;
     g_list_free(list);
     return NS_OK;
   }
 #ifndef MOZ_NO_GECKO_UI_FALLBACK_1_8_COMPAT
   EmbedPrompter prompter;
   prompter.SetTitle(aDialogTitle ? aDialogTitle : NS_LITERAL_STRING("Select").get());
   prompter.SetMessageText(aDialogText);
@@ -523,40 +502,40 @@ GtkPromptService::CookieDialog(
   const nsACString &aHostname,
   PRInt32 aCookiesFromHost,
   PRBool aChangingCookie,
   PRBool *aRememberDecision,
   PRInt32 *aAccept)
 {
   /* FIXME - missing gint actions and gboolean illegal_path */
   gint actions = 1;
-  nsCString hostName (aHostname);
+  nsCString hostName(aHostname);
   nsCString aName;
   aCookie->GetName(aName);
   nsCString aValue;
   aCookie->GetValue(aValue);
   nsCString aDomain;
   aCookie->GetHost(aDomain);
   nsCString aPath;
   aCookie->GetPath(aPath);
   /* We have to investigate a value to use here */
   gboolean illegal_path = FALSE;
   PRUint64 aExpires;
   aCookie->GetExpires(&aExpires);
-  nsCOMPtr<nsIDOMWindow> domWindow (do_QueryInterface (aParent));
+  nsCOMPtr<nsIDOMWindow> domWindow(do_QueryInterface(aParent));
   GtkMozEmbed *parentWidget = GTK_MOZ_EMBED(GetGtkWidgetForDOMWindow(domWindow));
   GtkMozEmbedCookie *cookie_struct = g_new0(GtkMozEmbedCookie, 1);
   UNACCEPTABLE_CRASHY_GLIB_ALLOCATION(cookie_struct);
   if (parentWidget && cookie_struct) {
     g_signal_emit_by_name(
       GTK_OBJECT(parentWidget->common),
       "ask-cookie",
       cookie_struct,
       actions,
-      (const gchar *) hostName.get (),
+      (const gchar *) hostName.get(),
       (const gchar *) aName.get(),
       (const gchar *) aValue.get(),
       (const gchar *) aDomain.get(),
       (const gchar *) aPath.get(),
       illegal_path,
       aExpires,
       NULL);
   }
--- a/embedding/browser/gtk/src/Makefile.in
+++ b/embedding/browser/gtk/src/Makefile.in
@@ -38,28 +38,35 @@
 
 DEPTH		= ../../../..
 topsrcdir	= @top_srcdir@
 srcdir		= @srcdir@
 VPATH		= @srcdir@
 
 include $(DEPTH)/config/autoconf.mk
 
-MODULE		= gtkembedmoz
-LIBRARY_NAME	= gtkembedmoz
-LIBXUL_LIBRARY	= 1
+MODULE          = gtkembedmoz
+LIBRARY_NAME    = gtkembedmoz
+LIBXUL_LIBRARY  = 1
 FORCE_STATIC_LIB = 1
 
 LOCAL_INCLUDES += \
                   -I. \
                   $(NULL)
 
-#ifdef MOZ_GNOMEVFS_CFLAGS
-#DEFINES += -DMOZ_ENABLE_GNOMEVFS
-#endif
+#Temporary define for full migration from libxul
+#MOZ_GTKEMBED_DYN = 1
+
+ifdef MOZ_GTKEMBED_DYN
+#DEFINES += -DFIXED_BUG347731
+FORCE_SHARED_LIB = 1
+ifdef MOZ_ENABLE_LIBXUL
+LIBXUL_LIBRARY  = 
+endif
+endif
 
 DEFINES += -DIMPL_XREAPI
 
 # New Stuff in GtkMozEmbed
 ifdef MOZ_MICROBEMBED
 DEFINES += -DBAD_CERT_LISTENER2
 #Probably scrolling can be fixed without this hack
 DEFINES += -DMOZ_SCROLL_TOP_LEFT_HACK
@@ -99,16 +106,17 @@ REQUIRES	= xpcom \
 		  xulapp \
 		  exthandler \
 		  mimetype \
 		  chardet \
 		  find \
 		  webbrowserpersist \
 		  cookie \
 		  nkcache \
+		  pipboot \
 		  $(NULL)
 
 ifdef ACCESSIBILITY
 REQUIRES        += accessibility
 endif
 
 CPPSRCS		= \
 		gtkmozembed2.cpp \
@@ -133,17 +141,17 @@ CPPSRCS		+= \
 		$(NULL)
 
 ifdef MOZ_GTKPASSWORD_INTERFACE
 CPPSRCS		+= \
 		EmbedPasswordMgr.cpp \
 		$(NULL)
 
 XPIDLSRCS       += \
-	        nsIPassword.idl \
+		nsIPassword.idl \
 		nsIPasswordInternal.idl \
 		$(NULL)
 endif
 
 CSRCS           = \
 		gtkmozembedmarshal.c
 
 CPPSRCS         += \
@@ -167,16 +175,33 @@ EXPORTS		= \
 
 ifdef MOZ_ENABLE_GTK2
 EXPORTS		+= \
 		gtkmozembed_common.h \
 		gtkmozembed_download.h \
 		$(NULL)
 endif
 
+ifdef MOZ_GTKEMBED_DYN
+ifneq (,$(filter gtk gtk2 qt xlib,$(MOZ_WIDGET_TOOLKIT)))
+EXTRA_DSO_LDOPTS += \
+		$(DIST)/lib/libxpcomglue_s.$(LIB_SUFFIX) \
+		$(MOZ_COMPONENT_LIBS) \
+		$(MOZ_GTK2_LIBS) \
+		$(NULL)
+
+#Any Idea what can be used instead -lxul in FF configuration?
+ifndef MOZ_ENABLE_LIBXUL
+EXTRA_DSO_LDOPTS += \
+		-lxul \
+		$(NULL)
+endif
+endif
+endif
+
 include $(topsrcdir)/config/rules.mk
 
 ifeq ($(OS_ARCH), SunOS)
 ifndef GNU_CC
 # When using Sun's WorkShop compiler, including
 # /wherever/workshop-5.0/SC5.0/include/CC/std/time.h
 # causes most of these compiles to fail with:
 # line 29: Error: Multiple declaration for std::tm.
--- a/embedding/browser/gtk/src/gtkmozembed.h
+++ b/embedding/browser/gtk/src/gtkmozembed.h
@@ -81,16 +81,27 @@ extern "C" {
 #ifdef _IMPL_GTKMOZEMBED
 #define GTKMOZEMBED_API(type, name, params) NS_EXPORT_(type) name params;
 #else
 #define GTKMOZEMBED_API(type,name, params) NS_IMPORT_(type) name params;
 #endif
 
 #endif /* XPCOM_GLUE */
 
+/** @struct GtkWebHistoryItem.
+ *  Defines a web history item.
+ */
+typedef struct _GtkMozHistoryItem GtkMozHistoryItem;
+struct _GtkMozHistoryItem
+{
+  const gchar *title; /** < URL title */
+  const gchar *url;   /** < URL */
+  long accessed;      /** < The last time that the URL was accessed */
+};
+
 #ifdef MOZ_WIDGET_GTK2
 #include "gtkmozembed_common.h"
 #endif
 
 #define GTK_TYPE_MOZ_EMBED             (gtk_moz_embed_get_type())
 #define GTK_MOZ_EMBED(obj)             GTK_CHECK_CAST((obj), GTK_TYPE_MOZ_EMBED, GtkMozEmbed)
 #define GTK_MOZ_EMBED_CLASS(klass)     GTK_CHECK_CLASS_CAST((klass), GTK_TYPE_MOZ_EMBED, GtkMozEmbedClass)
 #define GTK_IS_MOZ_EMBED(obj)          GTK_CHECK_TYPE((obj), GTK_TYPE_MOZ_EMBED)
@@ -172,32 +183,30 @@ struct _GtkMozEmbedClass
                                 char **user, char **pass, const char *check_msg, gboolean *check_val);
   gboolean (* select)          (GtkMozEmbed *embed, const char *title, const char *text,
                                 GList *list, gint *selected_item);
   void     (* download_request)(GtkMozEmbed *, const char *, const char *, const char *, long, int, gpointer);
   gboolean (* upload_dialog)   (GtkMozEmbed *, const char *, const char *, char **);
   void     (* icon_changed)    (GtkMozEmbed *, gpointer*);
   void     (* mailto)          (GtkMozEmbed *, gchar *);
   void     (* network_error)   (GtkMozEmbed *, gchar *, const gint, const gchar **);
+  void     (* rss_request)     (GtkMozEmbed *, gchar *, gchar *);
 };
 
 GTKMOZEMBED_API(GtkType,       gtk_moz_embed_get_type,            (void))
 GTKMOZEMBED_API(GtkWidget*,    gtk_moz_embed_new,                 (void))
 GTKMOZEMBED_API(void,          gtk_moz_embed_push_startup,        (void))
 GTKMOZEMBED_API(void,          gtk_moz_embed_pop_startup,         (void))
 
 /* Tell gtkmozembed where the gtkmozembed libs live. If this is not specified,
    The MOZILLA_FIVE_HOME environment variable is checked. */
 GTKMOZEMBED_API(void,          gtk_moz_embed_set_path,            (const char *aPath))
-
 GTKMOZEMBED_API(void,          gtk_moz_embed_set_comp_path,       (const char *aPath))
-GTKMOZEMBED_API(void,          gtk_moz_embed_set_profile_path,    (const char *aDir,
-                                                                   const char *aName))
-GTKMOZEMBED_API(void,          gtk_moz_embed_load_url,            (GtkMozEmbed *embed,
-                                                                   const char *url))
+GTKMOZEMBED_API(void,          gtk_moz_embed_set_profile_path,    (const char *aDir, const char *aName))
+GTKMOZEMBED_API(void,          gtk_moz_embed_load_url,            (GtkMozEmbed *embed, const char *url))
 GTKMOZEMBED_API(void,          gtk_moz_embed_stop_load,           (GtkMozEmbed *embed))
 GTKMOZEMBED_API(gboolean,      gtk_moz_embed_can_go_back,         (GtkMozEmbed *embed))
 GTKMOZEMBED_API(gboolean,      gtk_moz_embed_can_go_forward,      (GtkMozEmbed *embed))
 GTKMOZEMBED_API(void,          gtk_moz_embed_go_back,             (GtkMozEmbed *embed))
 GTKMOZEMBED_API(void,          gtk_moz_embed_go_forward,          (GtkMozEmbed *embed))
 GTKMOZEMBED_API(void,          gtk_moz_embed_render_data,         (GtkMozEmbed *embed, const char *data, guint32 len,
                                                                    const char *base_uri, const char *mime_type))
 GTKMOZEMBED_API(void,          gtk_moz_embed_open_stream,         (GtkMozEmbed *embed,
@@ -209,36 +218,42 @@ GTKMOZEMBED_API(gchar*,        gtk_moz_e
 GTKMOZEMBED_API(gchar*,        gtk_moz_embed_get_js_status,       (GtkMozEmbed *embed))
 GTKMOZEMBED_API(gchar*,        gtk_moz_embed_get_title,           (GtkMozEmbed *embed))
 GTKMOZEMBED_API(gchar*,        gtk_moz_embed_get_location,        (GtkMozEmbed *embed))
 GTKMOZEMBED_API(void,          gtk_moz_embed_reload,              (GtkMozEmbed *embed, gint32 flags))
 GTKMOZEMBED_API(void,          gtk_moz_embed_set_chrome_mask,     (GtkMozEmbed *embed, guint32 flags))
 GTKMOZEMBED_API(guint32,       gtk_moz_embed_get_chrome_mask,     (GtkMozEmbed *embed))
 GTKMOZEMBED_API(gboolean,      gtk_moz_embed_get_zoom_level,      (GtkMozEmbed *embed, gint*, gpointer))
 GTKMOZEMBED_API(gboolean,      gtk_moz_embed_set_zoom_level,      (GtkMozEmbed *embed, gint, gpointer))
-GTKMOZEMBED_API(gboolean,      gtk_moz_embed_load_image,          (GtkMozEmbed *embed, const gchar*))
 GTKMOZEMBED_API(gboolean,      gtk_moz_embed_find_text,           (GtkMozEmbed *embed, const gchar*, gboolean, gboolean, gboolean, gboolean, gint))
 GTKMOZEMBED_API(gboolean,      gtk_moz_embed_clipboard,           (GtkMozEmbed *embed, guint, gint))
 GTKMOZEMBED_API(void,          gtk_moz_embed_notify_plugins,      (GtkMozEmbed *embed, guint))
 GTKMOZEMBED_API(void,          gtk_moz_embed_check_logins,        (GtkMozEmbed *embed))
 GTKMOZEMBED_API(char*,         gtk_moz_embed_get_encoding,        (GtkMozEmbed *embed, gint))
 GTKMOZEMBED_API(void,          gtk_moz_embed_set_encoding,        (GtkMozEmbed *embed, const gchar *, gint))
 GTKMOZEMBED_API(guint,         gtk_moz_embed_get_context_info,    (GtkMozEmbed *embed, gpointer event, gpointer *node,
                                                                    gint *x, gint *y, gint *docindex,
                                                                    const gchar **url, const gchar **objurl, const gchar **docurl))
 GTKMOZEMBED_API(const gchar*,  gtk_moz_embed_get_selection,       (GtkMozEmbed *embed))
 GTKMOZEMBED_API(gboolean,      gtk_moz_embed_get_doc_info,        (GtkMozEmbed *embed, gpointer node, gint docindex, const gchar**title,
                                                                    const gchar**location, const gchar **file_type, guint *file_size,
                                                                    gint *width, gint *height))
 GTKMOZEMBED_API(gboolean,      gtk_moz_embed_insert_text,         (GtkMozEmbed *embed, const gchar*, gpointer node))
 GTKMOZEMBED_API(gboolean,      gtk_moz_embed_save_target,         (GtkMozEmbed *embed, gchar*, gchar*, gint))
+GTKMOZEMBED_API(gint,          gtk_moz_embed_get_shistory_list,   (GtkMozEmbed *embed, GtkMozHistoryItem **GtkHI, guint type))
+GTKMOZEMBED_API(gint,          gtk_moz_embed_get_shistory_index,  (GtkMozEmbed *embed))
+GTKMOZEMBED_API(void,          gtk_moz_embed_shistory_goto_index, (GtkMozEmbed *embed, gint index))
+GTKMOZEMBED_API(gboolean,      gtk_moz_embed_get_server_cert,     (GtkMozEmbed *embed, gpointer *aCert, gpointer))
 
-/* Defines used by download and upload components */
-#define GTK_MOZ_EMBED_COMMON_FILE_SCHEME "file://"
-#define GTK_MOZ_EMBED_BLUETOOTH_FILE_SCHEME "obex://"
+typedef enum
+{
+  GTK_MOZ_EMBED_BACK_SHISTORY,
+  GTK_MOZ_EMBED_FORWARD_SHISTORY
+} GtkMozEmbedSessionHistory;
+
 typedef enum
 {
   GTK_MOZ_EMBED_SELECT_ALL,
   GTK_MOZ_EMBED_CAN_SELECT,
   GTK_MOZ_EMBED_CUT,
   GTK_MOZ_EMBED_COPY,
   GTK_MOZ_EMBED_PASTE,
   GTK_MOZ_EMBED_CAN_CUT,
--- a/embedding/browser/gtk/src/gtkmozembed2.cpp
+++ b/embedding/browser/gtk/src/gtkmozembed2.cpp
@@ -60,22 +60,29 @@
 #include "nsIIOService.h"
 #include "nsIFileURL.h"
 #include "nsIURI.h"
 #include "nsILocalFile.h"
 #include "nsIFile.h"
 // so we can do our get_nsIWebBrowser later...
 #include "nsIWebBrowser.h"
 
+#include "nsISSLStatus.h"
+#include "nsISSLStatusProvider.h"
+#include "nsIX509Cert.h"
+#include "nsISecureBrowserUI.h"
+
 // for strings
 #ifdef MOZILLA_INTERNAL_API
 #include "nsXPIDLString.h"
 #include "nsReadableUtils.h"
 #else
 #include "nsStringAPI.h"
+#include "nsComponentManagerUtils.h"
+#include "nsServiceManagerUtils.h"
 #endif
 
 #ifdef MOZ_WIDGET_GTK2
 
 #include "gtkmozembedmarshal.h"
 
 #define NEW_TOOLKIT_STRING(x) g_strdup(NS_ConvertUTF16toUTF8(x).get())
 #define GET_OBJECT_CLASS_TYPE(x) G_OBJECT_CLASS_TYPE(x)
@@ -166,18 +173,18 @@ handle_child_focus_out(GtkWidget     *aW
                        GdkEventFocus *aGdkFocusEvent,
                        GtkMozEmbed   *aEmbed);
 
 #ifdef MOZ_WIDGET_GTK
 // signal handlers for tracking the focus in and and focus out events
 // on the toplevel window.
 
 static void
-handle_toplevel_focus_in (GtkMozArea    *aArea,
-                          GtkMozEmbed   *aEmbed);
+handle_toplevel_focus_in(GtkMozArea    *aArea,
+                         GtkMozEmbed   *aEmbed);
 
 static void
 handle_toplevel_focus_out(GtkMozArea    *aArea,
                           GtkMozEmbed   *aEmbed);
 
 #endif /* MOZ_WIDGET_GTK */
 
 // globals for this type of widget
@@ -234,36 +241,36 @@ gtk_moz_embed_class_init(GtkMozEmbedClas
   widget_class->get_accessible = gtk_moz_embed_get_accessible;
 #endif
 
   object_class->destroy = gtk_moz_embed_destroy;
 
   // set up our signals
 
   moz_embed_signals[LINK_MESSAGE] =
-    gtk_signal_new ("link_message",
-                    GTK_RUN_FIRST,
-                    GET_OBJECT_CLASS_TYPE(klass),
-                    GTK_SIGNAL_OFFSET(GtkMozEmbedClass, link_message),
-                    gtk_marshal_NONE__NONE,
-                    GTK_TYPE_NONE, 0);
+    gtk_signal_new("link_message",
+                   GTK_RUN_FIRST,
+                   GET_OBJECT_CLASS_TYPE(klass),
+                   GTK_SIGNAL_OFFSET(GtkMozEmbedClass, link_message),
+                   gtk_marshal_NONE__NONE,
+                   GTK_TYPE_NONE, 0);
   moz_embed_signals[JS_STATUS] =
-    gtk_signal_new ("js_status",
-                    GTK_RUN_FIRST,
-                    GET_OBJECT_CLASS_TYPE(klass),
-                    GTK_SIGNAL_OFFSET(GtkMozEmbedClass, js_status),
-                    gtk_marshal_NONE__NONE,
-                    GTK_TYPE_NONE, 0);
+    gtk_signal_new("js_status",
+                   GTK_RUN_FIRST,
+                   GET_OBJECT_CLASS_TYPE(klass),
+                   GTK_SIGNAL_OFFSET(GtkMozEmbedClass, js_status),
+                   gtk_marshal_NONE__NONE,
+                   GTK_TYPE_NONE, 0);
   moz_embed_signals[LOCATION] =
-    gtk_signal_new ("location",
-                    GTK_RUN_FIRST,
-                    GET_OBJECT_CLASS_TYPE(klass),
-                    GTK_SIGNAL_OFFSET(GtkMozEmbedClass, location),
-                    gtk_marshal_NONE__NONE,
-                    GTK_TYPE_NONE, 0);
+    gtk_signal_new("location",
+                   GTK_RUN_FIRST,
+                   GET_OBJECT_CLASS_TYPE(klass),
+                   GTK_SIGNAL_OFFSET(GtkMozEmbedClass, location),
+                   gtk_marshal_NONE__NONE,
+                   GTK_TYPE_NONE, 0);
   moz_embed_signals[TITLE] =
     gtk_signal_new("title",
                    GTK_RUN_FIRST,
                    GET_OBJECT_CLASS_TYPE(klass),
                    GTK_SIGNAL_OFFSET(GtkMozEmbedClass, title),
                    gtk_marshal_NONE__NONE,
                    GTK_TYPE_NONE, 0);
   moz_embed_signals[PROGRESS] =
@@ -625,16 +632,26 @@ gtk_moz_embed_class_init(GtkMozEmbedClas
                    GTK_SIGNAL_OFFSET(GtkMozEmbedClass, network_error),
                    gtkmozembed_VOID__INT_STRING_STRING,
                    GTK_TYPE_NONE,
                    3,
                    GTK_TYPE_INT,
                    GTK_TYPE_STRING,
                    GTK_TYPE_STRING);
 
+  moz_embed_signals[RSS_REQUEST] =
+    gtk_signal_new("rss_request",
+                   GTK_RUN_LAST,
+                   GET_OBJECT_CLASS_TYPE(klass),
+                   GTK_SIGNAL_OFFSET(GtkMozEmbedClass, rss_request),
+                   gtkmozembed_VOID__STRING_STRING,
+                   GTK_TYPE_NONE,
+                   2,
+                   GTK_TYPE_STRING, GTK_TYPE_STRING);
+
 #endif
 
 #ifdef MOZ_WIDGET_GTK
   gtk_object_class_add_signals(object_class, moz_embed_signals,
                                EMBED_LAST_SIGNAL);
 #endif /* MOZ_WIDGET_GTK */
 
 }
@@ -670,17 +687,17 @@ gtk_moz_embed_destroy(GtkObject *object)
   g_return_if_fail(GTK_IS_MOZ_EMBED(object));
 
   embed = GTK_MOZ_EMBED(object);
   embedPrivate = (EmbedPrivate *)embed->data;
 
   if (embedPrivate) {
 
     // Destroy the widget only if it's been Init()ed.
-    if(embedPrivate->mMozWindowWidget != 0) {
+    if (embedPrivate->mMozWindowWidget != 0) {
       embedPrivate->Destroy();
     }
 
     delete embedPrivate;
     embed->data = NULL;
   }
 }
 
@@ -703,28 +720,28 @@ gtk_moz_embed_realize(GtkWidget *widget)
   GTK_WIDGET_SET_FLAGS(widget, GTK_REALIZED);
 
   attributes.window_type = GDK_WINDOW_CHILD;
   attributes.x = widget->allocation.x;
   attributes.y = widget->allocation.y;
   attributes.width = widget->allocation.width;
   attributes.height = widget->allocation.height;
   attributes.wclass = GDK_INPUT_OUTPUT;
-  attributes.visual = gtk_widget_get_visual (widget);
-  attributes.colormap = gtk_widget_get_colormap (widget);
-  attributes.event_mask = gtk_widget_get_events (widget) | GDK_EXPOSURE_MASK;
+  attributes.visual = gtk_widget_get_visual(widget);
+  attributes.colormap = gtk_widget_get_colormap(widget);
+  attributes.event_mask = gtk_widget_get_events(widget) | GDK_EXPOSURE_MASK;
 
   attributes_mask = GDK_WA_X | GDK_WA_Y | GDK_WA_VISUAL | GDK_WA_COLORMAP;
 
-  widget->window = gdk_window_new (gtk_widget_get_parent_window (widget),
+  widget->window = gdk_window_new(gtk_widget_get_parent_window(widget),
            &attributes, attributes_mask);
-  gdk_window_set_user_data (widget->window, embed);
+  gdk_window_set_user_data(widget->window, embed);
 
   widget->style = gtk_style_attach (widget->style, widget->window);
-  gtk_style_set_background (widget->style, widget->window, GTK_STATE_NORMAL);
+  gtk_style_set_background(widget->style, widget->window, GTK_STATE_NORMAL);
 
   // initialize the window
   nsresult rv;
   rv = embedPrivate->Init(embed);
   g_return_if_fail(NS_SUCCEEDED(rv));
 
   PRBool alreadyRealized = PR_FALSE;
   rv = embedPrivate->Realize(&alreadyRealized);
@@ -888,18 +905,18 @@ handle_child_focus_out(GtkWidget     *aW
 
   embedPrivate->ChildFocusOut();
 
   return PR_FALSE;
 }
 
 #ifdef MOZ_WIDGET_GTK
 void
-handle_toplevel_focus_in (GtkMozArea    *aArea,
-                          GtkMozEmbed   *aEmbed)
+handle_toplevel_focus_in(GtkMozArea    *aArea,
+                         GtkMozEmbed   *aEmbed)
 {
   EmbedPrivate   *embedPrivate;
   embedPrivate = (EmbedPrivate *)aEmbed->data;
 
   embedPrivate->TopLevelFocusIn();
 }
 
 void
@@ -964,16 +981,17 @@ gtk_moz_embed_load_url(GtkMozEmbed *embe
   EmbedPrivate *embedPrivate;
 
   g_return_if_fail(embed != NULL);
   g_return_if_fail(GTK_IS_MOZ_EMBED(embed));
 
   embedPrivate = (EmbedPrivate *)embed->data;
 
   embedPrivate->SetURI(url);
+  embedPrivate->mOpenBlock = PR_FALSE;
 
   // If the widget is realized, load the URI.  If it isn't then we
   // will load it later.
   if (GTK_WIDGET_REALIZED(embed))
     embedPrivate->LoadCurrentURI();
 }
 
 void
@@ -1237,65 +1255,65 @@ gtk_moz_embed_get_chrome_mask(GtkMozEmbe
   g_return_val_if_fail (GTK_IS_MOZ_EMBED(embed), 0);
 
   embedPrivate = (EmbedPrivate *)embed->data;
 
   return embedPrivate->mChromeMask;
 }
 
 void
-gtk_moz_embed_get_nsIWebBrowser  (GtkMozEmbed *embed, nsIWebBrowser **retval)
+gtk_moz_embed_get_nsIWebBrowser(GtkMozEmbed *embed, nsIWebBrowser **retval)
 {
   EmbedPrivate *embedPrivate;
 
   g_return_if_fail (embed != NULL);
   g_return_if_fail (GTK_IS_MOZ_EMBED(embed));
 
   embedPrivate = (EmbedPrivate *)embed->data;
 
   if (embedPrivate->mWindow)
     embedPrivate->mWindow->GetWebBrowser(retval);
 }
 
 PRUnichar *
-gtk_moz_embed_get_title_unichar (GtkMozEmbed *embed)
+gtk_moz_embed_get_title_unichar(GtkMozEmbed *embed)
 {
   PRUnichar *retval = nsnull;
   EmbedPrivate *embedPrivate;
 
   g_return_val_if_fail ((embed != NULL), (PRUnichar *)NULL);
   g_return_val_if_fail (GTK_IS_MOZ_EMBED(embed), (PRUnichar *)NULL);
 
   embedPrivate = (EmbedPrivate *)embed->data;
 
   if (embedPrivate->mWindow)
     retval = ToNewUnicode(embedPrivate->mWindow->mTitle);
 
   return retval;
 }
 
 PRUnichar *
-gtk_moz_embed_get_js_status_unichar (GtkMozEmbed *embed)
+gtk_moz_embed_get_js_status_unichar(GtkMozEmbed *embed)
 {
   PRUnichar *retval = nsnull;
   EmbedPrivate *embedPrivate;
 
   g_return_val_if_fail ((embed != NULL), (PRUnichar *)NULL);
   g_return_val_if_fail (GTK_IS_MOZ_EMBED(embed), (PRUnichar *)NULL);
 
   embedPrivate = (EmbedPrivate *)embed->data;
 
   if (embedPrivate->mWindow)
     retval = ToNewUnicode(embedPrivate->mWindow->mJSStatus);
 
   return retval;
 }
 
 PRUnichar *
-gtk_moz_embed_get_link_message_unichar (GtkMozEmbed *embed)
+gtk_moz_embed_get_link_message_unichar(GtkMozEmbed *embed)
 {
   PRUnichar *retval = nsnull;
   EmbedPrivate *embedPrivate;
 
   g_return_val_if_fail ((embed != NULL), (PRUnichar *)NULL);
   g_return_val_if_fail (GTK_IS_MOZ_EMBED(embed), (PRUnichar *)NULL);
 
   embedPrivate = (EmbedPrivate *)embed->data;
@@ -1415,82 +1433,71 @@ gtk_moz_embed_single_create_window(GtkMo
     return;
 
   gtk_signal_emit(GTK_OBJECT(single),
                   moz_embed_single_signals[NEW_WINDOW_ORPHAN],
                   aNewEmbed, aChromeFlags);
 }
 
 gboolean
-gtk_moz_embed_set_zoom_level (GtkMozEmbed *embed, gint zoom_level, gpointer context)
+gtk_moz_embed_set_zoom_level(GtkMozEmbed *embed, gint zoom_level, gpointer context)
 {
   g_return_val_if_fail (embed != NULL, FALSE);
-  g_return_val_if_fail (GTK_IS_MOZ_EMBED (embed), FALSE);
-  g_return_val_if_fail (GTK_WIDGET_REALIZED (GTK_WIDGET(embed)), FALSE);
+  g_return_val_if_fail (GTK_IS_MOZ_EMBED(embed), FALSE);
+  g_return_val_if_fail (GTK_WIDGET_REALIZED(GTK_WIDGET(embed)), FALSE);
   EmbedPrivate *embedPrivate;
   embedPrivate = (EmbedPrivate *) embed->data;
   nsresult rv = NS_OK;
   if (embedPrivate)
     rv = embedPrivate->SetZoom(zoom_level, (nsISupports*)context);
   return NS_SUCCEEDED(rv);
 }
 
 gboolean
-gtk_moz_embed_get_zoom_level (GtkMozEmbed *embed, gint *zoom_level, gpointer context)
+gtk_moz_embed_get_zoom_level(GtkMozEmbed *embed, gint *zoom_level, gpointer context)
 {
   g_return_val_if_fail (embed != NULL, FALSE);
-  g_return_val_if_fail (GTK_IS_MOZ_EMBED (embed), FALSE);
-  g_return_val_if_fail (GTK_WIDGET_REALIZED (GTK_WIDGET(embed)), FALSE);
+  g_return_val_if_fail (GTK_IS_MOZ_EMBED(embed), FALSE);
+  g_return_val_if_fail (GTK_WIDGET_REALIZED(GTK_WIDGET(embed)), FALSE);
   EmbedPrivate *embedPrivate;
   embedPrivate = (EmbedPrivate *) embed->data;
   nsresult rv = NS_OK;
   if (embedPrivate)
     rv = embedPrivate->GetZoom(zoom_level, (nsISupports*)context);
   return NS_SUCCEEDED(rv);
 }
 
 gboolean
-gtk_moz_embed_load_image (GtkMozEmbed *embed, const gchar *url)
-{
-  g_return_val_if_fail (embed != NULL, FALSE);
-  g_return_val_if_fail (embed, FALSE);
-
-  gtk_moz_embed_load_url (embed, url);
-
-  return TRUE;
-}
-
-gboolean
-gtk_moz_embed_find_text (GtkMozEmbed *embed, const gchar *string,
-                         gboolean reverse, gboolean whole_word,
-                         gboolean case_sensitive, gboolean restart, gint target)
+gtk_moz_embed_find_text(GtkMozEmbed *embed, const gchar *string,
+                        gboolean reverse, gboolean whole_word,
+                        gboolean case_sensitive, gboolean restart, gint target)
 {
   EmbedPrivate *embedPrivate;
   g_return_val_if_fail (embed != NULL, FALSE);
   g_return_val_if_fail (GTK_IS_MOZ_EMBED(embed), FALSE);
   g_return_val_if_fail (GTK_WIDGET_REALIZED(GTK_WIDGET(embed)), FALSE);
   embedPrivate = (EmbedPrivate *)embed->data;
   if (embedPrivate->mWindow)
-    return embedPrivate->FindText (string, reverse, whole_word, case_sensitive, restart);
+    return embedPrivate->FindText(string, reverse, whole_word, case_sensitive, restart);
   return FALSE;
 }
 
 gboolean
-gtk_moz_embed_clipboard (GtkMozEmbed *embed, guint action, gint target)
+gtk_moz_embed_clipboard(GtkMozEmbed *embed, guint action, gint target)
 {
   EmbedPrivate *embedPrivate;
   g_return_val_if_fail (embed != NULL, FALSE);
   g_return_val_if_fail (GTK_IS_MOZ_EMBED(embed), FALSE);
   g_return_val_if_fail (GTK_WIDGET_REALIZED(GTK_WIDGET(embed)), FALSE);
   embedPrivate = (EmbedPrivate *)embed->data;
   return embedPrivate->ClipBoardAction((GtkMozEmbedClipboard)action) ? TRUE : FALSE;
 }
 
 void
-gtk_moz_embed_notify_plugins (GtkMozEmbed *embed, guint)
+gtk_moz_embed_notify_plugins(GtkMozEmbed *embed, guint)
 {
   return;
 }
 
 gchar *
 gtk_moz_embed_get_encoding(GtkMozEmbed *embed, gint frame_number)
 {
   gchar *retval = nsnull;
@@ -1506,69 +1513,66 @@ gtk_moz_embed_get_encoding(GtkMozEmbed *
 void
 gtk_moz_embed_set_encoding(GtkMozEmbed *embed, const gchar *encoding_text, gint frame_number)
 {
   EmbedPrivate *embedPrivate;
   g_return_if_fail(embed != NULL);
   g_return_if_fail(GTK_IS_MOZ_EMBED(embed));
   embedPrivate = (EmbedPrivate *)embed->data;
   if (embedPrivate->mWindow)
-    embedPrivate->SetEncoding (encoding_text);
+    embedPrivate->SetEncoding(encoding_text);
   return;
 }
 
 guint
 gtk_moz_embed_get_context_info(GtkMozEmbed *embed, gpointer event, gpointer *node,
                                gint *x, gint *y, gint *docindex,
                                const gchar **url, const gchar **objurl, const gchar **docurl)
 {
 #ifdef MOZ_WIDGET_GTK2
   EmbedPrivate *embedPrivate;
   g_return_val_if_fail(embed != NULL, GTK_MOZ_EMBED_CTX_NONE);
   g_return_val_if_fail(GTK_IS_MOZ_EMBED(embed), GTK_MOZ_EMBED_CTX_NONE);
   embedPrivate = (EmbedPrivate *)embed->data;
 
-   if (!event) {
-      nsIWebBrowser *webBrowser = nsnull;
-      gtk_moz_embed_get_nsIWebBrowser (GTK_MOZ_EMBED (embed), &webBrowser);
-      if (!webBrowser) return GTK_MOZ_EMBED_CTX_NONE;
+  if (!event) {
+    nsIWebBrowser *webBrowser = nsnull;
+    gtk_moz_embed_get_nsIWebBrowser(GTK_MOZ_EMBED(embed), &webBrowser);
+    if (!webBrowser) return GTK_MOZ_EMBED_CTX_NONE;
 
-      nsCOMPtr<nsIDOMWindow> DOMWindow;
-      webBrowser->GetContentDOMWindow(getter_AddRefs(DOMWindow));
-      if (!DOMWindow) return GTK_MOZ_EMBED_CTX_NONE;
+    nsCOMPtr<nsIDOMWindow> DOMWindow;
+    webBrowser->GetContentDOMWindow(getter_AddRefs(DOMWindow));
+    if (!DOMWindow) return GTK_MOZ_EMBED_CTX_NONE;
 
-      nsCOMPtr<nsIDOMDocument> doc;
-      DOMWindow->GetDocument (getter_AddRefs(doc));
-      if (!doc) return GTK_MOZ_EMBED_CTX_NONE;
+    nsCOMPtr<nsIDOMDocument> doc;
+    DOMWindow->GetDocument(getter_AddRefs(doc));
+    if (!doc) return GTK_MOZ_EMBED_CTX_NONE;
 
-      nsCOMPtr<nsIDOMNode> docnode = do_QueryInterface(doc);
-      *node = docnode;
-      return GTK_MOZ_EMBED_CTX_DOCUMENT;
+    nsCOMPtr<nsIDOMNode> docnode = do_QueryInterface(doc);
+    *node = docnode;
+    return GTK_MOZ_EMBED_CTX_DOCUMENT;
   }
 
   if (embedPrivate->mEventListener) {
-#ifdef MOZILLA_INTERNAL_API //FIXME replace to using nsStringAPI
-
     EmbedContextMenuInfo * ctx_menu = embedPrivate->mEventListener->GetContextInfo();
     if (!ctx_menu)
       return 0;
     ctx_menu->UpdateContextData(event);
     *x = ctx_menu->mX;
     *y = ctx_menu->mY;
     *docindex = ctx_menu->mCtxFrameNum;
     if (ctx_menu->mEmbedCtxType & GTK_MOZ_EMBED_CTX_LINK && !*url) {
-      *url = ToNewCString(ctx_menu->mCtxHref);
+      *url = ToNewUTF8String(ctx_menu->mCtxHref);
     }
     if (ctx_menu->mEmbedCtxType & GTK_MOZ_EMBED_CTX_IMAGE) {
-      *objurl = ToNewCString(ctx_menu->mCtxImgHref);
+      *objurl = ToNewUTF8String(ctx_menu->mCtxImgHref);
     }
-    *docurl = ToNewCString(ctx_menu->mCtxURI);
+    *docurl = ToNewUTF8String(ctx_menu->mCtxURI);
     *node = ctx_menu->mEventNode;
     return ctx_menu->mEmbedCtxType;
-#endif
   }
 #endif
   return 0;
 }
 
 const gchar*
 gtk_moz_embed_get_selection(GtkMozEmbed *embed)
 {
@@ -1601,78 +1605,80 @@ gtk_moz_embed_insert_text(GtkMozEmbed *e
   }
   if (string) {
     embedPrivate->InsertTextToNode((nsIDOMNode*)node, string);
     return TRUE;
   }
   return FALSE;
 }
 
+
 gboolean
-gtk_moz_embed_save_target (GtkMozEmbed *aEmbed, gchar* aUrl,
-                           gchar* aDestination,  gint aSetting)
+gtk_moz_embed_save_target(GtkMozEmbed *aEmbed, gchar* aUrl,
+                          gchar* aDestination, gint aSetting)
 {
   //FIXME
   nsresult rv;
 
   g_return_val_if_fail (aEmbed != NULL, FALSE);
   nsIWebBrowser *webBrowser = nsnull;
-  gtk_moz_embed_get_nsIWebBrowser (GTK_MOZ_EMBED (aEmbed), &webBrowser);
-  g_return_val_if_fail  (webBrowser != NULL, FALSE);
+  gtk_moz_embed_get_nsIWebBrowser(GTK_MOZ_EMBED(aEmbed), &webBrowser);
+  g_return_val_if_fail (webBrowser != NULL, FALSE);
 
   nsCOMPtr<nsIDOMWindow> DOMWindow;
   webBrowser->GetContentDOMWindow(getter_AddRefs(DOMWindow));
   g_return_val_if_fail (DOMWindow != NULL, FALSE);
 
   nsCOMPtr<nsIDOMDocument> doc;
-  DOMWindow->GetDocument (getter_AddRefs(doc));
+  DOMWindow->GetDocument(getter_AddRefs(doc));
   g_return_val_if_fail (doc != NULL, FALSE);
 
   nsCOMPtr<nsIWebBrowserPersist> persist =
     do_CreateInstance(NS_WEBBROWSERPERSIST_CONTRACTID);
   if (!persist)
     return FALSE;
 
-  nsCOMPtr<nsIIOService> ios (do_GetService(NS_IOSERVICE_CONTRACTID));
+  nsCOMPtr<nsIIOService> ios(do_GetService(NS_IOSERVICE_CONTRACTID));
   if (!ios)
     return FALSE;
 
   nsCOMPtr<nsIURI> uri;
   rv = ios->NewURI(nsDependentCString(aDestination), "", nsnull, getter_AddRefs(uri));
   if (!uri)
     return FALSE;
 
-  nsCOMPtr<nsIFileURL> fileURL(do_QueryInterface(uri));
-  if (!fileURL)
-    return FALSE;
-
-  nsCOMPtr<nsIFile> file;
-  rv = fileURL->GetFile(getter_AddRefs(file));
-  if (!file)
-    return FALSE;
-
   if (aSetting == 0)
   {
-    rv = ios->NewURI(nsDependentCString(aUrl), "", nsnull, getter_AddRefs(uri));
-    if (!uri)
+    nsCOMPtr<nsIURI> uri_s;
+    rv = ios->NewURI(nsDependentCString(aUrl), "", nsnull, getter_AddRefs(uri_s));
+    rv = ios->NewURI(nsDependentCString(aDestination), "", nsnull, getter_AddRefs(uri));
+
+    if (!uri_s)
       return FALSE;
-    rv = persist->SaveURI(uri, nsnull, nsnull, nsnull, "", file);
+    rv = persist->SaveURI(uri_s, nsnull, nsnull, nsnull, "", uri);  
+
     if (NS_SUCCEEDED(rv))
       return TRUE;
 
   } else if (aSetting == 1)
   {
-    nsCOMPtr<nsILocalFile> contentFolder;
+    nsCOMPtr<nsIURI> contentFolder;
+    rv = ios->NewURI(nsDependentCString(aDestination), "", nsnull, getter_AddRefs(uri));
+    rv = ios->NewURI(nsDependentCString(aDestination), "", nsnull, getter_AddRefs(contentFolder));
+
     nsCString contentFolderPath;
-    file->GetNativePath(contentFolderPath);
+    contentFolder->GetSpec(contentFolderPath);
     contentFolderPath.Append("_content");
-    rv = NS_NewNativeLocalFile(contentFolderPath, PR_TRUE, getter_AddRefs(contentFolder));
+    printf("GetNativePath=%s ", contentFolderPath.get());
+    rv = ios->NewURI(contentFolderPath, "", nsnull, getter_AddRefs(contentFolder));
+
     if (NS_FAILED(rv))
       return FALSE;
-    rv = persist->SaveDocument(doc, file, contentFolder, nsnull, 0, 0);
+    
+    rv = persist->SaveDocument(doc, uri, contentFolder, nsnull, 0, 0);
     if (NS_SUCCEEDED(rv))
       return TRUE;
   } else if (aSetting == 2)
   {
     // FIXME: How should I handle this option G_WEBENGINE_SAVE_FRAMES ?
     return FALSE;
   }
   return FALSE;
@@ -1699,20 +1705,102 @@ gtk_moz_embed_get_doc_info(GtkMozEmbed *
 
   if (width && height) {
     nsString imgSrc;
     EmbedContextMenuInfo * ctx_menu = embedPrivate->mEventListener->GetContextInfo();
     if (ctx_menu)
       ctx_menu->CheckDomImageElement((nsIDOMNode*)node, imgSrc, width, height);
   }
 
+  if (title) {
+    EmbedContextMenuInfo * ctx_menu = embedPrivate->mEventListener->GetContextInfo();
+    if (ctx_menu)
+      *title = NEW_TOOLKIT_STRING(ctx_menu->GetCtxDocTitle());
+  }
+
   if (file_size && location && *location != nsnull) {
     nsCOMPtr<nsICacheEntryDescriptor> descriptor;
     nsresult rv;
     rv = embedPrivate->GetCacheEntry("HTTP", *location, nsICache::ACCESS_READ, PR_FALSE, getter_AddRefs(descriptor));
     if (descriptor) {
       rv = descriptor->GetDataSize(file_size);
     }
   }
 #endif
 
   return TRUE;
 }
+
+gint
+gtk_moz_embed_get_shistory_list(GtkMozEmbed *embed, GtkMozHistoryItem **GtkHI,
+                                guint type)
+{
+  g_return_val_if_fail ((embed != NULL), 0);
+  g_return_val_if_fail (GTK_IS_MOZ_EMBED(embed), 0);
+  EmbedPrivate *embedPrivate;
+  gint count = 0;
+
+  embedPrivate = (EmbedPrivate *)embed->data;
+  if (embedPrivate)
+    embedPrivate->GetSHistoryList(GtkHI, (GtkMozEmbedSessionHistory)type, &count);
+  return count;
+}
+
+gint
+gtk_moz_embed_get_shistory_index(GtkMozEmbed *embed)
+{
+  g_return_val_if_fail ((embed != NULL), -1);
+  g_return_val_if_fail (GTK_IS_MOZ_EMBED(embed), -1);
+
+  PRInt32 curIndex;
+  EmbedPrivate *embedPrivate;
+  
+  embedPrivate = (EmbedPrivate *)embed->data;
+  if (embedPrivate->mSessionHistory)
+    embedPrivate->mSessionHistory->GetIndex(&curIndex);
+
+  return (gint)curIndex;
+}
+
+void
+gtk_moz_embed_shistory_goto_index(GtkMozEmbed *embed, gint index)
+{
+  g_return_if_fail (embed != NULL);
+  g_return_if_fail (GTK_IS_MOZ_EMBED(embed));
+
+  EmbedPrivate *embedPrivate;
+
+  embedPrivate = (EmbedPrivate *)embed->data;
+  if (embedPrivate->mNavigation)
+    embedPrivate->mNavigation->GotoIndex(index);
+}
+
+gboolean
+gtk_moz_embed_get_server_cert(GtkMozEmbed *embed, gpointer *aCert, gpointer context)
+{
+  g_return_val_if_fail(embed != NULL, FALSE);
+  g_return_val_if_fail(GTK_IS_MOZ_EMBED(embed), FALSE);
+
+  nsIWebBrowser *webBrowser = nsnull;
+  gtk_moz_embed_get_nsIWebBrowser(GTK_MOZ_EMBED(embed), &webBrowser);
+  if (!webBrowser) return FALSE;
+
+  nsCOMPtr<nsIDocShell> docShell(do_GetInterface((nsISupports*)webBrowser));
+  if (!docShell) return FALSE;
+
+  nsCOMPtr<nsISecureBrowserUI> mSecureUI;
+  docShell->GetSecurityUI(getter_AddRefs(mSecureUI));
+  if (!mSecureUI) return FALSE;
+
+  nsCOMPtr<nsISSLStatusProvider> mSecureProvider = do_QueryInterface(mSecureUI);
+  if (!mSecureProvider) return FALSE;
+
+  nsCOMPtr<nsISSLStatus> SSLStatus;
+  mSecureProvider->GetSSLStatus(getter_AddRefs(SSLStatus));
+  if (!SSLStatus) return FALSE;
+
+  nsCOMPtr<nsIX509Cert> serverCert;
+  SSLStatus->GetServerCert(getter_AddRefs(serverCert));
+  if (!serverCert) return FALSE;
+
+  *aCert = serverCert;
+  return TRUE;
+}
--- a/embedding/browser/gtk/src/gtkmozembed_common.cpp
+++ b/embedding/browser/gtk/src/gtkmozembed_common.cpp
@@ -63,27 +63,27 @@
 #include "nsIPermissionManager.h"
 #include "nsNetCID.h"
 #include "nsICookie.h"
 #include "nsIX509Cert.h"
 // for strings
 #ifdef MOZILLA_INTERNAL_API
 #include "nsXPIDLString.h"
 #include "nsReadableUtils.h"
+#include "nsString.h"
 #else
 #include "nsStringAPI.h"
 #include "nsComponentManagerUtils.h"
 #include "nsServiceManagerUtils.h"
 #endif
 // for plugins
 #include "nsIDOMNavigator.h"
 #include "nsIDOMPluginArray.h"
 #include "nsIDOMPlugin.h"
 #include <plugin/nsIPluginHost.h>
-#include "nsString.h"
 #include "nsIDOMMimeType.h"
 #include "nsIObserverService.h"
 
 //for security
 #include "nsIWebProgressListener.h"
 
 //for cache
 #include "nsICacheService.h"
@@ -329,46 +329,46 @@ gtk_moz_embed_common_destroy(GtkObject *
     embed->data = NULL;
   }
 }
 
 GtkWidget *
 gtk_moz_embed_common_new(void)
 {
   GtkWidget *widget = (GtkWidget*) gtk_type_new(gtk_moz_embed_common_get_type());
-  gtk_widget_set_name (widget, "gtkmozembedcommon");
+  gtk_widget_set_name(widget, "gtkmozembedcommon");
   return (GtkWidget *) widget;
 }
 
 gboolean
 gtk_moz_embed_common_set_pref(GtkType type, gchar *name, gpointer value)
 {
   g_return_val_if_fail (name != NULL, FALSE);
 
   nsCOMPtr<nsIPref> pref = do_GetService(NS_PREF_CONTRACTID);
 
   if (pref) {
     nsresult rv = NS_ERROR_FAILURE;
     switch (type) {
     case GTK_TYPE_BOOL:
       {
         /* I doubt this cast pair is correct */
-        rv = pref->SetBoolPref (name, !!*(int*)value);
+        rv = pref->SetBoolPref(name, !!*(int*)value);
         break;
       }
     case GTK_TYPE_INT:
       {
         /* I doubt this cast pair is correct */
-        rv = pref->SetIntPref (name, *(int*)value);
+        rv = pref->SetIntPref(name, *(int*)value);
         break;
       }
     case GTK_TYPE_STRING:
       {
         g_return_val_if_fail (value, FALSE);
-        rv = pref->SetCharPref (name, (gchar*)value);
+        rv = pref->SetCharPref(name, (gchar*)value);
         break;
       }
     default:
       break;
     }
     return NS_SUCCEEDED(rv);
   }
   return FALSE;
@@ -381,27 +381,27 @@ gtk_moz_embed_common_get_pref(GtkType ty
 
   nsCOMPtr<nsIPref> pref = do_GetService(NS_PREF_CONTRACTID);
 
   nsresult rv = NS_ERROR_FAILURE;
   if (pref){
     switch (type) {
     case GTK_TYPE_BOOL:
       {
-        rv = pref->GetBoolPref (name, (gboolean*)value);
+        rv = pref->GetBoolPref(name, (gboolean*)value);
         break;
       }
     case GTK_TYPE_INT:
       {
-        rv = pref->GetIntPref (name, (gint*)value);
+        rv = pref->GetIntPref(name, (gint*)value);
         break;
       }
     case GTK_TYPE_STRING:
       {
-        rv = pref->GetCharPref (name, (gchar**)value);
+        rv = pref->GetCharPref(name, (gchar**)value);
         break;
       }
     default:
       break;
     }
     return NS_SUCCEEDED(rv);
   }
   return FALSE;
@@ -427,37 +427,37 @@ gtk_moz_embed_common_get_logins(const ch
   nsCOMPtr<nsISimpleEnumerator> passwordEnumerator;
   nsresult result = passwordManager->GetEnumerator(getter_AddRefs(passwordEnumerator));
   PRBool enumResult;
   for (passwordEnumerator->HasMoreElements(&enumResult) ;
        enumResult == PR_TRUE ;
        passwordEnumerator->HasMoreElements(&enumResult))
   {
     nsCOMPtr<nsIPassword> nsPassword;
-    result = passwordEnumerator->GetNext (getter_AddRefs(nsPassword));
+    result = passwordEnumerator->GetNext(getter_AddRefs(nsPassword));
     if (NS_FAILED(result)) {
       /* this almost certainly leaks logins */
       return ret;
     }
     nsCString host;
-    nsPassword->GetHost (host);
+    nsPassword->GetHost(host);
     nsCString nsCURI(uri);
     if (uri) {
-      if (!StringBeginsWith (nsCURI, host)
-          // && !StringBeginsWith (host, nsCURI)
+      if (!StringBeginsWith(nsCURI, host)
+          // && !StringBeginsWith(host, nsCURI)
           )
         continue;
     } else if (!passwordManager->IsEqualToLastHostQuery(host))
       continue;
 
     if (list) {
       nsString unicodeName;
       nsString unicodePassword;
-      nsPassword->GetUser (unicodeName);
-      nsPassword->GetPassword (unicodePassword);
+      nsPassword->GetUser(unicodeName);
+      nsPassword->GetPassword(unicodePassword);
       GtkMozLogin * login = g_new0(GtkMozLogin, 1);
       UNACCEPTABLE_CRASHY_GLIB_ALLOCATION(login);
       login->user = ToNewUTF8String(unicodeName);
       ALLOC_NOT_CHECKED(login->user);
       login->pass = ToNewUTF8String(unicodePassword);
       ALLOC_NOT_CHECKED(login->pass);
       login->host = NS_strdup(host.get());
       ALLOC_NOT_CHECKED(login->host);
@@ -480,39 +480,39 @@ gtk_moz_embed_common_remove_passwords(co
   } else {
     passwordManager->RemovePasswords(host, user);
   }
 #endif
   return TRUE;
 }
 
 gint
-gtk_moz_embed_common_get_history_list (GtkMozHistoryItem **GtkHI)
+gtk_moz_embed_common_get_history_list(GtkMozHistoryItem **GtkHI)
 {
   gint count = 0;
   EmbedGlobalHistory *history = EmbedGlobalHistory::GetInstance();
   history->GetContentList(GtkHI, &count);
   return count;
 }
 
 gint
-gtk_moz_embed_common_remove_history (gchar *url, gint time) {
+gtk_moz_embed_common_remove_history(gchar *url, gint time) {
   nsresult rv;
   // The global history service
   nsCOMPtr<nsIGlobalHistory2> globalHistory(do_GetService("@mozilla.org/browser/global-history;2"));
   if (!globalHistory) return NS_ERROR_NULL_POINTER;
   // The browser history interface
   nsCOMPtr<nsIObserver> myHistory = do_QueryInterface(globalHistory, &rv);
   if (!myHistory) return NS_ERROR_NULL_POINTER ;
   if (!url)
     myHistory->Observe(nsnull, "RemoveEntries", nsnull);
   else {
     EmbedGlobalHistory *history = EmbedGlobalHistory::GetInstance();
-    PRUnichar *uniurl = LocaleToUnicode(url);
-    rv = history->RemoveEntries (uniurl, time);
+    PRUnichar *uniurl = ToNewUnicode(NS_ConvertUTF8toUTF16(url));
+    rv = history->RemoveEntries(uniurl, time);
     NS_Free(uniurl);
   }
   return 1;
 }
 
 GSList*
 gtk_moz_embed_common_get_cookie_list(void)
 {
@@ -549,54 +549,54 @@ gtk_moz_embed_common_get_cookie_list(voi
       c->path = g_strdup(g_strconcat("http://",c->domain,"/",NULL));
     cookies = g_slist_prepend(cookies, c);
   }
   cookies = g_slist_reverse(cookies);
   return cookies;
 }
 
 gint
-gtk_moz_embed_common_delete_all_cookies (GSList *deletedCookies)
+gtk_moz_embed_common_delete_all_cookies(GSList *deletedCookies)
 {
   nsCOMPtr<nsIPermissionManager> permissionManager =
     do_GetService(NS_PERMISSIONMANAGER_CONTRACTID);
 
   if (!permissionManager)
     return 1;
 
-  permissionManager->RemoveAll ();
+  permissionManager->RemoveAll();
 
   if (!deletedCookies)
     return 1;
 
   nsCOMPtr<nsICookieManager> cookieManager =
     do_GetService(NS_COOKIEMANAGER_CONTRACTID);
 
   if (!cookieManager)
     return 1;
   cookieManager->RemoveAll();
 
-  g_slist_free (deletedCookies);
-    return 0;//False in GWebStatus means OK, as opposed to gboolean in C
+  g_slist_free(deletedCookies);
+  return 0;//False in GWebStatus means OK, as opposed to gboolean in C
 }
 
 unsigned char *
 gtk_moz_embed_common_nsx509_to_raw(void *nsIX509Ptr, guint *len)
 {
   if (!nsIX509Ptr)
     return NULL;
   unsigned char *data;
   ((nsIX509Cert*)nsIX509Ptr)->GetRawDER(len, (PRUint8 **)&data);
   if (!data)
     return NULL;
   return data;
 }
 
 gint
-gtk_moz_embed_common_get_plugins_list (GList **pluginArray)
+gtk_moz_embed_common_get_plugins_list(GList **pluginArray)
 {
   nsresult rv;
   nsCOMPtr<nsIPluginManager> pluginMan =
     do_GetService(kPluginManagerCID, &rv);
   if (NS_FAILED(rv)) {
     g_print("Could not get the plugin manager\n");
     return -1;
   }
@@ -620,55 +620,67 @@ gtk_moz_embed_common_get_plugins_list (G
 
   rv = pluginHost->GetPlugins(aLength, aItems);
   if (NS_FAILED(rv)) {
     delete [] aItems;
     return -1;
   }
 
   nsString string;
-  for (int aIndex = 0; aIndex < (gint) aLength; aIndex++)
+  for (int plugin_index = 0; plugin_index < (gint) aLength; plugin_index++)
   {
     GtkMozPlugin *list_item = g_new0(GtkMozPlugin, 1);
     UNACCEPTABLE_CRASHY_GLIB_ALLOCATION(list_item);
 
-    rv = aItems[aIndex]->GetName(string);
+    rv = aItems[plugin_index]->GetName(string);
     if (!NS_FAILED(rv))
       list_item->title = g_strdup(NS_ConvertUTF16toUTF8(string).get());
 
-    aItems[aIndex]->GetFilename(string);
+    aItems[plugin_index]->GetFilename(string);
     if (!NS_FAILED(rv))
       list_item->path = g_strdup(NS_ConvertUTF16toUTF8(string).get());
 
     nsCOMPtr<nsIDOMMimeType> mimeType;
-    rv = aItems[aIndex]->Item(aIndex, getter_AddRefs(mimeType));
+    PRUint32 mime_count = 0;
+    rv = aItems[plugin_index]->GetLength(&mime_count);
     if (NS_FAILED(rv))
       continue;
-
-    rv = mimeType->GetDescription(string);
-    if (!NS_FAILED(rv))
-      list_item->type = g_strdup(NS_ConvertUTF16toUTF8(string).get());
+    
+    nsString single_mime;
+    string.SetLength(0);
+    for (int mime_index = 0; mime_index < mime_count; ++mime_index) {
+      rv = aItems[plugin_index]->Item(mime_index, getter_AddRefs(mimeType));
+      if (NS_FAILED(rv))
+        continue;
+      rv = mimeType->GetDescription(single_mime);
+      if (!NS_FAILED(rv)) {
+        string.Append(single_mime);
+        string.AppendLiteral(";");
+      }
+    }
+    
+    list_item->type = g_strdup(NS_ConvertUTF16toUTF8(string).get());
     if (!NS_FAILED(rv))
       *pluginArray = g_list_append(*pluginArray, list_item);
   }
   delete [] aItems;
   return (gint)aLength;
 }
 
 void
-gtk_moz_embed_common_reload_plugins ()
+gtk_moz_embed_common_reload_plugins()
 {
   nsresult rv;
   nsCOMPtr<nsIPluginManager> pluginMan =
     do_GetService(kPluginManagerCID, &rv);
   pluginMan->ReloadPlugins(PR_TRUE); //FIXME XXX MEMLEAK
 }
 
 guint
-gtk_moz_embed_common_get_security_mode (guint sec_state)
+gtk_moz_embed_common_get_security_mode(guint sec_state)
 {
   GtkMozEmbedSecurityMode sec_mode;
 
   switch (sec_state) {
     case nsIWebProgressListener::STATE_IS_INSECURE:
       sec_mode = GTK_MOZ_EMBED_NO_SECURITY;
       //g_print("GTK_MOZ_EMBED_NO_SECURITY\n");
       break;
@@ -699,17 +711,17 @@ gtk_moz_embed_common_get_security_mode (
   return sec_mode;
 }
 
 gint
 gtk_moz_embed_common_clear_cache(void)
 {
   nsCacheStoragePolicy storagePolicy;
 
-  nsCOMPtr<nsICacheService> cacheService = do_GetService (NS_CACHESERVICE_CONTRACTID);
+  nsCOMPtr<nsICacheService> cacheService = do_GetService(NS_CACHESERVICE_CONTRACTID);
 
   if (cacheService)
   {
     //clean disk cache and memory cache
     storagePolicy = nsICache::STORE_ANYWHERE;
     cacheService->EvictEntries(storagePolicy);
     return 0;
   }
--- a/embedding/browser/gtk/src/gtkmozembed_common.h
+++ b/embedding/browser/gtk/src/gtkmozembed_common.h
@@ -34,16 +34,17 @@
  * decision by deleting the provisions above and replace them with the notice
  * and other provisions required by the GPL or the LGPL. If you do not delete
  * the provisions above, a recipient may use your version of this file under
  * the terms of any one of the MPL, the GPL or the LGPL.
  *
  * ***** END LICENSE BLOCK ***** */
 #ifndef gtkmozembed_common_h
 #define gtkmozembed_common_h
+#include "gtkmozembed.h"
 #ifdef __cplusplus
 extern "C" {
 #endif /* __cplusplus */
 #include <stddef.h>
 #include <gtk/gtk.h>
 #ifdef MOZILLA_CLIENT
 #include "nscore.h"
 #else // MOZILLA_CLIENT
@@ -135,26 +136,16 @@ typedef enum
 {
   GTK_MOZ_EMBED_NO_SECURITY = 0,
   GTK_MOZ_EMBED_LOW_SECURITY,
   GTK_MOZ_EMBED_MEDIUM_SECURITY,
   GTK_MOZ_EMBED_HIGH_SECURITY,
   GTK_MOZ_EMBED_UNKNOWN_SECURITY
 } GtkMozEmbedSecurityMode;
 
-/** @struct GtkWebHistoryItem.
-  * Defines a web history item.
-  */
-typedef struct _GtkMozHistoryItem GtkMozHistoryItem;
-struct _GtkMozHistoryItem
-{
-    const gchar *title; /** < URL title */
-    const gchar *url;   /** < URL */
-    long accessed;      /** < The last time that the URL was accessed */
-};
 typedef struct _GtkMozCookieList GtkMozCookieList;
 struct _GtkMozCookieList
 {
     gchar *domain; /** < The domain's name */
     gchar *name;   /** < The cookie's name */
     gchar *value;  /** < The cookie's value */
     gchar *path;   /** < The cookie's path */
 };
@@ -165,19 +156,19 @@ struct _GtkMozEmbedCookie
     gboolean accept;
 };
 /** @struct GtkMozPlugin.
  * Defines a Mozilla Plugin.
  */
 typedef struct _GtkMozPlugin GtkMozPlugin;
 struct _GtkMozPlugin
 {
-    const gchar *title;  /** < Plugin title */
-    const gchar *path;   /** < Plugin path */
-    const gchar *type;   /** < Plugin type */
+    gchar *title;  /** < Plugin title */
+    gchar *path;   /** < Plugin path */
+    gchar *type;   /** < Plugin type */
     gboolean isDisabled; /** < is plugin enabled */
 };
 
 typedef struct _GtkMozLogin GtkMozLogin;
 struct _GtkMozLogin
 {
     const gchar *user; /** < Plugin title */
     const gchar *pass; /** < Plugin path */
--- a/embedding/browser/gtk/src/gtkmozembed_download.cpp
+++ b/embedding/browser/gtk/src/gtkmozembed_download.cpp
@@ -1,10 +1,10 @@
 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
-/* vim:set ts=2 sw=4 sts=2 tw=80 et cindent: */
+/* vim:set ts=2 sw=2 sts=2 tw=80 et cindent: */
 /* ***** 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/
  *
@@ -32,39 +32,43 @@
  * under the terms of either the GPL or the LGPL, and not to allow others to
  * use your version of this file under the terms of the MPL, indicate your
  * decision by deleting the provisions above and replace them with the notice
  * and other provisions required by the GPL or the LGPL. If you do not delete
  * the provisions above, a recipient may use your version of this file under
  * the terms of any one of the MPL, the GPL or the LGPL.
  *
  * ***** END LICENSE BLOCK ***** */
+
 #include <stdio.h>
 #include "gtkmozembed.h"
 #include "gtkmozembed_download.h"
 #include "gtkmozembedprivate.h"
 #include "gtkmozembed_internal.h"
 #include "EmbedPrivate.h"
 #include "EmbedWindow.h"
 #include "EmbedDownloadMgr.h"
 // so we can do our get_nsIWebBrowser later...
 #include "nsIWebBrowser.h"
+
 // for strings
 #ifdef MOZILLA_INTERNAL_API
 #include "nsXPIDLString.h"
 #include "nsReadableUtils.h"
 #else
 #include "nsStringAPI.h"
 #endif
+
 #ifdef MOZ_WIDGET_GTK2
 #include "gtkmozembedmarshal.h"
 #define NEW_TOOLKIT_STRING(x) g_strdup(NS_ConvertUTF16toUTF8(x).get())
 #define GET_TOOLKIT_STRING(x) NS_ConvertUTF16toUTF8(x).get()
 #define GET_OBJECT_CLASS_TYPE(x) G_OBJECT_CLASS_TYPE(x)
 #endif /* MOZ_WIDGET_GTK2 */
+
 #ifdef MOZ_WIDGET_GTK
 // so we can get callbacks from the mozarea
 #include <gtkmozarea.h>
 // so we get the right marshaler for gtk 1.2
 #define gtkmozembed_VOID__INT_UINT \
   gtk_marshal_NONE__INT_INT
 #define gtkmozembed_VOID__STRING_INT_INT \
   gtk_marshal_NONE__POINTER_INT_INT
@@ -76,28 +80,27 @@
   gtk_marshal_BOOL__POINTER
 #define gtkmozembed_VOID__INT_INT_BOOLEAN \
   gtk_marshal_NONE__INT_INT_BOOLEAN
 #define G_SIGNAL_TYPE_STATIC_SCOPE 0
 #define NEW_TOOLKIT_STRING(x) g_strdup(NS_LossyConvertUTF16toASCII(x).get())
 #define GET_TOOLKIT_STRING(x) NS_LossyConvertUTF16toASCII(x).get()
 #define GET_OBJECT_CLASS_TYPE(x) (GTK_OBJECT_CLASS(x)->type)
 #endif /* MOZ_WIDGET_GTK */
-static void gtk_moz_embed_download_set_lastest_object (GtkObject *o);
+
+static void gtk_moz_embed_download_set_latest_object(GtkObject *o);
 static GtkObject *latest_download_object = nsnull;
+
 // class and instance initialization
 guint moz_embed_download_signals[DOWNLOAD_LAST_SIGNAL] = { 0 };
-static void
-gtk_moz_embed_download_class_init(GtkMozEmbedDownloadClass *klass);
-static void
-gtk_moz_embed_download_init(GtkMozEmbedDownload *embed);
-static void
-gtk_moz_embed_download_destroy(GtkObject *object);
-GtkObject *
-gtk_moz_embed_download_new(void);
+static void gtk_moz_embed_download_class_init(GtkMozEmbedDownloadClass *klass);
+static void gtk_moz_embed_download_init(GtkMozEmbedDownload *embed);
+static void gtk_moz_embed_download_destroy(GtkObject *object);
+GtkObject * gtk_moz_embed_download_new(void);
+
 // GtkObject + class-related functions
 GtkType
 gtk_moz_embed_download_get_type(void)
 {
   static GtkType moz_embed_download_type = 0;
   if (!moz_embed_download_type)
   {
     static const GtkTypeInfo moz_embed_download_info =
@@ -110,156 +113,201 @@ gtk_moz_embed_download_get_type(void)
       0,
       0,
       0
     };
     moz_embed_download_type = gtk_type_unique(GTK_TYPE_OBJECT, &moz_embed_download_info);
   }
   return moz_embed_download_type;
 }
+
 static void
 gtk_moz_embed_download_class_init(GtkMozEmbedDownloadClass *klass)
 {
   GtkObjectClass     *object_class;
   object_class    = GTK_OBJECT_CLASS(klass);
   object_class->destroy = gtk_moz_embed_download_destroy;
+
   // set up our signals
   moz_embed_download_signals[DOWNLOAD_STARTED_SIGNAL] =
     gtk_signal_new("started",
-       GTK_RUN_FIRST,
-       GET_OBJECT_CLASS_TYPE(klass),
-       GTK_SIGNAL_OFFSET(GtkMozEmbedDownloadClass,
-             started),
-       gtk_marshal_NONE__POINTER,
-       GTK_TYPE_NONE, 1,
+                   GTK_RUN_FIRST,
+                   GET_OBJECT_CLASS_TYPE(klass),
+                   GTK_SIGNAL_OFFSET(GtkMozEmbedDownloadClass, started),
+                   gtk_marshal_NONE__POINTER,
+                   GTK_TYPE_NONE,
+                   1,
                    G_TYPE_POINTER);
+
   moz_embed_download_signals[DOWNLOAD_COMPLETED_SIGNAL] =
     gtk_signal_new("completed",
-       GTK_RUN_FIRST,
-       GET_OBJECT_CLASS_TYPE(klass),
-       GTK_SIGNAL_OFFSET(GtkMozEmbedDownloadClass,
-             completed),
-       gtk_marshal_NONE__NONE,
-       GTK_TYPE_NONE, 0);
+                   GTK_RUN_FIRST,
+                   GET_OBJECT_CLASS_TYPE(klass),
+                   GTK_SIGNAL_OFFSET(GtkMozEmbedDownloadClass, completed),
+                   gtk_marshal_NONE__NONE,
+                   GTK_TYPE_NONE, 0);
+
   moz_embed_download_signals[DOWNLOAD_FAILED_SIGNAL] =
     gtk_signal_new("error",
-       GTK_RUN_FIRST,
-       GET_OBJECT_CLASS_TYPE(klass),
-       GTK_SIGNAL_OFFSET(GtkMozEmbedDownloadClass,
-             error),
-       gtk_marshal_NONE__NONE,
-       GTK_TYPE_NONE, 0);
+                   GTK_RUN_FIRST,
+                   GET_OBJECT_CLASS_TYPE(klass),
+                   GTK_SIGNAL_OFFSET(GtkMozEmbedDownloadClass, error),
+                   gtk_marshal_NONE__NONE,
+                   GTK_TYPE_NONE, 0);
+
   moz_embed_download_signals[DOWNLOAD_DESTROYED_SIGNAL] =
     gtk_signal_new("aborted",
-       GTK_RUN_FIRST,
-       GET_OBJECT_CLASS_TYPE(klass),
-       GTK_SIGNAL_OFFSET(GtkMozEmbedDownloadClass,
-             aborted),
-       gtk_marshal_NONE__NONE,
-       GTK_TYPE_NONE, 0);
+                   GTK_RUN_FIRST,
+                   GET_OBJECT_CLASS_TYPE(klass),
+                   GTK_SIGNAL_OFFSET(GtkMozEmbedDownloadClass, aborted),
+                   gtk_marshal_NONE__NONE,
+                   GTK_TYPE_NONE, 0);
+
   moz_embed_download_signals[DOWNLOAD_PROGRESS_SIGNAL] =
     gtk_signal_new("progress",
-       GTK_RUN_FIRST,
-       GET_OBJECT_CLASS_TYPE(klass),
-       GTK_SIGNAL_OFFSET(GtkMozEmbedDownloadClass,
-             progress),
-       gtkmozembed_VOID__ULONG_ULONG_ULONG,
-       GTK_TYPE_NONE,
-       3,
-       G_TYPE_ULONG,
-       G_TYPE_ULONG,
-       G_TYPE_ULONG);
+                   GTK_RUN_FIRST,
+                   GET_OBJECT_CLASS_TYPE(klass),
+                   GTK_SIGNAL_OFFSET(GtkMozEmbedDownloadClass, progress),
+                   gtkmozembed_VOID__ULONG_ULONG_ULONG,
+                   GTK_TYPE_NONE,
+                   3,
+                   G_TYPE_ULONG,
+                   G_TYPE_ULONG,
+                   G_TYPE_ULONG);
+
 #ifdef MOZ_WIDGET_GTK
   gtk_object_class_add_signals(object_class, moz_embed_download_signals,
-             DOWNLOAD_LAST_SIGNAL);
+                               DOWNLOAD_LAST_SIGNAL);
 #endif /* MOZ_WIDGET_GTK */
 }
+
 static void
 gtk_moz_embed_download_init(GtkMozEmbedDownload *download)
 {
   // this is a placeholder for later in case we need to stash data at
   // a later data and maintain backwards compatibility.
   download->data = nsnull;
   EmbedDownload *priv = new EmbedDownload();
   download->data = priv;
 }
+
 static void
 gtk_moz_embed_download_destroy(GtkObject *object)
 {
-    GtkMozEmbedDownload  *embed;
-    EmbedDownload *downloadPrivate;
-    g_return_if_fail(object != NULL);
-    g_return_if_fail(GTK_IS_MOZ_EMBED_DOWNLOAD(object));
-    embed = GTK_MOZ_EMBED_DOWNLOAD(object);
-    downloadPrivate = (EmbedDownload *)embed->data;
-    if (downloadPrivate) {
-        delete downloadPrivate;
-        embed->data = NULL;
-    }
+  g_return_if_fail(object != NULL);
+  g_return_if_fail(GTK_IS_MOZ_EMBED_DOWNLOAD(object));
+
+  GtkMozEmbedDownload  *embed;
+  EmbedDownload *downloadPrivate;
+
+  embed = GTK_MOZ_EMBED_DOWNLOAD(object);
+  downloadPrivate = (EmbedDownload *)embed->data;
+
+  if (downloadPrivate) {
+    delete downloadPrivate;
+    embed->data = NULL;
+  }
 }
+
 GtkObject *
 gtk_moz_embed_download_new(void)
 {
-  GtkObject *instance = (GtkObject *) gtk_type_new (gtk_moz_embed_download_get_type());
-  gtk_moz_embed_download_set_lastest_object (instance);
+  GtkObject *instance = (GtkObject *) gtk_type_new(gtk_moz_embed_download_get_type());
+  gtk_moz_embed_download_set_latest_object(instance);
+
   return instance;
 }
+
 GtkObject *
-gtk_moz_embed_download_get_lastest_object (void)
+gtk_moz_embed_download_get_latest_object(void)
 {
   return latest_download_object;
 }
+
 static void
-gtk_moz_embed_download_set_lastest_object (GtkObject *obj)
+gtk_moz_embed_download_set_latest_object(GtkObject *obj)
 {
   latest_download_object = obj;
   return ;
 }
-void gtk_moz_embed_download_do_command (GtkMozEmbedDownload *item, guint command)
+
+void
+gtk_moz_embed_download_do_command(GtkMozEmbedDownload *item, guint command)
 {
-  g_return_if_fail(item);
   EmbedDownload *download_priv = (EmbedDownload *) item->data;
-  if (!download_priv) return ;
+
+  if (!download_priv)
+    return;
+
   if (command == GTK_MOZ_EMBED_DOWNLOAD_CANCEL) {
-    // workaround to avoid crashs if download is 0%.
-    if (download_priv->downloaded_size != -1)
-        download_priv->launcher->Cancel (GTK_MOZ_EMBED_STATUS_FAILED_USERCANCELED);
-    download_priv->launcher->SetWebProgressListener (nsnull);
-  } else if (command == GTK_MOZ_EMBED_DOWNLOAD_RESUME) {
-    download_priv->request->Resume ();
-    download_priv->isPaused = FALSE;
-  } else if (command == GTK_MOZ_EMBED_DOWNLOAD_PAUSE) {
-    download_priv->request->Suspend ();
-    download_priv->isPaused = TRUE;
-  } else if (command == GTK_MOZ_EMBED_DOWNLOAD_RELOAD) {
+    download_priv->launcher->Cancel(GTK_MOZ_EMBED_STATUS_FAILED_USERCANCELED);
+    download_priv->launcher->SetWebProgressListener(nsnull);
+
+    return;
+  }
+
+  if (command == GTK_MOZ_EMBED_DOWNLOAD_RESUME) {
+    download_priv->request->Resume();
+    download_priv->is_paused = FALSE;
+
+    return;
+  }
+
+  if (command == GTK_MOZ_EMBED_DOWNLOAD_PAUSE) {
+    if (download_priv->request) {
+      download_priv->request->Suspend();
+      download_priv->is_paused = TRUE;
+    }
+
+    return;
+  }
+
+  if (command == GTK_MOZ_EMBED_DOWNLOAD_RELOAD) {
     if (download_priv->gtkMozEmbedParentWidget) {}
   }
   // FIXME: missing GTK_MOZ_EMBED_DOWNLOAD_STORE and GTK_MOZ_EMBED_DOWNLOAD_RESTORE implementation.
 }
-gchar * gtk_moz_embed_download_get_file_name (GtkMozEmbedDownload *item)
+
+gchar*
+gtk_moz_embed_download_get_file_name(GtkMozEmbedDownload *item)
 {
-  g_return_val_if_fail(item, nsnull);
   EmbedDownload *download_priv = (EmbedDownload *) item->data;
-  if (!download_priv) return nsnull;
+
+  if (!download_priv)
+    return nsnull;
+
   return (gchar *) download_priv->file_name;
 }
-gchar * gtk_moz_embed_download_get_url (GtkMozEmbedDownload *item)
+
+gchar*
+gtk_moz_embed_download_get_url(GtkMozEmbedDownload *item)
 {
-  g_return_val_if_fail(item, nsnull);
   EmbedDownload *download_priv = (EmbedDownload *) item->data;
-  if (!download_priv) return nsnull;
+
+  if (!download_priv)
+    return nsnull;
+
   // FIXME : 'server' is storing the wrong value. See EmbedDownloadMgr.cpp l. 189.
   return (gchar *) download_priv->server;
 }
-glong gtk_moz_embed_download_get_progress (GtkMozEmbedDownload *item)
+
+glong
+gtk_moz_embed_download_get_progress(GtkMozEmbedDownload *item)
 {
-  g_return_val_if_fail(item, -1);
   EmbedDownload *download_priv = (EmbedDownload *) item->data;
-  if (!download_priv) return -1;
+
+  if (!download_priv)
+    return -1;
+
   return (glong) download_priv->downloaded_size;
 }
-glong gtk_moz_embed_download_get_file_size (GtkMozEmbedDownload *item)
+
+glong
+gtk_moz_embed_download_get_file_size(GtkMozEmbedDownload *item)
 {
-  g_return_val_if_fail(item, -1);
   EmbedDownload *download_priv = (EmbedDownload *) item->data;
-  if (!download_priv) return -1;
+
+  if (!download_priv)
+    return -1;
+
   return (glong) download_priv->file_size;
 }
+
--- a/embedding/browser/gtk/src/gtkmozembed_download.h
+++ b/embedding/browser/gtk/src/gtkmozembed_download.h
@@ -30,16 +30,17 @@
  * under the terms of either the GPL or the LGPL, and not to allow others to
  * use your version of this file under the terms of the MPL, indicate your
  * decision by deleting the provisions above and replace them with the notice
  * and other provisions required by the GPL or the LGPL. If you do not delete
  * the provisions above, a recipient may use your version of this file under
  * the terms of any one of the MPL, the GPL or the LGPL.
  *
  * ***** END LICENSE BLOCK ***** */
+
 #ifndef gtkmozembed_download_h
 #define gtkmozembed_download_h
 #ifdef __cplusplus
 extern "C" {
 #endif /* __cplusplus */
 #include <stddef.h>
 #include <gtk/gtk.h>
 #ifdef MOZILLA_CLIENT
@@ -64,53 +65,59 @@ extern "C" {
   extern name##Type name NS_HIDDEN;
 #else // XPCOM_GLUE
 #ifdef _IMPL_GTKMOZEMBED
 #define GTKMOZEMBED_API(type, name, params) NS_EXPORT_(type) name params;
 #else
 #define GTKMOZEMBED_API(type,name, params) NS_IMPORT_(type) name params;
 #endif
 #endif // XPCOM_GLUE
+
 #define GTK_TYPE_MOZ_EMBED_DOWNLOAD             (gtk_moz_embed_download_get_type())
 #define GTK_MOZ_EMBED_DOWNLOAD(obj)             GTK_CHECK_CAST((obj), GTK_TYPE_MOZ_EMBED_DOWNLOAD, GtkMozEmbedDownload)
 #define GTK_MOZ_EMBED_DOWNLOAD_CLASS(klass)     GTK_CHECK_CLASS_CAST((klass), GTK_TYPE_MOZ_EMBED_DOWNLOAD, GtkMozEmbedDownloadClass)
 #define GTK_IS_MOZ_EMBED_DOWNLOAD(obj)          GTK_CHECK_TYPE((obj), GTK_TYPE_MOZ_EMBED_DOWNLOAD)
 #define GTK_IS_MOZ_EMBED_DOWNLOAD_CLASS(klass)  GTK_CHECK_CLASS_TYPE((klass), GTK_TYPE_MOZ_EMBED_DOWNLOAD)
+
 typedef struct _GtkMozEmbedDownload      GtkMozEmbedDownload;
 typedef struct _GtkMozEmbedDownloadClass GtkMozEmbedDownloadClass;
+
 struct _GtkMozEmbedDownload
 {
   GtkObject  object;
   void *data;
 };
+
 struct _GtkMozEmbedDownloadClass
 {
   GtkObjectClass parent_class;
   void (*started) (GtkMozEmbedDownload* item, gchar **file_name_with_path);
   void (*completed) (GtkMozEmbedDownload* item);
   void (*error) (GtkMozEmbedDownload* item);
   void (*aborted) (GtkMozEmbedDownload* item);
   void (*progress) (GtkMozEmbedDownload* item, gulong downloaded_bytes, gulong total_bytes, gdouble kbps);
 };
+
 typedef enum
 {
   GTK_MOZ_EMBED_DOWNLOAD_RESUME,
   GTK_MOZ_EMBED_DOWNLOAD_CANCEL,
   GTK_MOZ_EMBED_DOWNLOAD_PAUSE,
   GTK_MOZ_EMBED_DOWNLOAD_RELOAD,
   GTK_MOZ_EMBED_DOWNLOAD_STORE,
   GTK_MOZ_EMBED_DOWNLOAD_RESTORE
 } GtkMozEmbedDownloadActions;
-GTKMOZEMBED_API(GtkType,             gtk_moz_embed_download_get_type, (void))
-GTKMOZEMBED_API(GtkObject *,         gtk_moz_embed_download_new,      (void))
-GTKMOZEMBED_API(GtkObject *,         gtk_moz_embed_download_get_lastest_object, (void))
-GTKMOZEMBED_API(void,                gtk_moz_embed_download_do_command , (GtkMozEmbedDownload *item, guint command))
-GTKMOZEMBED_API(void,                gtk_moz_embed_download_do_command , (GtkMozEmbedDownload *item, guint command))
-GTKMOZEMBED_API(void,                gtk_moz_embed_download_do_command , (GtkMozEmbedDownload *item, guint command))
-GTKMOZEMBED_API(void,                gtk_moz_embed_download_do_command , (GtkMozEmbedDownload *item, guint command))
-GTKMOZEMBED_API(gchar *,             gtk_moz_embed_download_get_file_name , (GtkMozEmbedDownload *item))
-GTKMOZEMBED_API(gchar *,             gtk_moz_embed_download_get_url , (GtkMozEmbedDownload *item))
-GTKMOZEMBED_API(glong ,              gtk_moz_embed_download_get_progress , (GtkMozEmbedDownload *item))
-GTKMOZEMBED_API(glong ,              gtk_moz_embed_download_get_file_size , (GtkMozEmbedDownload *item))
+
+GTKMOZEMBED_API(GtkType,      gtk_moz_embed_download_get_type,           (void))
+GTKMOZEMBED_API(GtkObject *,  gtk_moz_embed_download_new,                (void))
+GTKMOZEMBED_API(GtkObject *,  gtk_moz_embed_download_get_latest_object,  (void))
+GTKMOZEMBED_API(void,         gtk_moz_embed_download_do_command,         (GtkMozEmbedDownload *item, guint command))
+GTKMOZEMBED_API(void,         gtk_moz_embed_download_do_command,         (GtkMozEmbedDownload *item, guint command))
+GTKMOZEMBED_API(void,         gtk_moz_embed_download_do_command,         (GtkMozEmbedDownload *item, guint command))
+GTKMOZEMBED_API(void,         gtk_moz_embed_download_do_command,         (GtkMozEmbedDownload *item, guint command))
+GTKMOZEMBED_API(gchar*,       gtk_moz_embed_download_get_file_name,      (GtkMozEmbedDownload *item))
+GTKMOZEMBED_API(gchar*,       gtk_moz_embed_download_get_url,            (GtkMozEmbedDownload *item))
+GTKMOZEMBED_API(glong,        gtk_moz_embed_download_get_progress,       (GtkMozEmbedDownload *item))
+GTKMOZEMBED_API(glong,        gtk_moz_embed_download_get_file_size,      (GtkMozEmbedDownload *item))
 #ifdef __cplusplus
 }
 #endif /* __cplusplus */
 #endif /* gtkmozembed_download_h */
--- a/embedding/browser/gtk/src/gtkmozembed_glue.cpp
+++ b/embedding/browser/gtk/src/gtkmozembed_glue.cpp
@@ -37,16 +37,17 @@
  *
  * ***** END LICENSE BLOCK ***** */
 
 // This file is an implementation file, meant to be #included in a
 // single C++ file of an embedding application. It is called after
 // XPCOMGlueStartup to glue the gtkmozembed functions.
 
 #include "gtkmozembed.h"
+#include "gtkmozembed_internal.h"
 #ifdef MOZ_WIDGET_GTK2
 #include "gtkmozembed_common.h"
 #include "gtkmozembed_download.h"
 #endif
 #include "nsXPCOMGlue.h"
 
 #ifndef XPCOM_GLUE
 #error This file only makes sense when XPCOM_GLUE is defined.
@@ -60,25 +61,30 @@
   GTKF(gtk_moz_embed_common_new) \
   GTKF(gtk_moz_embed_common_set_pref) \
   GTKF(gtk_moz_embed_common_get_pref) \
   GTKF(gtk_moz_embed_common_save_prefs) \
   GTKF(gtk_moz_embed_common_remove_passwords) \
   GTKF(gtk_moz_embed_common_get_history_list) \
   GTKF(gtk_moz_embed_get_zoom_level) \
   GTKF(gtk_moz_embed_set_zoom_level) \
-  GTKF(gtk_moz_embed_load_image) \
   GTKF(gtk_moz_embed_find_text) \
   GTKF(gtk_moz_embed_clipboard) \
   GTKF(gtk_moz_embed_notify_plugins) \
   GTKF(gtk_moz_embed_get_context_info) \
   GTKF(gtk_moz_embed_get_selection) \
   GTKF(gtk_moz_embed_get_doc_info) \
   GTKF(gtk_moz_embed_insert_text) \
-  GTKF(gtk_moz_embed_common_nsx509_to_raw)
+  GTKF(gtk_moz_embed_common_nsx509_to_raw) \
+  GTKF(gtk_moz_embed_common_observe) \
+  GTKF(gtk_moz_embed_get_shistory_list) \
+  GTKF(gtk_moz_embed_get_shistory_index) \
+  GTKF(gtk_moz_embed_shistory_goto_index) \
+  GTKF(gtk_moz_embed_get_server_cert) \
+  GTKF(gtk_moz_embed_get_nsIWebBrowser)
 #else
 #define GTKMOZEMBED2_FUNCTIONS
 #endif
 
 #define GTKMOZEMBED_FUNCTIONS \
   GTKF(gtk_moz_embed_get_type) \
   GTKF(gtk_moz_embed_new) \
   GTKF(gtk_moz_embed_push_startup) \
--- a/embedding/browser/gtk/src/gtkmozembedprivate.h
+++ b/embedding/browser/gtk/src/gtkmozembedprivate.h
@@ -90,16 +90,17 @@ enum {
   DOM_MOUSE_SCROLL,
   DOM_MOUSE_LONG_PRESS,
   DOM_FOCUS,
   DOM_BLUR,
   UPLOAD_DIALOG,
   ICON_CHANGED,
   MAILTO,
   NETWORK_ERROR,
+  RSS_REQUEST,
   EMBED_LAST_SIGNAL
 };
 
 //  DOM_MOUSE_MOVE,
 extern guint moz_embed_signals[EMBED_LAST_SIGNAL];
 
 #if 0
 enum {