Index: mozilla/accessible/src/atk/nsAccessibleWrap.cpp =================================================================== RCS file: /cvsroot/mozilla/accessible/src/atk/nsAccessibleWrap.cpp,v retrieving revision 1.60 diff -u -r1.60 mozilla/accessible/src/atk/nsAccessibleWrap.cpp --- mozilla/accessible/src/atk/nsAccessibleWrap.cpp +++ mozilla/accessible/src/atk/nsAccessibleWrap.cpp @@ -337,42 +337,37 @@ GetRole(&accRole); //nsIAccessibleText - nsCOMPtr accessInterfaceText; - QueryInterface(NS_GET_IID(nsIAccessibleText), - getter_AddRefs(accessInterfaceText)); + nsCOMPtr accessInterfaceText = + do_QueryInterface(NS_ISUPPORTS_CAST(nsIAccessible*, this)); if (accessInterfaceText) { interfacesBits |= 1 << MAI_INTERFACE_TEXT; } //nsIAccessibleEditableText - nsCOMPtr accessInterfaceEditableText; - QueryInterface(NS_GET_IID(nsIAccessibleEditableText), - getter_AddRefs(accessInterfaceEditableText)); + nsCOMPtr accessInterfaceEditableText = + do_QueryInterface(NS_ISUPPORTS_CAST(nsIAccessible*, this)); if (accessInterfaceEditableText) { interfacesBits |= 1 << MAI_INTERFACE_EDITABLE_TEXT; } //nsIAccessibleSelection - nsCOMPtr accessInterfaceSelection; - QueryInterface(NS_GET_IID(nsIAccessibleSelectable), - getter_AddRefs(accessInterfaceSelection)); + nsCOMPtr accessInterfaceSelection = + do_QueryInterface(NS_ISUPPORTS_CAST(nsIAccessible*, this)); if (accessInterfaceSelection) { interfacesBits |= 1 << MAI_INTERFACE_SELECTION; } //nsIAccessibleValue - nsCOMPtr accessInterfaceValue; - QueryInterface(NS_GET_IID(nsIAccessibleValue), - getter_AddRefs(accessInterfaceValue)); + nsCOMPtr accessInterfaceValue = + do_QueryInterface(NS_ISUPPORTS_CAST(nsIAccessible*, this)); if (accessInterfaceValue) { interfacesBits |= 1 << MAI_INTERFACE_VALUE; } //nsIAccessibleHypertext PRInt32 linkCount = 0; - nsCOMPtr accessInterfaceHypertext; - QueryInterface(NS_GET_IID(nsIAccessibleHyperText), - getter_AddRefs(accessInterfaceHypertext)); + nsCOMPtr accessInterfaceHypertext = + do_QueryInterface(NS_ISUPPORTS_CAST(nsIAccessible*, this)); if (accessInterfaceHypertext) { nsresult rv = accessInterfaceHypertext->GetLinks(&linkCount); if (NS_SUCCEEDED(rv) && (linkCount > 0)) { @@ -381,25 +376,22 @@ } //nsIAccessibleHyperLink - nsCOMPtr accessInterfaceHyperlink; - QueryInterface(NS_GET_IID(nsIAccessibleHyperLink), - getter_AddRefs(accessInterfaceHyperlink)); + nsCOMPtr accessInterfaceHyperlink = + do_QueryInterface(NS_ISUPPORTS_CAST(nsIAccessible*, this)); if (accessInterfaceHyperlink) { interfacesBits |= 1 << MAI_INTERFACE_HYPERLINK_IMPL; } //nsIAccessibleTable - nsCOMPtr accessInterfaceTable; - QueryInterface(NS_GET_IID(nsIAccessibleTable), - getter_AddRefs(accessInterfaceTable)); + nsCOMPtr accessInterfaceTable = + do_QueryInterface(NS_ISUPPORTS_CAST(nsIAccessible*, this)); if (accessInterfaceTable) { interfacesBits |= 1 << MAI_INTERFACE_TABLE; } //nsIAccessibleDocument - nsCOMPtr accessInterfaceDocument; - QueryInterface(NS_GET_IID(nsIAccessibleDocument), - getter_AddRefs(accessInterfaceDocument)); + nsCOMPtr accessInterfaceDocument = + do_QueryInterface(NS_ISUPPORTS_CAST(nsIAccessible*, this)); if (accessInterfaceDocument) { interfacesBits |= 1 << MAI_INTERFACE_DOCUMENT; } @@ -909,15 +901,13 @@ NS_REINTERPRET_CAST(MaiAtkObject*, aAtkObj)->accWrap; PRInt32 count = 0; - nsCOMPtr hyperText; - accWrap->QueryInterface(NS_GET_IID(nsIAccessibleHyperText), getter_AddRefs(hyperText)); + nsCOMPtr hyperText(do_QueryInterface(NS_ISUPPORTS_CAST(nsIAccessible*, accWrap))); if (hyperText) { // If HyperText, then number of links matches number of children hyperText->GetLinks(&count); } else { - nsCOMPtr accText; - accWrap->QueryInterface(NS_GET_IID(nsIAccessibleText), getter_AddRefs(accText)); + nsCOMPtr accText(do_QueryInterface(NS_ISUPPORTS_CAST(nsIAccessible*, accWrap))); if (!accText) { // Accessible text that is not a HyperText has no children accWrap->GetChildCount(&count); } @@ -943,8 +933,7 @@ nsresult rv; nsCOMPtr accChild; - nsCOMPtr hyperText; - accWrap->QueryInterface(NS_GET_IID(nsIAccessibleHyperText), getter_AddRefs(hyperText)); + nsCOMPtr hyperText(do_QueryInterface(NS_ISUPPORTS_CAST(nsIAccessible*, accWrap))); if (hyperText) { // If HyperText, then number of links matches number of children nsCOMPtr hyperLink; @@ -952,8 +941,7 @@ accChild = do_QueryInterface(hyperLink); } else { - nsCOMPtr accText; - accWrap->QueryInterface(NS_GET_IID(nsIAccessibleText), getter_AddRefs(accText)); + nsCOMPtr accText(do_QueryInterface(NS_ISUPPORTS_CAST(nsIAccessible*, accWrap))); if (!accText) { // Accessible Text that is not HyperText has no children rv = accWrap->GetChildAt(aChildIndex, getter_AddRefs(accChild)); } Index: mozilla/accessible/src/atk/nsAppRootAccessible.cpp =================================================================== RCS file: /cvsroot/mozilla/accessible/src/atk/nsAppRootAccessible.cpp,v retrieving revision 1.22 diff -u -r1.22 mozilla/accessible/src/atk/nsAppRootAccessible.cpp --- mozilla/accessible/src/atk/nsAppRootAccessible.cpp +++ mozilla/accessible/src/atk/nsAppRootAccessible.cpp @@ -44,6 +44,7 @@ #include "nsAppRootAccessible.h" #include "prlink.h" #include "nsIServiceManager.h" +#include "nsArrayUtils.h" #include #include @@ -658,9 +659,7 @@ if (aChildNum < 0) return NS_ERROR_INVALID_ARG; - nsCOMPtr childWeakRef; - rv = mChildren->QueryElementAt(aChildNum, NS_GET_IID(nsIWeakReference), - getter_AddRefs(childWeakRef)); + nsCOMPtr childWeakRef(do_QueryElementAt(mChildren, aChildNum, &rv)); if (childWeakRef) { MAI_LOG_DEBUG(("GetChildAt(%d), has weak ref\n", aChildNum)); nsCOMPtr childAcc = do_QueryReferent(childWeakRef); Index: mozilla/accessible/src/atk/nsMaiInterfaceDocument.cpp =================================================================== RCS file: /cvsroot/mozilla/accessible/src/atk/nsMaiInterfaceDocument.cpp,v retrieving revision 1.3 diff -u -r1.3 mozilla/accessible/src/atk/nsMaiInterfaceDocument.cpp --- mozilla/accessible/src/atk/nsMaiInterfaceDocument.cpp +++ mozilla/accessible/src/atk/nsMaiInterfaceDocument.cpp @@ -67,9 +67,7 @@ nsAccessibleWrap *accWrap = GetAccessibleWrap(ATK_OBJECT(aDocument)); NS_ENSURE_TRUE(accWrap, nsnull); - nsCOMPtr accDocument; - accWrap->QueryInterface(NS_GET_IID(nsIAccessibleDocument), - getter_AddRefs(accDocument)); + nsCOMPtr accDocument(do_QueryInterface(NS_ISUPPORTS_CAST(nsIAccessible*, accWrap))); NS_ENSURE_TRUE(accDocument, nsnull); nsAutoString aMimeType; @@ -94,9 +92,7 @@ nsAccessibleWrap *accWrap = GetAccessibleWrap(ATK_OBJECT(aDocument)); NS_ENSURE_TRUE(accWrap, nsnull); - nsCOMPtr accDocument; - accWrap->QueryInterface(NS_GET_IID(nsIAccessibleDocument), - getter_AddRefs(accDocument)); + nsCOMPtr accDocument(do_QueryInterface(NS_ISUPPORTS_CAST(nsIAccessible*, accWrap))); NS_ENSURE_TRUE(accDocument, nsnull); // according to atkobject.h, AtkAttributeSet is a GSList @@ -128,9 +124,7 @@ nsAccessibleWrap *accWrap = GetAccessibleWrap(ATK_OBJECT(aDocument)); NS_ENSURE_TRUE(accWrap, nsnull); - nsCOMPtr accDocument; - accWrap->QueryInterface(NS_GET_IID(nsIAccessibleDocument), - getter_AddRefs(accDocument)); + nsCOMPtr accDocument(do_QueryInterface(NS_ISUPPORTS_CAST(nsIAccessible*, accWrap))); NS_ENSURE_TRUE(accDocument, nsnull); nsresult rv; Index: mozilla/accessible/src/atk/nsMaiInterfaceEditableText.cpp =================================================================== RCS file: /cvsroot/mozilla/accessible/src/atk/nsMaiInterfaceEditableText.cpp,v retrieving revision 1.6 diff -u -r1.6 mozilla/accessible/src/atk/nsMaiInterfaceEditableText.cpp --- mozilla/accessible/src/atk/nsMaiInterfaceEditableText.cpp +++ mozilla/accessible/src/atk/nsMaiInterfaceEditableText.cpp @@ -67,9 +67,7 @@ nsAccessibleWrap *accWrap = GetAccessibleWrap(ATK_OBJECT(aText)); NS_ENSURE_TRUE(accWrap, FALSE); - nsCOMPtr accText; - accWrap->QueryInterface(NS_GET_IID(nsIAccessibleEditableText), - getter_AddRefs(accText)); + nsCOMPtr accText(do_QueryInterface(NS_ISUPPORTS_CAST(nsIAccessible*, accWrap))); NS_ENSURE_TRUE(accText, FALSE); nsCOMPtr attrSet; @@ -87,9 +85,7 @@ if (!accWrap) return; - nsCOMPtr accText; - accWrap->QueryInterface(NS_GET_IID(nsIAccessibleEditableText), - getter_AddRefs(accText)); + nsCOMPtr accText(do_QueryInterface(NS_ISUPPORTS_CAST(nsIAccessible*, accWrap))); if (!accText) return; @@ -110,9 +106,7 @@ if (!accWrap) return; - nsCOMPtr accText; - accWrap->QueryInterface(NS_GET_IID(nsIAccessibleEditableText), - getter_AddRefs(accText)); + nsCOMPtr accText(do_QueryInterface(NS_ISUPPORTS_CAST(nsIAccessible*, accWrap))); if (!accText) return; @@ -139,9 +133,7 @@ if (!accWrap) return; - nsCOMPtr accText; - accWrap->QueryInterface(NS_GET_IID(nsIAccessibleEditableText), - getter_AddRefs(accText)); + nsCOMPtr accText(do_QueryInterface(NS_ISUPPORTS_CAST(nsIAccessible*, accWrap))); if (!accText) return; @@ -159,9 +151,7 @@ if (!accWrap) return; - nsCOMPtr accText; - accWrap->QueryInterface(NS_GET_IID(nsIAccessibleEditableText), - getter_AddRefs(accText)); + nsCOMPtr accText(do_QueryInterface(NS_ISUPPORTS_CAST(nsIAccessible*, accWrap))); if (!accText) return; MAI_LOG_DEBUG(("EditableText: cutTextCB, aStartPos=%d, aEndPos=%d", @@ -178,9 +168,7 @@ if (!accWrap) return; - nsCOMPtr accText; - accWrap->QueryInterface(NS_GET_IID(nsIAccessibleEditableText), - getter_AddRefs(accText)); + nsCOMPtr accText(do_QueryInterface(NS_ISUPPORTS_CAST(nsIAccessible*, accWrap))); if (!accText) return; @@ -198,9 +186,7 @@ if (!accWrap) return; - nsCOMPtr accText; - accWrap->QueryInterface(NS_GET_IID(nsIAccessibleEditableText), - getter_AddRefs(accText)); + nsCOMPtr accText(do_QueryInterface(NS_ISUPPORTS_CAST(nsIAccessible*, accWrap))); if (!accText) return; Index: mozilla/accessible/src/atk/nsMaiInterfaceHyperlinkImpl.cpp =================================================================== RCS file: /cvsroot/mozilla/accessible/src/atk/nsMaiInterfaceHyperlinkImpl.cpp,v retrieving revision 1.1 diff -u -r1.1 mozilla/accessible/src/atk/nsMaiInterfaceHyperlinkImpl.cpp --- mozilla/accessible/src/atk/nsMaiInterfaceHyperlinkImpl.cpp +++ mozilla/accessible/src/atk/nsMaiInterfaceHyperlinkImpl.cpp @@ -55,9 +55,7 @@ nsAccessibleWrap *accWrap = GetAccessibleWrap(ATK_OBJECT(aImpl)); NS_ENSURE_TRUE(accWrap, nsnull); - nsCOMPtr accHyperlink; - accWrap->QueryInterface(NS_GET_IID(nsIAccessibleHyperLink), - getter_AddRefs(accHyperlink)); + nsCOMPtr accHyperlink(do_QueryInterface(NS_ISUPPORTS_CAST(nsIAccessible*, accWrap))); NS_ENSURE_TRUE(accHyperlink, nsnull); MaiHyperlink *maiHyperlink = new MaiHyperlink(accHyperlink); Index: mozilla/accessible/src/atk/nsMaiInterfaceHypertext.cpp =================================================================== RCS file: /cvsroot/mozilla/accessible/src/atk/nsMaiInterfaceHypertext.cpp,v retrieving revision 1.6 diff -u -r1.6 mozilla/accessible/src/atk/nsMaiInterfaceHypertext.cpp --- mozilla/accessible/src/atk/nsMaiInterfaceHypertext.cpp +++ mozilla/accessible/src/atk/nsMaiInterfaceHypertext.cpp @@ -59,9 +59,7 @@ nsAccessibleWrap *accWrap = GetAccessibleWrap(ATK_OBJECT(aText)); NS_ENSURE_TRUE(accWrap, nsnull); - nsCOMPtr accHyperlink; - accWrap->QueryInterface(NS_GET_IID(nsIAccessibleHyperText), - getter_AddRefs(accHyperlink)); + nsCOMPtr accHyperlink(do_QueryInterface(NS_ISUPPORTS_CAST(nsIAccessible*, accWrap))); NS_ENSURE_TRUE(accHyperlink, nsnull); nsCOMPtr hyperLink; @@ -79,9 +77,7 @@ nsAccessibleWrap *accWrap = GetAccessibleWrap(ATK_OBJECT(aText)); NS_ENSURE_TRUE(accWrap, -1); - nsCOMPtr accHyperlink; - accWrap->QueryInterface(NS_GET_IID(nsIAccessibleHyperText), - getter_AddRefs(accHyperlink)); + nsCOMPtr accHyperlink(do_QueryInterface(NS_ISUPPORTS_CAST(nsIAccessible*, accWrap))); NS_ENSURE_TRUE(accHyperlink, -1); PRInt32 count = -1; @@ -97,9 +93,7 @@ nsAccessibleWrap *accWrap = GetAccessibleWrap(ATK_OBJECT(aText)); NS_ENSURE_TRUE(accWrap, -1); - nsCOMPtr accHyperlink; - accWrap->QueryInterface(NS_GET_IID(nsIAccessibleHyperText), - getter_AddRefs(accHyperlink)); + nsCOMPtr accHyperlink(do_QueryInterface(NS_ISUPPORTS_CAST(nsIAccessible*, accWrap))); NS_ENSURE_TRUE(accHyperlink, -1); PRInt32 index = -1; Index: mozilla/accessible/src/atk/nsMaiInterfaceSelection.cpp =================================================================== RCS file: /cvsroot/mozilla/accessible/src/atk/nsMaiInterfaceSelection.cpp,v retrieving revision 1.4 diff -u -r1.4 mozilla/accessible/src/atk/nsMaiInterfaceSelection.cpp --- mozilla/accessible/src/atk/nsMaiInterfaceSelection.cpp +++ mozilla/accessible/src/atk/nsMaiInterfaceSelection.cpp @@ -62,9 +62,7 @@ nsAccessibleWrap *accWrap = GetAccessibleWrap(ATK_OBJECT(aSelection)); NS_ENSURE_TRUE(accWrap, FALSE); - nsCOMPtr accSelection; - accWrap->QueryInterface(NS_GET_IID(nsIAccessibleSelectable), - getter_AddRefs(accSelection)); + nsCOMPtr accSelection(do_QueryInterface(NS_ISUPPORTS_CAST(nsIAccessible*, accWrap))); NS_ENSURE_TRUE(accSelection, FALSE); return NS_SUCCEEDED(accSelection->AddChildToSelection(i)); @@ -76,9 +74,7 @@ nsAccessibleWrap *accWrap = GetAccessibleWrap(ATK_OBJECT(aSelection)); NS_ENSURE_TRUE(accWrap, FALSE); - nsCOMPtr accSelection; - accWrap->QueryInterface(NS_GET_IID(nsIAccessibleSelectable), - getter_AddRefs(accSelection)); + nsCOMPtr accSelection(do_QueryInterface(NS_ISUPPORTS_CAST(nsIAccessible*, accWrap))); NS_ENSURE_TRUE(accSelection, FALSE); return NS_SUCCEEDED(accSelection->ClearSelection()); @@ -90,9 +86,7 @@ nsAccessibleWrap *accWrap = GetAccessibleWrap(ATK_OBJECT(aSelection)); NS_ENSURE_TRUE(accWrap, nsnull); - nsCOMPtr accSelection; - accWrap->QueryInterface(NS_GET_IID(nsIAccessibleSelectable), - getter_AddRefs(accSelection)); + nsCOMPtr accSelection(do_QueryInterface(NS_ISUPPORTS_CAST(nsIAccessible*, accWrap))); NS_ENSURE_TRUE(accSelection, nsnull); AtkObject *atkObj = nsnull; @@ -115,9 +109,7 @@ nsAccessibleWrap *accWrap = GetAccessibleWrap(ATK_OBJECT(aSelection)); NS_ENSURE_TRUE(accWrap, -1); - nsCOMPtr accSelection; - accWrap->QueryInterface(NS_GET_IID(nsIAccessibleSelectable), - getter_AddRefs(accSelection)); + nsCOMPtr accSelection(do_QueryInterface(NS_ISUPPORTS_CAST(nsIAccessible*, accWrap))); NS_ENSURE_TRUE(accSelection, -1); PRInt32 num = 0; @@ -131,9 +123,7 @@ nsAccessibleWrap *accWrap = GetAccessibleWrap(ATK_OBJECT(aSelection)); NS_ENSURE_TRUE(accWrap, FALSE); - nsCOMPtr accSelection; - accWrap->QueryInterface(NS_GET_IID(nsIAccessibleSelectable), - getter_AddRefs(accSelection)); + nsCOMPtr accSelection(do_QueryInterface(NS_ISUPPORTS_CAST(nsIAccessible*, accWrap))); NS_ENSURE_TRUE(accSelection, FALSE); PRBool result = FALSE; @@ -147,9 +137,7 @@ nsAccessibleWrap *accWrap = GetAccessibleWrap(ATK_OBJECT(aSelection)); NS_ENSURE_TRUE(accWrap, FALSE); - nsCOMPtr accSelection; - accWrap->QueryInterface(NS_GET_IID(nsIAccessibleSelectable), - getter_AddRefs(accSelection)); + nsCOMPtr accSelection(do_QueryInterface(NS_ISUPPORTS_CAST(nsIAccessible*, accWrap))); NS_ENSURE_TRUE(accSelection, FALSE); nsresult rv = accSelection->RemoveChildFromSelection(i); @@ -162,9 +150,7 @@ nsAccessibleWrap *accWrap = GetAccessibleWrap(ATK_OBJECT(aSelection)); NS_ENSURE_TRUE(accWrap, FALSE); - nsCOMPtr accSelection; - accWrap->QueryInterface(NS_GET_IID(nsIAccessibleSelectable), - getter_AddRefs(accSelection)); + nsCOMPtr accSelection(do_QueryInterface(NS_ISUPPORTS_CAST(nsIAccessible*, accWrap))); NS_ENSURE_TRUE(accSelection, FALSE); PRBool result = FALSE; Index: mozilla/accessible/src/atk/nsMaiInterfaceTable.cpp =================================================================== RCS file: /cvsroot/mozilla/accessible/src/atk/nsMaiInterfaceTable.cpp,v retrieving revision 1.5 diff -u -r1.5 mozilla/accessible/src/atk/nsMaiInterfaceTable.cpp --- mozilla/accessible/src/atk/nsMaiInterfaceTable.cpp +++ mozilla/accessible/src/atk/nsMaiInterfaceTable.cpp @@ -74,9 +74,7 @@ nsAccessibleWrap *accWrap = GetAccessibleWrap(ATK_OBJECT(aTable)); NS_ENSURE_TRUE(accWrap, nsnull); - nsCOMPtr accTable; - accWrap->QueryInterface(NS_GET_IID(nsIAccessibleTable), - getter_AddRefs(accTable)); + nsCOMPtr accTable(do_QueryInterface(NS_ISUPPORTS_CAST(nsIAccessible*, accWrap))); NS_ENSURE_TRUE(accTable, nsnull); nsCOMPtr cell; @@ -99,9 +97,7 @@ nsAccessibleWrap *accWrap = GetAccessibleWrap(ATK_OBJECT(aTable)); NS_ENSURE_TRUE(accWrap, -1); - nsCOMPtr accTable; - accWrap->QueryInterface(NS_GET_IID(nsIAccessibleTable), - getter_AddRefs(accTable)); + nsCOMPtr accTable(do_QueryInterface(NS_ISUPPORTS_CAST(nsIAccessible*, accWrap))); NS_ENSURE_TRUE(accTable, -1); PRInt32 index; @@ -117,9 +113,7 @@ nsAccessibleWrap *accWrap = GetAccessibleWrap(ATK_OBJECT(aTable)); NS_ENSURE_TRUE(accWrap, -1); - nsCOMPtr accTable; - accWrap->QueryInterface(NS_GET_IID(nsIAccessibleTable), - getter_AddRefs(accTable)); + nsCOMPtr accTable(do_QueryInterface(NS_ISUPPORTS_CAST(nsIAccessible*, accWrap))); NS_ENSURE_TRUE(accTable, -1); PRInt32 col; @@ -135,9 +129,7 @@ nsAccessibleWrap *accWrap = GetAccessibleWrap(ATK_OBJECT(aTable)); NS_ENSURE_TRUE(accWrap, -1); - nsCOMPtr accTable; - accWrap->QueryInterface(NS_GET_IID(nsIAccessibleTable), - getter_AddRefs(accTable)); + nsCOMPtr accTable(do_QueryInterface(NS_ISUPPORTS_CAST(nsIAccessible*, accWrap))); NS_ENSURE_TRUE(accTable, -1); PRInt32 row; @@ -153,9 +145,7 @@ nsAccessibleWrap *accWrap = GetAccessibleWrap(ATK_OBJECT(aTable)); NS_ENSURE_TRUE(accWrap, -1); - nsCOMPtr accTable; - accWrap->QueryInterface(NS_GET_IID(nsIAccessibleTable), - getter_AddRefs(accTable)); + nsCOMPtr accTable(do_QueryInterface(NS_ISUPPORTS_CAST(nsIAccessible*, accWrap))); NS_ENSURE_TRUE(accTable, -1); PRInt32 count; @@ -171,9 +161,7 @@ nsAccessibleWrap *accWrap = GetAccessibleWrap(ATK_OBJECT(aTable)); NS_ENSURE_TRUE(accWrap, -1); - nsCOMPtr accTable; - accWrap->QueryInterface(NS_GET_IID(nsIAccessibleTable), - getter_AddRefs(accTable)); + nsCOMPtr accTable(do_QueryInterface(NS_ISUPPORTS_CAST(nsIAccessible*, accWrap))); NS_ENSURE_TRUE(accTable, -1); PRInt32 count; @@ -190,9 +178,7 @@ nsAccessibleWrap *accWrap = GetAccessibleWrap(ATK_OBJECT(aTable)); NS_ENSURE_TRUE(accWrap, -1); - nsCOMPtr accTable; - accWrap->QueryInterface(NS_GET_IID(nsIAccessibleTable), - getter_AddRefs(accTable)); + nsCOMPtr accTable(do_QueryInterface(NS_ISUPPORTS_CAST(nsIAccessible*, accWrap))); NS_ENSURE_TRUE(accTable, -1); PRInt32 extent; @@ -209,9 +195,7 @@ nsAccessibleWrap *accWrap = GetAccessibleWrap(ATK_OBJECT(aTable)); NS_ENSURE_TRUE(accWrap, -1); - nsCOMPtr accTable; - accWrap->QueryInterface(NS_GET_IID(nsIAccessibleTable), - getter_AddRefs(accTable)); + nsCOMPtr accTable(do_QueryInterface(NS_ISUPPORTS_CAST(nsIAccessible*, accWrap))); NS_ENSURE_TRUE(accTable, -1); PRInt32 extent; @@ -227,9 +211,7 @@ nsAccessibleWrap *accWrap = GetAccessibleWrap(ATK_OBJECT(aTable)); NS_ENSURE_TRUE(accWrap, nsnull); - nsCOMPtr accTable; - accWrap->QueryInterface(NS_GET_IID(nsIAccessibleTable), - getter_AddRefs(accTable)); + nsCOMPtr accTable(do_QueryInterface(NS_ISUPPORTS_CAST(nsIAccessible*, accWrap))); NS_ENSURE_TRUE(accTable, nsnull); nsCOMPtr caption; @@ -250,9 +232,7 @@ nsAccessibleWrap *accWrap = GetAccessibleWrap(ATK_OBJECT(aTable)); NS_ENSURE_TRUE(accWrap, nsnull); - nsCOMPtr accTable; - accWrap->QueryInterface(NS_GET_IID(nsIAccessibleTable), - getter_AddRefs(accTable)); + nsCOMPtr accTable(do_QueryInterface(NS_ISUPPORTS_CAST(nsIAccessible*, accWrap))); NS_ENSURE_TRUE(accTable, nsnull); nsAutoString autoStr; @@ -268,9 +248,7 @@ nsAccessibleWrap *accWrap = GetAccessibleWrap(ATK_OBJECT(aTable)); NS_ENSURE_TRUE(accWrap, nsnull); - nsCOMPtr accTable; - accWrap->QueryInterface(NS_GET_IID(nsIAccessibleTable), - getter_AddRefs(accTable)); + nsCOMPtr accTable(do_QueryInterface(NS_ISUPPORTS_CAST(nsIAccessible*, accWrap))); NS_ENSURE_TRUE(accTable, nsnull); nsCOMPtr header; @@ -304,9 +282,7 @@ nsAccessibleWrap *accWrap = GetAccessibleWrap(ATK_OBJECT(aTable)); NS_ENSURE_TRUE(accWrap, nsnull); - nsCOMPtr accTable; - accWrap->QueryInterface(NS_GET_IID(nsIAccessibleTable), - getter_AddRefs(accTable)); + nsCOMPtr accTable(do_QueryInterface(NS_ISUPPORTS_CAST(nsIAccessible*, accWrap))); NS_ENSURE_TRUE(accTable, nsnull); nsAutoString autoStr; @@ -322,9 +298,7 @@ nsAccessibleWrap *accWrap = GetAccessibleWrap(ATK_OBJECT(aTable)); NS_ENSURE_TRUE(accWrap, nsnull); - nsCOMPtr accTable; - accWrap->QueryInterface(NS_GET_IID(nsIAccessibleTable), - getter_AddRefs(accTable)); + nsCOMPtr accTable(do_QueryInterface(NS_ISUPPORTS_CAST(nsIAccessible*, accWrap))); NS_ENSURE_TRUE(accTable, nsnull); nsCOMPtr header; @@ -354,9 +328,7 @@ nsAccessibleWrap *accWrap = GetAccessibleWrap(ATK_OBJECT(aTable)); NS_ENSURE_TRUE(accWrap, 0); - nsCOMPtr accTable; - accWrap->QueryInterface(NS_GET_IID(nsIAccessibleTable), - getter_AddRefs(accTable)); + nsCOMPtr accTable(do_QueryInterface(NS_ISUPPORTS_CAST(nsIAccessible*, accWrap))); NS_ENSURE_TRUE(accTable, 0); PRUint32 size = 0; @@ -388,9 +360,7 @@ nsAccessibleWrap *accWrap = GetAccessibleWrap(ATK_OBJECT(aTable)); NS_ENSURE_TRUE(accWrap, 0); - nsCOMPtr accTable; - accWrap->QueryInterface(NS_GET_IID(nsIAccessibleTable), - getter_AddRefs(accTable)); + nsCOMPtr accTable(do_QueryInterface(NS_ISUPPORTS_CAST(nsIAccessible*, accWrap))); NS_ENSURE_TRUE(accTable, 0); PRUint32 size = 0; @@ -422,9 +392,7 @@ nsAccessibleWrap *accWrap = GetAccessibleWrap(ATK_OBJECT(aTable)); NS_ENSURE_TRUE(accWrap, FALSE); - nsCOMPtr accTable; - accWrap->QueryInterface(NS_GET_IID(nsIAccessibleTable), - getter_AddRefs(accTable)); + nsCOMPtr accTable(do_QueryInterface(NS_ISUPPORTS_CAST(nsIAccessible*, accWrap))); NS_ENSURE_TRUE(accTable, FALSE); PRBool outValue; @@ -438,9 +406,7 @@ nsAccessibleWrap *accWrap = GetAccessibleWrap(ATK_OBJECT(aTable)); NS_ENSURE_TRUE(accWrap, FALSE); - nsCOMPtr accTable; - accWrap->QueryInterface(NS_GET_IID(nsIAccessibleTable), - getter_AddRefs(accTable)); + nsCOMPtr accTable(do_QueryInterface(NS_ISUPPORTS_CAST(nsIAccessible*, accWrap))); NS_ENSURE_TRUE(accTable, FALSE); PRBool outValue; @@ -454,9 +420,7 @@ nsAccessibleWrap *accWrap = GetAccessibleWrap(ATK_OBJECT(aTable)); NS_ENSURE_TRUE(accWrap, FALSE); - nsCOMPtr accTable; - accWrap->QueryInterface(NS_GET_IID(nsIAccessibleTable), - getter_AddRefs(accTable)); + nsCOMPtr accTable(do_QueryInterface(NS_ISUPPORTS_CAST(nsIAccessible*, accWrap))); NS_ENSURE_TRUE(accTable, FALSE); PRBool outValue; Index: mozilla/accessible/src/atk/nsMaiInterfaceText.cpp =================================================================== RCS file: /cvsroot/mozilla/accessible/src/atk/nsMaiInterfaceText.cpp,v retrieving revision 1.13 diff -u -r1.13 mozilla/accessible/src/atk/nsMaiInterfaceText.cpp --- mozilla/accessible/src/atk/nsMaiInterfaceText.cpp +++ mozilla/accessible/src/atk/nsMaiInterfaceText.cpp @@ -91,9 +91,7 @@ nsAccessibleWrap *accWrap = GetAccessibleWrap(ATK_OBJECT(aText)); NS_ENSURE_TRUE(accWrap, nsnull); - nsCOMPtr accText; - accWrap->QueryInterface(NS_GET_IID(nsIAccessibleText), - getter_AddRefs(accText)); + nsCOMPtr accText(do_QueryInterface(NS_ISUPPORTS_CAST(nsIAccessible*, accWrap))); NS_ENSURE_TRUE(accText, nsnull); nsAutoString autoStr; @@ -115,9 +113,7 @@ nsAccessibleWrap *accWrap = GetAccessibleWrap(ATK_OBJECT(aText)); NS_ENSURE_TRUE(accWrap, nsnull); - nsCOMPtr accText; - accWrap->QueryInterface(NS_GET_IID(nsIAccessibleText), - getter_AddRefs(accText)); + nsCOMPtr accText(do_QueryInterface(NS_ISUPPORTS_CAST(nsIAccessible*, accWrap))); NS_ENSURE_TRUE(accText, nsnull); nsAutoString autoStr; @@ -143,9 +139,7 @@ nsAccessibleWrap *accWrap = GetAccessibleWrap(ATK_OBJECT(aText)); NS_ENSURE_TRUE(accWrap, nsnull); - nsCOMPtr accText; - accWrap->QueryInterface(NS_GET_IID(nsIAccessibleText), - getter_AddRefs(accText)); + nsCOMPtr accText(do_QueryInterface(NS_ISUPPORTS_CAST(nsIAccessible*, accWrap))); NS_ENSURE_TRUE(accText, nsnull); nsAutoString autoStr; @@ -169,9 +163,7 @@ nsAccessibleWrap *accWrap = GetAccessibleWrap(ATK_OBJECT(aText)); NS_ENSURE_TRUE(accWrap, 0); - nsCOMPtr accText; - accWrap->QueryInterface(NS_GET_IID(nsIAccessibleText), - getter_AddRefs(accText)); + nsCOMPtr accText(do_QueryInterface(NS_ISUPPORTS_CAST(nsIAccessible*, accWrap))); NS_ENSURE_TRUE(accText, 0); /* PRUnichar is unsigned short in Mozilla */ @@ -198,9 +190,7 @@ nsAccessibleWrap *accWrap = GetAccessibleWrap(ATK_OBJECT(aText)); NS_ENSURE_TRUE(accWrap, nsnull); - nsCOMPtr accText; - accWrap->QueryInterface(NS_GET_IID(nsIAccessibleText), - getter_AddRefs(accText)); + nsCOMPtr accText(do_QueryInterface(NS_ISUPPORTS_CAST(nsIAccessible*, accWrap))); NS_ENSURE_TRUE(accText, nsnull); nsAutoString autoStr; @@ -224,9 +214,7 @@ nsAccessibleWrap *accWrap = GetAccessibleWrap(ATK_OBJECT(aText)); NS_ENSURE_TRUE(accWrap, 0); - nsCOMPtr accText; - accWrap->QueryInterface(NS_GET_IID(nsIAccessibleText), - getter_AddRefs(accText)); + nsCOMPtr accText(do_QueryInterface(NS_ISUPPORTS_CAST(nsIAccessible*, accWrap))); NS_ENSURE_TRUE(accText, 0); PRInt32 offset; @@ -242,9 +230,7 @@ nsAccessibleWrap *accWrap = GetAccessibleWrap(ATK_OBJECT(aText)); NS_ENSURE_TRUE(accWrap, nsnull); - nsCOMPtr accText; - accWrap->QueryInterface(NS_GET_IID(nsIAccessibleText), - getter_AddRefs(accText)); + nsCOMPtr accText(do_QueryInterface(NS_ISUPPORTS_CAST(nsIAccessible*, accWrap))); NS_ENSURE_TRUE(accText, nsnull); nsCOMPtr accessibleWithAttrs; @@ -276,9 +262,7 @@ if(!accWrap || !aX || !aY || !aWidth || !aHeight) return; - nsCOMPtr accText; - accWrap->QueryInterface(NS_GET_IID(nsIAccessibleText), - getter_AddRefs(accText)); + nsCOMPtr accText(do_QueryInterface(NS_ISUPPORTS_CAST(nsIAccessible*, accWrap))); if (!accText) return; @@ -303,9 +287,7 @@ if(!accWrap || !aRect) return; - nsCOMPtr accText; - accWrap->QueryInterface(NS_GET_IID(nsIAccessibleText), - getter_AddRefs(accText)); + nsCOMPtr accText(do_QueryInterface(NS_ISUPPORTS_CAST(nsIAccessible*, accWrap))); if (!accText) return; @@ -329,9 +311,7 @@ nsAccessibleWrap *accWrap = GetAccessibleWrap(ATK_OBJECT(aText)); NS_ENSURE_TRUE(accWrap, 0); - nsCOMPtr accText; - accWrap->QueryInterface(NS_GET_IID(nsIAccessibleText), - getter_AddRefs(accText)); + nsCOMPtr accText(do_QueryInterface(NS_ISUPPORTS_CAST(nsIAccessible*, accWrap))); NS_ENSURE_TRUE(accText, 0); PRInt32 count = 0; @@ -347,9 +327,7 @@ nsAccessibleWrap *accWrap = GetAccessibleWrap(ATK_OBJECT(aText)); NS_ENSURE_TRUE(accWrap, -1); - nsCOMPtr accText; - accWrap->QueryInterface(NS_GET_IID(nsIAccessibleText), - getter_AddRefs(accText)); + nsCOMPtr accText(do_QueryInterface(NS_ISUPPORTS_CAST(nsIAccessible*, accWrap))); NS_ENSURE_TRUE(accText, -1); PRInt32 offset = 0; @@ -375,9 +353,7 @@ nsAccessibleWrap *accWrap = GetAccessibleWrap(ATK_OBJECT(aText)); NS_ENSURE_TRUE(accWrap, nsnull); - nsCOMPtr accText; - accWrap->QueryInterface(NS_GET_IID(nsIAccessibleText), - getter_AddRefs(accText)); + nsCOMPtr accText(do_QueryInterface(NS_ISUPPORTS_CAST(nsIAccessible*, accWrap))); NS_ENSURE_TRUE(accText, nsnull); PRInt32 startOffset = 0, endOffset = 0; @@ -401,9 +377,7 @@ nsAccessibleWrap *accWrap = GetAccessibleWrap(ATK_OBJECT(aText)); NS_ENSURE_TRUE(accWrap, FALSE); - nsCOMPtr accText; - accWrap->QueryInterface(NS_GET_IID(nsIAccessibleText), - getter_AddRefs(accText)); + nsCOMPtr accText(do_QueryInterface(NS_ISUPPORTS_CAST(nsIAccessible*, accWrap))); NS_ENSURE_TRUE(accText, FALSE); nsresult rv = accText->AddSelection(aStartOffset, aEndOffset); @@ -418,9 +392,7 @@ nsAccessibleWrap *accWrap = GetAccessibleWrap(ATK_OBJECT(aText)); NS_ENSURE_TRUE(accWrap, FALSE); - nsCOMPtr accText; - accWrap->QueryInterface(NS_GET_IID(nsIAccessibleText), - getter_AddRefs(accText)); + nsCOMPtr accText(do_QueryInterface(NS_ISUPPORTS_CAST(nsIAccessible*, accWrap))); NS_ENSURE_TRUE(accText, FALSE); nsresult rv = accText->RemoveSelection(aSelectionNum); @@ -435,9 +407,7 @@ nsAccessibleWrap *accWrap = GetAccessibleWrap(ATK_OBJECT(aText)); NS_ENSURE_TRUE(accWrap, FALSE); - nsCOMPtr accText; - accWrap->QueryInterface(NS_GET_IID(nsIAccessibleText), - getter_AddRefs(accText)); + nsCOMPtr accText(do_QueryInterface(NS_ISUPPORTS_CAST(nsIAccessible*, accWrap))); NS_ENSURE_TRUE(accText, FALSE); nsresult rv = accText->SetSelectionBounds(aSelectionNum, @@ -451,9 +421,7 @@ nsAccessibleWrap *accWrap = GetAccessibleWrap(ATK_OBJECT(aText)); NS_ENSURE_TRUE(accWrap, FALSE); - nsCOMPtr accText; - accWrap->QueryInterface(NS_GET_IID(nsIAccessibleText), - getter_AddRefs(accText)); + nsCOMPtr accText(do_QueryInterface(NS_ISUPPORTS_CAST(nsIAccessible*, accWrap))); NS_ENSURE_TRUE(accText, FALSE); nsresult rv = accText->SetCaretOffset(aOffset); Index: mozilla/accessible/src/atk/nsMaiInterfaceValue.cpp =================================================================== RCS file: /cvsroot/mozilla/accessible/src/atk/nsMaiInterfaceValue.cpp,v retrieving revision 1.8 diff -u -r1.8 mozilla/accessible/src/atk/nsMaiInterfaceValue.cpp --- mozilla/accessible/src/atk/nsMaiInterfaceValue.cpp +++ mozilla/accessible/src/atk/nsMaiInterfaceValue.cpp @@ -61,9 +61,7 @@ if (!accWrap) return; - nsCOMPtr accValue; - accWrap->QueryInterface(NS_GET_IID(nsIAccessibleValue), - getter_AddRefs(accValue)); + nsCOMPtr accValue(do_QueryInterface(NS_ISUPPORTS_CAST(nsIAccessible*, accWrap))); if (!accValue) return; @@ -82,9 +80,7 @@ if (!accWrap) return; - nsCOMPtr accValue; - accWrap->QueryInterface(NS_GET_IID(nsIAccessibleValue), - getter_AddRefs(accValue)); + nsCOMPtr accValue(do_QueryInterface(NS_ISUPPORTS_CAST(nsIAccessible*, accWrap))); if (!accValue) return; @@ -103,9 +99,7 @@ if (!accWrap) return; - nsCOMPtr accValue; - accWrap->QueryInterface(NS_GET_IID(nsIAccessibleValue), - getter_AddRefs(accValue)); + nsCOMPtr accValue(do_QueryInterface(NS_ISUPPORTS_CAST(nsIAccessible*, accWrap))); if (!accValue) return; @@ -124,9 +118,7 @@ if (!accWrap) return; - nsCOMPtr accValue; - accWrap->QueryInterface(NS_GET_IID(nsIAccessibleValue), - getter_AddRefs(accValue)); + nsCOMPtr accValue(do_QueryInterface(NS_ISUPPORTS_CAST(nsIAccessible*, accWrap))); if (!accValue) return; @@ -144,9 +136,7 @@ nsAccessibleWrap *accWrap = GetAccessibleWrap(ATK_OBJECT(obj)); NS_ENSURE_TRUE(accWrap, FALSE); - nsCOMPtr accValue; - accWrap->QueryInterface(NS_GET_IID(nsIAccessibleValue), - getter_AddRefs(accValue)); + nsCOMPtr accValue(do_QueryInterface(NS_ISUPPORTS_CAST(nsIAccessible*, accWrap))); NS_ENSURE_TRUE(accValue, FALSE); double accDouble =g_value_get_double (value); Index: mozilla/accessible/src/base/nsAccessNode.cpp =================================================================== RCS file: /cvsroot/mozilla/accessible/src/base/nsAccessNode.cpp,v retrieving revision 1.34 diff -u -r1.34 mozilla/accessible/src/base/nsAccessNode.cpp --- mozilla/accessible/src/base/nsAccessNode.cpp +++ mozilla/accessible/src/base/nsAccessNode.cpp @@ -286,7 +286,7 @@ // nsRootAccessible has a special QI // that let us get that concrete type directly. nsRootAccessible* foo; - accDoc->QueryInterface(NS_GET_IID(nsRootAccessible), (void**)&foo); // addrefs + CallQueryInterface(accDoc, &foo); return foo; } Index: mozilla/accessible/src/base/nsAccessible.cpp =================================================================== RCS file: /cvsroot/mozilla/accessible/src/base/nsAccessible.cpp,v retrieving revision 1.221 diff -u -r1.221 mozilla/accessible/src/base/nsAccessible.cpp --- mozilla/accessible/src/base/nsAccessible.cpp +++ mozilla/accessible/src/base/nsAccessible.cpp @@ -141,23 +141,9 @@ } #endif -nsresult nsAccessible::QueryInterface(REFNSIID aIID, void** aInstancePtr) -{ - // Custom-built QueryInterface() knows when we support nsIAccessibleSelectable - // based on role attribute and waistate:multiselect - *aInstancePtr = nsnull; - - if (aIID.Equals(NS_GET_IID(nsIAccessible))) { - *aInstancePtr = NS_STATIC_CAST(nsIAccessible*, this); - NS_ADDREF_THIS(); - return NS_OK; - } - - if(aIID.Equals(NS_GET_IID(nsPIAccessible))) { - *aInstancePtr = NS_STATIC_CAST(nsPIAccessible*, this); - NS_ADDREF_THIS(); - return NS_OK; - } +NS_INTERFACE_MAP_BEGIN(nsAccessible) +NS_INTERFACE_MAP_ENTRY(nsIAccessible) +NS_INTERFACE_MAP_ENTRY(nsPIAccessible) if (aIID.Equals(NS_GET_IID(nsIAccessibleSelectable))) { nsCOMPtr content(do_QueryInterface(mDOMNode)); @@ -176,32 +162,23 @@ nsAccessibilityAtoms::multiselect, strings, eCaseMatters) == nsIContent::ATTR_VALUE_NO_MATCH) { - *aInstancePtr = NS_STATIC_CAST(nsIAccessibleSelectable*, this); - NS_ADDREF_THIS(); + foundInterface = NS_STATIC_CAST(nsIAccessibleSelectable*, this); } } - } + } else - if (aIID.Equals(NS_GET_IID(nsIAccessibleValue))) { - if (mRoleMapEntry && mRoleMapEntry->valueRule != eNoValue) { - *aInstancePtr = NS_STATIC_CAST(nsIAccessibleValue*, this); - NS_ADDREF_THIS(); - } - } +NS_INTERFACE_MAP_ENTRY_CONDITIONAL(nsIAccessibleValue, + mRoleMapEntry && mRoleMapEntry->valueRule != eNoValue) if (aIID.Equals(NS_GET_IID(nsIAccessibleHyperLink))) { nsCOMPtr parent(GetParent()); nsCOMPtr hyperTextParent(do_QueryInterface(parent)); - if (hyperTextParent) { - *aInstancePtr = NS_STATIC_CAST(nsIAccessibleHyperLink*, this); - NS_ADDREF_THIS(); - return NS_OK; - } - return NS_ERROR_NO_INTERFACE; - } + if (!hyperTextParent) + return NS_ERROR_NO_INTERFACE; + foundInterface = NS_STATIC_CAST(nsIAccessibleHyperLink*, this); + } else - return nsAccessNode::QueryInterface(aIID, aInstancePtr); -} +NS_INTERFACE_MAP_END_INHERITING(nsAccessNode) nsAccessible::nsAccessible(nsIDOMNode* aNode, nsIWeakReference* aShell): nsAccessNodeWrap(aNode, aShell), mParent(nsnull), mFirstChild(nsnull), mNextSibling(nsnull), mRoleMapEntry(nsnull), Index: mozilla/accessible/src/base/nsRootAccessible.cpp =================================================================== RCS file: /cvsroot/mozilla/accessible/src/base/nsRootAccessible.cpp,v retrieving revision 1.175 diff -u -r1.175 mozilla/accessible/src/base/nsRootAccessible.cpp --- mozilla/accessible/src/base/nsRootAccessible.cpp +++ mozilla/accessible/src/base/nsRootAccessible.cpp @@ -902,7 +902,7 @@ GetDocAccessibleFor(contentTreeItem, PR_TRUE); NS_ASSERTION(accDoc, "No EMBEDS document"); if (accDoc) { - accDoc->QueryInterface(NS_GET_IID(nsIAccessible), (void**)aRelated); + CallQueryInterface(accDoc, aRelated); } } return NS_OK; Index: mozilla/accessible/src/html/nsHyperTextAccessible.cpp =================================================================== RCS file: /cvsroot/mozilla/accessible/src/html/nsHyperTextAccessible.cpp,v retrieving revision 1.33 diff -u -r1.33 mozilla/accessible/src/html/nsHyperTextAccessible.cpp --- mozilla/accessible/src/html/nsHyperTextAccessible.cpp +++ mozilla/accessible/src/html/nsHyperTextAccessible.cpp @@ -67,9 +67,7 @@ NS_IMPL_ADDREF_INHERITED(nsHyperTextAccessible, nsAccessible) NS_IMPL_RELEASE_INHERITED(nsHyperTextAccessible, nsAccessible) -nsresult nsHyperTextAccessible::QueryInterface(REFNSIID aIID, void** aInstancePtr) -{ - *aInstancePtr = nsnull; +NS_INTERFACE_MAP_BEGIN(nsHyperTextAccessible) nsCOMPtr xulDoc(do_QueryInterface(mDOMNode)); if (mDOMNode && !xulDoc) { @@ -82,38 +80,23 @@ PRInt32 numChildren; GetChildCount(&numChildren); if (numChildren > 0) { - *aInstancePtr = NS_STATIC_CAST(nsIAccessibleText*, this); - NS_ADDREF_THIS(); - return NS_OK; + foundInterface = NS_STATIC_CAST(nsIAccessibleText*, this); } - return NS_ERROR_NO_INTERFACE; - } + } else - if (aIID.Equals(NS_GET_IID(nsIAccessibleHyperText))) { - if (IsHyperText()) { - // If |this| contains text and embedded objects - *aInstancePtr = NS_STATIC_CAST(nsIAccessibleHyperText*, this); - NS_ADDREF_THIS(); - return NS_OK; - } - return NS_ERROR_NO_INTERFACE; - } +NS_INTERFACE_MAP_ENTRY_CONDITIONAL(nsIAccessibleHyperText, IsHyperText()) if (aIID.Equals(NS_GET_IID(nsIAccessibleEditableText))) { // If this contains editable text PRUint32 extState; GetExtState(&extState); if (extState & EXT_STATE_EDITABLE) { - *aInstancePtr = NS_STATIC_CAST(nsIAccessibleEditableText*, this); - NS_ADDREF_THIS(); - return NS_OK; + foundInterface = NS_STATIC_CAST(nsIAccessibleEditableText*, this); } - return NS_ERROR_NO_INTERFACE; } - } + } else - return nsAccessible::QueryInterface(aIID, aInstancePtr); -} +NS_IMPL_QUERY_TAIL_INHERITING(nsAccessible) nsHyperTextAccessible::nsHyperTextAccessible(nsIDOMNode* aNode, nsIWeakReference* aShell): nsAccessibleWrap(aNode, aShell) Index: mozilla/accessible/src/msaa/nsAccessibleWrap.cpp =================================================================== RCS file: /cvsroot/mozilla/accessible/src/msaa/nsAccessibleWrap.cpp,v retrieving revision 1.51 diff -u -r1.51 mozilla/accessible/src/msaa/nsAccessibleWrap.cpp --- mozilla/accessible/src/msaa/nsAccessibleWrap.cpp +++ mozilla/accessible/src/msaa/nsAccessibleWrap.cpp @@ -51,6 +51,7 @@ #include "nsTextFormatter.h" #include "nsIView.h" #include "nsRoleMap.h" +#include "nsArrayUtils.h" // for the COM IEnumVARIANT solution in get_AccSelection() #define _ATLBASE_IMPL @@ -616,8 +617,8 @@ VariantInit(pvarChildren); pvarChildren->vt = VT_EMPTY; - nsCOMPtr select; - nsAccessNode::QueryInterface(NS_GET_IID(nsIAccessibleSelectable), getter_AddRefs(select)); + nsCOMPtr select = + do_QueryInterface(NS_ISUPPORTS_CAST(nsIAccessible*, this)); if (select) { // do we have an nsIAccessibleSelectable? // we have an accessible that can have children selected @@ -631,9 +632,7 @@ // 1) Populate an array to store in the enumeration for (PRUint32 i = 0 ; i < length ; i++) { - nsCOMPtr tempAccess; - selectedOptions->QueryElementAt(i, NS_GET_IID(nsIAccessible), - getter_AddRefs(tempAccess)); + nsCOMPtr tempAccess(do_QueryElementAt(selectedOptions, i)); if (tempAccess) { optionArray[i] = NativeAccessible(tempAccess); } Index: mozilla/browser/components/bookmarks/src/nsBookmarksService.cpp =================================================================== RCS file: /cvsroot/mozilla/browser/components/bookmarks/src/nsBookmarksService.cpp,v retrieving revision 1.93 diff -u -r1.93 mozilla/browser/components/bookmarks/src/nsBookmarksService.cpp --- mozilla/browser/components/bookmarks/src/nsBookmarksService.cpp +++ mozilla/browser/components/bookmarks/src/nsBookmarksService.cpp @@ -94,6 +94,7 @@ #include "plbase64.h" #include "nsCRTGlue.h" +#include "nsArrayUtils.h" #if defined(XP_WIN) || defined(XP_OS2) #define NS_LINEBREAK "\015\012" @@ -1466,7 +1467,7 @@ nsCOMPtr result; rv = gRDF->GetUnicodeResource(url, getter_AddRefs(result)); if (NS_FAILED(rv)) return rv; - return result->QueryInterface(NS_GET_IID(nsIRDFNode), (void**) aResult); + return CallQueryInterface(result, aResult); } nsresult @@ -1502,7 +1503,7 @@ nsCOMPtr result; rv = gRDF->GetLiteral(aValue.get(), getter_AddRefs(result)); if (NS_FAILED(rv)) return rv; - return result->QueryInterface(NS_GET_IID(nsIRDFNode), (void**) aResult); + return CallQueryInterface(result, aResult); } nsresult @@ -1530,7 +1531,7 @@ NS_ERROR("unable to get date literal for time"); return rv; } - return result->QueryInterface(NS_GET_IID(nsIRDFNode), (void**) aResult); + return CallQueryInterface(result, aResult); } nsresult @@ -3130,9 +3131,7 @@ if (length == 0) { *aIsBookmarked = PR_FALSE; } else { - nsCOMPtr topParent; - parentArray->QueryElementAt(0, NS_GET_IID(nsIRDFResource), - getter_AddRefs(topParent)); + nsCOMPtr topParent(do_QueryElementAt(parentArray, 0)); *aIsBookmarked = topParent == kNC_BookmarksTopRoot; } return NS_OK; @@ -4175,9 +4174,7 @@ // multiple arguments can be the same, by the way, thus the "offset" for (loop = 0; loop < numArguments; loop += 2) { - nsCOMPtr src; - rv = arguments->QueryElementAt(loop, NS_GET_IID(nsIRDFResource), - getter_AddRefs(src)); + nsCOMPtr src(do_QueryElementAt(arguments, loop, &rv)); if (NS_FAILED(rv)) return rv; if (src == res) @@ -4188,9 +4185,7 @@ continue; } - nsCOMPtr val; - rv = arguments->QueryElementAt(loop + 1, NS_GET_IID(nsIRDFNode), - getter_AddRefs(val)); + nsCOMPtr val(do_QueryElementAt(arguments, loop + 1, &rv)); if (NS_FAILED(rv)) return rv; *argValue = val; @@ -4303,9 +4298,7 @@ for (loop=((PRInt32)numSources)-1; loop>=0; loop--) { - nsCOMPtr src; - rv = aSources->QueryElementAt(loop, NS_GET_IID(nsIRDFResource), - getter_AddRefs(src)); + nsCOMPtr src(do_QueryElementAt(aSources, loop, &rv)); if (NS_FAILED(rv)) return rv; if (aCommand == kNC_BookmarkCommand_NewBookmark) @@ -4533,7 +4526,7 @@ nsCOMPtr bookmarksFile; rv = NS_GetSpecialDirectory(NS_APP_BOOKMARKS_50_FILE, - getter_AddRefs(bookmarksFile));; + getter_AddRefs(bookmarksFile)); if (NS_FAILED(rv) || !bookmarksFile) return; @@ -5360,7 +5353,7 @@ aResult.Truncate(); rv = NS_OK; } - else if (NS_SUCCEEDED(rv = aNode->QueryInterface(NS_GET_IID(nsIRDFResource), (void**) &resource))) + else if (NS_SUCCEEDED(rv = CallQueryInterface(aNode, &resource))) { const char *p = nsnull; if (NS_SUCCEEDED(rv = resource->GetValueConst( &p )) && (p)) @@ -5369,7 +5362,7 @@ } NS_RELEASE(resource); } - else if (NS_SUCCEEDED(rv = aNode->QueryInterface(NS_GET_IID(nsIRDFDate), (void**) &dateLiteral))) + else if (NS_SUCCEEDED(rv = CallQueryInterface(aNode, &resource))) { PRInt64 theDate, million; if (NS_SUCCEEDED(rv = dateLiteral->GetValue( &theDate ))) @@ -5383,7 +5376,7 @@ } NS_RELEASE(dateLiteral); } - else if (NS_SUCCEEDED(rv = aNode->QueryInterface(NS_GET_IID(nsIRDFInt), (void**) &intLiteral))) + else if (NS_SUCCEEDED(rv = CallQueryInterface(aNode, &resource))) { PRInt32 theInt; aResult.Truncate(); @@ -5393,7 +5386,7 @@ } NS_RELEASE(intLiteral); } - else if (NS_SUCCEEDED(rv = aNode->QueryInterface(NS_GET_IID(nsIRDFLiteral), (void**) &literal))) + else if (NS_SUCCEEDED(rv = CallQueryInterface(aNode, &resource))) { const PRUnichar *p = nsnull; if (NS_SUCCEEDED(rv = literal->GetValueConst( &p )) && (p)) Index: mozilla/browser/components/bookmarks/src/nsForwardProxyDataSource.cpp =================================================================== RCS file: /cvsroot/mozilla/browser/components/bookmarks/src/nsForwardProxyDataSource.cpp,v retrieving revision 1.6 diff -u -r1.6 mozilla/browser/components/bookmarks/src/nsForwardProxyDataSource.cpp --- mozilla/browser/components/bookmarks/src/nsForwardProxyDataSource.cpp +++ mozilla/browser/components/bookmarks/src/nsForwardProxyDataSource.cpp @@ -488,8 +488,7 @@ // have aggregate resources -- if they're found, append them // to a new array for (PRUint32 i = 0; i < sourcesCount; i++) { - rv = aSources->QueryElementAt(i, NS_GET_IID(nsIRDFResource), - getter_AddRefs(source)); + source = do_QueryElementAt(aSources, i, &rv); if (NS_FAILED(rv)) return rv; if (GetProxyResource(source, getter_AddRefs(proxyResource)) == NS_OK) { Index: mozilla/browser/components/migration/src/nsNetscapeProfileMigratorBase.cpp =================================================================== RCS file: /cvsroot/mozilla/browser/components/migration/src/nsNetscapeProfileMigratorBase.cpp,v retrieving revision 1.23 diff -u -r1.23 mozilla/browser/components/migration/src/nsNetscapeProfileMigratorBase.cpp --- mozilla/browser/components/migration/src/nsNetscapeProfileMigratorBase.cpp +++ mozilla/browser/components/migration/src/nsNetscapeProfileMigratorBase.cpp @@ -241,7 +241,12 @@ nsCOMPtr pls(do_CreateInstance("@mozilla.org/pref-localizedstring;1")); NS_ConvertUTF8toUTF16 data(xform->stringValue); pls->SetData(data.get()); - return aBranch->SetComplexValue(xform->targetPrefName ? xform->targetPrefName : xform->sourcePrefName, NS_GET_IID(nsIPrefLocalizedString), pls); + return + aBranch->SetComplexValue(xform->targetPrefName + ? xform->targetPrefName + : xform->sourcePrefName, + NS_GET_IID(nsIPrefLocalizedString), + pls); } return NS_OK; } @@ -254,7 +259,12 @@ nsCOMPtr pls(do_CreateInstance("@mozilla.org/pref-localizedstring;1")); nsAutoString data = NS_ConvertUTF8toUTF16(xform->stringValue); pls->SetData(data.get()); - return aBranch->SetComplexValue(xform->targetPrefName ? xform->targetPrefName : xform->sourcePrefName, NS_GET_IID(nsIPrefLocalizedString), pls); + return + aBranch->SetComplexValue(xform->targetPrefName + ? xform->targetPrefName + : xform->sourcePrefName, + NS_GET_IID(nsIPrefLocalizedString), + pls); } return NS_OK; } Index: mozilla/browser/components/migration/src/nsPhoenixProfileMigrator.cpp =================================================================== RCS file: /cvsroot/mozilla/browser/components/migration/src/nsPhoenixProfileMigrator.cpp,v retrieving revision 1.20 diff -u -r1.20 mozilla/browser/components/migration/src/nsPhoenixProfileMigrator.cpp --- mozilla/browser/components/migration/src/nsPhoenixProfileMigrator.cpp +++ mozilla/browser/components/migration/src/nsPhoenixProfileMigrator.cpp @@ -254,14 +254,11 @@ PRUint32 count; mProfileNames->Count(&count); for (PRUint32 i = 0; i < count; ++i) { - nsCOMPtr str; - mProfileNames->QueryElementAt(i, NS_GET_IID(nsISupportsString), - getter_AddRefs(str)); + nsCOMPtr str(do_QueryElementAt(mProfileNames, i)); nsString profileName; str->GetData(profileName); if (profileName.Equals(aProfile)) { - mProfileLocations->QueryElementAt(i, NS_GET_IID(nsILocalFile), - getter_AddRefs(mSourceProfile)); + mSourceProfile = do_QueryElementAt(mProfileLocations, i); break; } } Index: mozilla/browser/components/migration/src/nsSeamonkeyProfileMigrator.cpp =================================================================== RCS file: /cvsroot/mozilla/browser/components/migration/src/nsSeamonkeyProfileMigrator.cpp,v retrieving revision 1.31 diff -u -r1.31 mozilla/browser/components/migration/src/nsSeamonkeyProfileMigrator.cpp --- mozilla/browser/components/migration/src/nsSeamonkeyProfileMigrator.cpp +++ mozilla/browser/components/migration/src/nsSeamonkeyProfileMigrator.cpp @@ -277,14 +277,11 @@ PRUint32 count; mProfileNames->Count(&count); for (PRUint32 i = 0; i < count; ++i) { - nsCOMPtr str; - mProfileNames->QueryElementAt(i, NS_GET_IID(nsISupportsString), - getter_AddRefs(str)); + nsCOMPtr str(do_QueryElementAt(mProfileNames, i)); nsString profileName; str->GetData(profileName); if (profileName.Equals(aProfile)) { - mProfileLocations->QueryElementAt(i, NS_GET_IID(nsILocalFile), - getter_AddRefs(mSourceProfile)); + mSourceProflie = do_QueryElementAt(mProfileLocations, i); break; } } Index: mozilla/camino/src/application/AppDirServiceProvider.cpp =================================================================== RCS file: /cvsroot/mozilla/camino/src/application/AppDirServiceProvider.cpp,v retrieving revision 1.11 diff -u -r1.11 mozilla/camino/src/application/AppDirServiceProvider.cpp --- mozilla/camino/src/application/AppDirServiceProvider.cpp +++ mozilla/camino/src/application/AppDirServiceProvider.cpp @@ -99,7 +99,7 @@ } if (localFile && NS_SUCCEEDED(rv)) - return localFile->QueryInterface(NS_GET_IID(nsIFile), (void**)_retval); + return CallQueryInterface(localFile, _retval); return rv; } Index: mozilla/content/base/src/nsStyleLinkElement.cpp =================================================================== RCS file: /cvsroot/mozilla/content/base/src/nsStyleLinkElement.cpp,v retrieving revision 1.42 diff -u -r1.42 mozilla/content/base/src/nsStyleLinkElement.cpp --- mozilla/content/base/src/nsStyleLinkElement.cpp +++ mozilla/content/base/src/nsStyleLinkElement.cpp @@ -224,8 +224,7 @@ nsCOMPtr parser = mParser; mParser = nsnull; - nsCOMPtr thisContent; - QueryInterface(NS_GET_IID(nsIContent), getter_AddRefs(thisContent)); + nsCOMPtr thisContent(do_QueryInterface(NS_ISUPPORTS_CAST(nsIDOMLinkStyle*, this))); NS_ENSURE_TRUE(thisContent, NS_ERROR_FAILURE); Index: mozilla/content/xml/content/src/Makefile.in =================================================================== RCS file: /cvsroot/mozilla/content/xml/content/src/Makefile.in,v retrieving revision 1.38 diff -u -r1.38 mozilla/content/xml/content/src/Makefile.in --- mozilla/content/xml/content/src/Makefile.in +++ mozilla/content/xml/content/src/Makefile.in @@ -74,6 +74,10 @@ # we don't want the shared lib, but we want to force the creation of a static lib. FORCE_STATIC_LIB = 1 +LOCAL_INCLUDES = \ + -I$(topsrcdir)/dom/src/base \ + $(NULL) + include $(topsrcdir)/config/rules.mk INCLUDES += \ Index: mozilla/content/xml/content/src/nsXMLElement.cpp =================================================================== RCS file: /cvsroot/mozilla/content/xml/content/src/nsXMLElement.cpp,v retrieving revision 1.142 diff -u -r1.142 mozilla/content/xml/content/src/nsXMLElement.cpp --- mozilla/content/xml/content/src/nsXMLElement.cpp +++ mozilla/content/xml/content/src/nsXMLElement.cpp @@ -69,6 +69,7 @@ #include "nsLayoutAtoms.h" #include "nsEventDispatcher.h" #include "nsContentErrors.h" +#include "nsDOMClassInfo.h" static nsIContent::AttrValuesArray strings[] = {&nsLayoutAtoms::_new, &nsLayoutAtoms::replace, &nsLayoutAtoms::embed, nsnull}; @@ -98,38 +99,19 @@ // QueryInterface implementation for nsXMLElement -NS_IMETHODIMP -nsXMLElement::QueryInterface(REFNSIID aIID, void** aInstancePtr) -{ - NS_ENSURE_ARG_POINTER(aInstancePtr); - *aInstancePtr = nsnull; - +NS_INTERFACE_MAP_BEGIN(nsXMLElement) nsresult rv = nsGenericElement::QueryInterface(aIID, aInstancePtr); - if (NS_SUCCEEDED(rv)) return rv; - nsISupports *inst = nsnull; - - if (aIID.Equals(NS_GET_IID(nsIDOMNode))) { - inst = NS_STATIC_CAST(nsIDOMNode *, this); - } else if (aIID.Equals(NS_GET_IID(nsIDOMElement))) { - inst = NS_STATIC_CAST(nsIDOMElement *, this); - } else if (aIID.Equals(NS_GET_IID(nsIXMLContent))) { - inst = NS_STATIC_CAST(nsIXMLContent *, this); - } else if (aIID.Equals(NS_GET_IID(nsIClassInfo))) { - inst = nsContentUtils::GetClassInfoInstance(eDOMClassInfo_Element_id); - NS_ENSURE_TRUE(inst, NS_ERROR_OUT_OF_MEMORY); - } else { + NS_INTERFACE_MAP_ENTRY(nsIDOMNode) + NS_INTERFACE_MAP_ENTRY(nsIDOMElement) + NS_INTERFACE_MAP_ENTRY(nsIXMLContent) + NS_DOM_INTERFACE_MAP_ENTRY_CLASSINFO(Element) + { return PostQueryInterface(aIID, aInstancePtr); } - - NS_ADDREF(inst); - - *aInstancePtr = inst; - - return NS_OK; -} +NS_INTERFACE_MAP_END NS_IMPL_ADDREF_INHERITED(nsXMLElement, nsGenericElement) Index: mozilla/content/xtf/src/nsXTFElementWrapper.cpp =================================================================== RCS file: /cvsroot/mozilla/content/xtf/src/nsXTFElementWrapper.cpp,v retrieving revision 1.39 diff -u -r1.39 mozilla/content/xtf/src/nsXTFElementWrapper.cpp --- mozilla/content/xtf/src/nsXTFElementWrapper.cpp +++ mozilla/content/xtf/src/nsXTFElementWrapper.cpp @@ -103,22 +103,11 @@ NS_IMPL_ADDREF_INHERITED(nsXTFElementWrapper,nsXTFElementWrapperBase) NS_IMPL_RELEASE_INHERITED(nsXTFElementWrapper,nsXTFElementWrapperBase) -NS_IMETHODIMP -nsXTFElementWrapper::QueryInterface(REFNSIID aIID, void** aInstancePtr) -{ +NS_INTERFACE_MAP_BEGIN(nsXTFElementWrapper) nsresult rv; - - if(aIID.Equals(NS_GET_IID(nsIClassInfo))) { - *aInstancePtr = NS_STATIC_CAST(nsIClassInfo*, this); - NS_ADDREF_THIS(); - return NS_OK; - } - else if(aIID.Equals(NS_GET_IID(nsIXTFElementWrapper))) { - *aInstancePtr = NS_STATIC_CAST(nsIXTFElementWrapper*, this); - NS_ADDREF_THIS(); - return NS_OK; - } - else if (NS_SUCCEEDED(rv = nsXTFElementWrapperBase::QueryInterface(aIID, aInstancePtr))) { + NS_INTERFACE_MAP_ENTRY(nsIClassInfo) + NS_INTERFACE_MAP_ENTRY(nsIXTFElementWrapper) + if (NS_SUCCEEDED(rv = nsXTFElementWrapperBase::QueryInterface(aIID, aInstancePtr))) { return rv; } else { @@ -135,8 +124,7 @@ } } - return NS_ERROR_NO_INTERFACE; -} +NS_INTERFACE_MAP_END //---------------------------------------------------------------------- // nsIContent methods: Index: mozilla/content/xtf/src/nsXTFWeakTearoff.cpp =================================================================== RCS file: /cvsroot/mozilla/content/xtf/src/nsXTFWeakTearoff.cpp,v retrieving revision 1.8 diff -u -r1.8 mozilla/content/xtf/src/nsXTFWeakTearoff.cpp --- mozilla/content/xtf/src/nsXTFWeakTearoff.cpp +++ mozilla/content/xtf/src/nsXTFWeakTearoff.cpp @@ -116,19 +116,14 @@ NS_IMPL_ADDREF(nsXTFWeakTearoff) NS_IMPL_RELEASE(nsXTFWeakTearoff) -NS_IMETHODIMP -nsXTFWeakTearoff::QueryInterface(REFNSIID aIID, void** aInstancePtr) -{ +NS_INTERFACE_MAP_BEGIN(nsXTFWeakTearoff) if(aIID.Equals(mIID) || aIID.Equals(NS_GET_IID(nsISupports))) { - *aInstancePtr = mXPTCStub; - NS_ADDREF_THIS(); - return NS_OK; + foundInterface = mXPTCStub; } // we can't map QI onto the obj, because the xpcom wrapper otherwise // QI-accumulates all interfaces defined on mObj // else return mObj->QueryInterface(aIID, aInstancePtr); - return NS_ERROR_NO_INTERFACE; -} +NS_INTERFACE_MAP_END NS_IMETHODIMP nsXTFWeakTearoff::CallMethod(PRUint16 methodIndex, Index: mozilla/content/xul/content/src/Makefile.in =================================================================== RCS file: /cvsroot/mozilla/content/xul/content/src/Makefile.in,v retrieving revision 1.43 diff -u -r1.43 mozilla/content/xul/content/src/Makefile.in --- mozilla/content/xul/content/src/Makefile.in +++ mozilla/content/xul/content/src/Makefile.in @@ -87,6 +87,10 @@ # static lib. FORCE_STATIC_LIB = 1 +LOCAL_INCLUDES = \ + -I$(topsrcdir)/dom/src/base \ + $(NULL) + include $(topsrcdir)/config/rules.mk LOCAL_INCLUDES = \ Index: mozilla/content/xul/content/src/nsXULElement.cpp =================================================================== RCS file: /cvsroot/mozilla/content/xul/content/src/nsXULElement.cpp,v retrieving revision 1.671 diff -u -r1.671 mozilla/content/xul/content/src/nsXULElement.cpp --- mozilla/content/xul/content/src/nsXULElement.cpp +++ mozilla/content/xul/content/src/nsXULElement.cpp @@ -154,6 +154,7 @@ #include "nsNodeInfoManager.h" #include "nsXBLBinding.h" #include "nsEventDispatcher.h" +#include "nsDOMClassInfo.h" /** * Three bits are used for XUL Element's lazy state. @@ -414,47 +415,29 @@ NS_IMPL_ADDREF_INHERITED(nsXULElement, nsGenericElement) NS_IMPL_RELEASE_INHERITED(nsXULElement, nsGenericElement) -NS_IMETHODIMP -nsXULElement::QueryInterface(REFNSIID aIID, void** aInstancePtr) -{ - NS_ENSURE_ARG_POINTER(aInstancePtr); - *aInstancePtr = nsnull; - +NS_INTERFACE_MAP_BEGIN(nsXULElement) nsresult rv = nsGenericElement::QueryInterface(aIID, aInstancePtr); if (NS_SUCCEEDED(rv)) return rv; - nsISupports *inst = nsnull; - - if (aIID.Equals(NS_GET_IID(nsIDOMNode))) { - inst = NS_STATIC_CAST(nsIDOMNode *, this); - } else if (aIID.Equals(NS_GET_IID(nsIDOMElement))) { - inst = NS_STATIC_CAST(nsIDOMElement *, this); - } else if (aIID.Equals(NS_GET_IID(nsIDOMXULElement))) { - inst = NS_STATIC_CAST(nsIDOMXULElement *, this); - } else if (aIID.Equals(NS_GET_IID(nsIXMLContent))) { - inst = NS_STATIC_CAST(nsIXMLContent *, this); - } else if (aIID.Equals(NS_GET_IID(nsIScriptEventHandlerOwner))) { - inst = NS_STATIC_CAST(nsIScriptEventHandlerOwner *, this); - } else if (aIID.Equals(NS_GET_IID(nsIChromeEventHandler))) { - inst = NS_STATIC_CAST(nsIChromeEventHandler *, this); - } else if (aIID.Equals(NS_GET_IID(nsIDOMElementCSSInlineStyle))) { - inst = NS_STATIC_CAST(nsIDOMElementCSSInlineStyle *, - new nsXULElementTearoff(this)); - NS_ENSURE_TRUE(inst, NS_ERROR_OUT_OF_MEMORY); - } else if (aIID.Equals(NS_GET_IID(nsIClassInfo))) { - inst = nsContentUtils::GetClassInfoInstance(eDOMClassInfo_XULElement_id); - NS_ENSURE_TRUE(inst, NS_ERROR_OUT_OF_MEMORY); - } else { + NS_INTERFACE_MAP_ENTRY(nsIDOMNode) + NS_INTERFACE_MAP_ENTRY(nsIDOMElement) + NS_INTERFACE_MAP_ENTRY(nsIDOMXULElement) + NS_INTERFACE_MAP_ENTRY(nsIXMLContent) + NS_INTERFACE_MAP_ENTRY(nsIScriptEventHandlerOwner) + NS_INTERFACE_MAP_ENTRY(nsIChromeEventHandler) + if (aIID.Equals(NS_GET_IID(nsIDOMElementCSSInlineStyle))) { + foundInterface = NS_STATIC_CAST(nsIDOMElementCSSInlineStyle *, + new nsXULElementTearoff(this)); + NS_ENSURE_TRUE(foundInterface, NS_ERROR_OUT_OF_MEMORY); + } else + NS_DOM_INTERFACE_MAP_ENTRY_CLASSINFO(XULElement) + { return PostQueryInterface(aIID, aInstancePtr); } - NS_ADDREF(inst); - - *aInstancePtr = inst; - return NS_OK; -} +NS_INTERFACE_MAP_END //---------------------------------------------------------------------- // nsIDOMNode interface Index: mozilla/content/xul/document/src/nsXULPrototypeDocument.cpp =================================================================== RCS file: /cvsroot/mozilla/content/xul/document/src/nsXULPrototypeDocument.cpp,v retrieving revision 1.84 diff -u -r1.84 mozilla/content/xul/document/src/nsXULPrototypeDocument.cpp --- mozilla/content/xul/document/src/nsXULPrototypeDocument.cpp +++ mozilla/content/xul/document/src/nsXULPrototypeDocument.cpp @@ -483,8 +483,8 @@ rv |= aStream->Write32(referenceCount); for (i = 0; i < referenceCount; ++i) { - mStyleSheetReferences->QueryElementAt(i, NS_GET_IID(nsIURI), getter_AddRefs(referenceURI)); - + referenceURI = do_QueryElementAt(mStyleSheetReferences, i); + rv |= aStream->WriteCompoundObject(referenceURI, NS_GET_IID(nsIURI), PR_TRUE); } Index: mozilla/db/mork/build/nsMorkFactory.cpp =================================================================== RCS file: /cvsroot/mozilla/db/mork/build/nsMorkFactory.cpp,v retrieving revision 1.22 diff -u -r1.22 mozilla/db/mork/build/nsMorkFactory.cpp --- mozilla/db/mork/build/nsMorkFactory.cpp +++ mozilla/db/mork/build/nsMorkFactory.cpp @@ -76,21 +76,10 @@ NS_IMPL_ADDREF(nsMorkFactoryFactory) NS_IMPL_RELEASE(nsMorkFactoryFactory) -NS_IMETHODIMP -nsMorkFactoryFactory::QueryInterface(REFNSIID iid, void** result) -{ - if (! result) - return NS_ERROR_NULL_POINTER; - - *result = nsnull; - if(iid.Equals(NS_GET_IID(nsIMdbFactoryFactory)) || - iid.Equals(NS_GET_IID(nsISupports))) { - *result = NS_STATIC_CAST(nsIMdbFactoryFactory*, this); - AddRef(); - return NS_OK; - } - return NS_NOINTERFACE; -} +NS_INTERFACE_MAP_BEGIN(nsMorkFactoryFactory) + NS_INTERFACE_MAP_ENTRY(nsIMdbFactoryFactory) + NS_INTERFACE_MAP_ENTRY(nsISupports) +NS_INTERFACE_MAP_END Index: mozilla/docshell/base/nsDefaultURIFixup.cpp =================================================================== RCS file: /cvsroot/mozilla/docshell/base/nsDefaultURIFixup.cpp,v retrieving revision 1.50 diff -u -r1.50 mozilla/docshell/base/nsDefaultURIFixup.cpp --- mozilla/docshell/base/nsDefaultURIFixup.cpp +++ mozilla/docshell/base/nsDefaultURIFixup.cpp @@ -799,6 +799,6 @@ { return NS_ERROR_OUT_OF_MEMORY; } - return fixup->QueryInterface(NS_GET_IID(nsIURIFixup), (void **) aURIFixup); + return CallQueryInterface(fixup, aURIFixup); } Index: mozilla/docshell/base/nsDocShell.cpp =================================================================== RCS file: /cvsroot/mozilla/docshell/base/nsDocShell.cpp,v retrieving revision 1.820 diff -u -r1.820 mozilla/docshell/base/nsDocShell.cpp --- mozilla/docshell/base/nsDocShell.cpp +++ mozilla/docshell/base/nsDocShell.cpp @@ -1360,7 +1360,7 @@ rv = docShellEnum->First(); if (NS_FAILED(rv)) return rv; - rv = docShellEnum->QueryInterface(NS_GET_IID(nsISimpleEnumerator), (void **)outEnum); + rv = CallQueryInterface(docShellEnum.get(), outEnum); return rv; } Index: mozilla/docshell/base/nsDocShellEnumerator.cpp =================================================================== RCS file: /cvsroot/mozilla/docshell/base/nsDocShellEnumerator.cpp,v retrieving revision 1.5 diff -u -r1.5 mozilla/docshell/base/nsDocShellEnumerator.cpp --- mozilla/docshell/base/nsDocShellEnumerator.cpp +++ mozilla/docshell/base/nsDocShellEnumerator.cpp @@ -67,16 +67,14 @@ nsresult rv = EnsureDocShellArray(); if (NS_FAILED(rv)) return rv; - if (mCurIndex >= 0 && mCurIndex < mItemArray->Count()) - { - nsIDocShellTreeItem* thisItem = NS_REINTERPRET_CAST(nsIDocShellTreeItem*, mItemArray->ElementAt(mCurIndex)); - rv = thisItem->QueryInterface(NS_GET_IID(nsISupports), (void **)outCurItem); - if (NS_FAILED(rv)) return rv; - } - else + if (mCurIndex < 0 || mCurIndex >= mItemArray->Count()) return NS_ERROR_FAILURE; + + nsIDocShellTreeItem* thisItem = NS_REINTERPRET_CAST(nsIDocShellTreeItem*, mItemArray->ElementAt(mCurIndex)); + rv = CallQueryInterface(thisItem, outCurItem); + if (NS_FAILED(rv)) return rv; - mCurIndex ++; + ++mCurIndex; return NS_OK; } Index: mozilla/docshell/base/nsWebShell.cpp =================================================================== RCS file: /cvsroot/mozilla/docshell/base/nsWebShell.cpp,v retrieving revision 1.682 diff -u -r1.682 mozilla/docshell/base/nsWebShell.cpp --- mozilla/docshell/base/nsWebShell.cpp +++ mozilla/docshell/base/nsWebShell.cpp @@ -561,7 +561,7 @@ nsWebShell::~nsWebShell() { - Destroy(); + Destroy(); ++mRefCnt; // following releases can cause this destructor to be called // recursively if the refcount is allowed to remain 0 @@ -614,27 +614,27 @@ NS_IMPL_RELEASE_INHERITED(nsWebShell, nsDocShell) NS_INTERFACE_MAP_BEGIN(nsWebShell) - NS_INTERFACE_MAP_ENTRY(nsIWebShellServices) - NS_INTERFACE_MAP_ENTRY(nsILinkHandler) - NS_INTERFACE_MAP_ENTRY(nsIClipboardCommands) + NS_INTERFACE_MAP_ENTRY(nsIWebShellServices) + NS_INTERFACE_MAP_ENTRY(nsILinkHandler) + NS_INTERFACE_MAP_ENTRY(nsIClipboardCommands) NS_INTERFACE_MAP_END_INHERITING(nsDocShell) NS_IMETHODIMP nsWebShell::GetInterface(const nsIID &aIID, void** aInstancePtr) { - NS_PRECONDITION(aInstancePtr, "null out param"); + NS_PRECONDITION(aInstancePtr, "null out param"); - *aInstancePtr = nsnull; + *aInstancePtr = nsnull; - if(aIID.Equals(NS_GET_IID(nsICommandManager))) - { - NS_ENSURE_SUCCESS(EnsureCommandHandler(), NS_ERROR_FAILURE); - *aInstancePtr = mCommandManager; - NS_ADDREF((nsISupports*) *aInstancePtr); - return NS_OK; - } + if(aIID.Equals(NS_GET_IID(nsICommandManager))) + { + NS_ENSURE_SUCCESS(EnsureCommandHandler(), NS_ERROR_FAILURE); + *aInstancePtr = mCommandManager; + NS_ADDREF((nsISupports*) *aInstancePtr); + return NS_OK; + } - return nsDocShell::GetInterface(aIID, aInstancePtr); + return nsDocShell::GetInterface(aIID, aInstancePtr); } nsEventStatus PR_CALLBACK Index: mozilla/dom/public/nsIJSEventListener.h =================================================================== RCS file: /cvsroot/mozilla/dom/public/nsIJSEventListener.h,v retrieving revision 3.13 diff -u -r3.13 mozilla/dom/public/nsIJSEventListener.h --- mozilla/dom/public/nsIJSEventListener.h +++ mozilla/dom/public/nsIJSEventListener.h @@ -65,8 +65,7 @@ // GC from cleaning up our global in all cases. However, as this is a // weak-ref, we must ensure it is the identity of the event target and // not a "tear-off" or similar that may not live as long as we expect. - aTarget->QueryInterface(NS_GET_IID(nsISupports), - NS_REINTERPRET_CAST(void **, &mTarget)); + CallQueryInterface(aTarget, &mTarget); if (mTarget) // We keep a weak-ref, so remove the reference the QI added. mTarget->Release(); Index: mozilla/dom/src/base/nsGlobalWindow.cpp =================================================================== RCS file: /cvsroot/mozilla/dom/src/base/nsGlobalWindow.cpp,v retrieving revision 1.898 diff -u -r1.898 mozilla/dom/src/base/nsGlobalWindow.cpp --- mozilla/dom/src/base/nsGlobalWindow.cpp +++ mozilla/dom/src/base/nsGlobalWindow.cpp @@ -5684,8 +5684,7 @@ rv = compStyle->Init(aElt, aPseudoElt, presShell); NS_ENSURE_SUCCESS(rv, rv); - return compStyle->QueryInterface(NS_GET_IID(nsIDOMCSSStyleDeclaration), - (void **) aReturn); + return CallQueryInterface(compStyle, aReturn); } //***************************************************************************** Index: mozilla/dom/src/base/nsJSEnvironment.cpp =================================================================== RCS file: /cvsroot/mozilla/dom/src/base/nsJSEnvironment.cpp,v retrieving revision 1.307 diff -u -r1.307 mozilla/dom/src/base/nsJSEnvironment.cpp --- mozilla/dom/src/base/nsJSEnvironment.cpp +++ mozilla/dom/src/base/nsJSEnvironment.cpp @@ -102,6 +102,7 @@ #include "nsIObjectOutputStream.h" #include "nsITimelineService.h" #include "nsDOMScriptObjectHolder.h" +#include "nsArrayUtils.h" #include "prmem.h" #ifdef NS_DEBUG @@ -2332,10 +2333,8 @@ if (argsArray) { for (argCtr = 0; argCtr < argCount && NS_SUCCEEDED(rv); argCtr++) { - nsCOMPtr arg; + nsCOMPtr arg(do_QueryElementAt(argsArray, argCtr)); jsval *thisval = argv + argCtr; - argsArray->QueryElementAt(argCtr, NS_GET_IID(nsISupports), - getter_AddRefs(arg)); if (!arg) { *thisval = JSVAL_NULL; continue; @@ -3594,5 +3593,5 @@ delete ret; return rv; } - return ret->QueryInterface(NS_GET_IID(nsIArray), (void **)aArray); + return CallQueryInterface(ret, aArray); } Index: mozilla/dom/src/base/nsJSTimeoutHandler.cpp =================================================================== RCS file: /cvsroot/mozilla/dom/src/base/nsJSTimeoutHandler.cpp,v retrieving revision 1.4 diff -u -r1.4 mozilla/dom/src/base/nsJSTimeoutHandler.cpp --- mozilla/dom/src/base/nsJSTimeoutHandler.cpp +++ mozilla/dom/src/base/nsJSTimeoutHandler.cpp @@ -336,6 +336,5 @@ delete handler; return rv; } - return handler->QueryInterface(NS_GET_IID(nsIScriptTimeoutHandler), - NS_REINTERPRET_CAST(void **, aRet)); + return CallQueryInterface(handler, aRet); } Index: mozilla/editor/composer/src/nsComposerCommandsUpdater.cpp =================================================================== RCS file: /cvsroot/mozilla/editor/composer/src/nsComposerCommandsUpdater.cpp,v retrieving revision 1.23 diff -u -r1.23 mozilla/editor/composer/src/nsComposerCommandsUpdater.cpp --- mozilla/editor/composer/src/nsComposerCommandsUpdater.cpp +++ mozilla/editor/composer/src/nsComposerCommandsUpdater.cpp @@ -411,6 +411,5 @@ if (!newThang) return NS_ERROR_OUT_OF_MEMORY; - return newThang->QueryInterface(NS_GET_IID(nsISelectionListener), - (void **)aInstancePtrResult); + return CallQueryInterface(newThang, aInstancePtrResult); } Index: mozilla/editor/composer/src/nsEditingSession.cpp =================================================================== RCS file: /cvsroot/mozilla/editor/composer/src/nsEditingSession.cpp,v retrieving revision 1.47 diff -u -r1.47 mozilla/editor/composer/src/nsEditingSession.cpp --- mozilla/editor/composer/src/nsEditingSession.cpp +++ mozilla/editor/composer/src/nsEditingSession.cpp @@ -1183,8 +1183,7 @@ nsIDocShell *docShell = GetDocShellFromWindow(aWindow); if (!docShell) return NS_ERROR_FAILURE; - return docShell->QueryInterface(NS_GET_IID(nsIEditorDocShell), - (void **)outDocShell); + return CallQueryInterface(docShell, outDocShell); } /*--------------------------------------------------------------------------- Index: mozilla/editor/libeditor/base/EditAggregateTxn.cpp =================================================================== RCS file: /cvsroot/mozilla/editor/libeditor/base/EditAggregateTxn.cpp,v retrieving revision 1.33 diff -u -r1.33 mozilla/editor/libeditor/base/EditAggregateTxn.cpp --- mozilla/editor/libeditor/base/EditAggregateTxn.cpp +++ mozilla/editor/libeditor/base/EditAggregateTxn.cpp @@ -158,8 +158,8 @@ if (mChildren && aTxn) { // aaahhhh! broken interfaces drive me crazy!!! - nsCOMPtr isupports; - aTxn->QueryInterface(NS_GET_IID(nsISupports), getter_AddRefs(isupports)); + nsCOMPtr isupports = + do_QueryInterface(NS_ISUPPORTS_CAST(nsITransaction *, aTxn)); mChildren->AppendElement(isupports); return NS_OK; } Index: mozilla/editor/libeditor/base/PlaceholderTxn.cpp =================================================================== RCS file: /cvsroot/mozilla/editor/libeditor/base/PlaceholderTxn.cpp,v retrieving revision 1.34 diff -u -r1.34 mozilla/editor/libeditor/base/PlaceholderTxn.cpp --- mozilla/editor/libeditor/base/PlaceholderTxn.cpp +++ mozilla/editor/libeditor/base/PlaceholderTxn.cpp @@ -60,23 +60,10 @@ NS_IMPL_ADDREF_INHERITED(PlaceholderTxn, EditAggregateTxn) NS_IMPL_RELEASE_INHERITED(PlaceholderTxn, EditAggregateTxn) -//NS_IMPL_QUERY_INTERFACE_INHERITED1(Class, Super, AdditionalInterface) -NS_IMETHODIMP PlaceholderTxn::QueryInterface(REFNSIID aIID, void** aInstancePtr) -{ - if (!aInstancePtr) return NS_ERROR_NULL_POINTER; - - if (aIID.Equals(NS_GET_IID(nsIAbsorbingTransaction))) { - *aInstancePtr = (nsISupports*)(nsIAbsorbingTransaction*)(this); - NS_ADDREF_THIS(); - return NS_OK; - } - if (aIID.Equals(NS_GET_IID(nsISupportsWeakReference))) { - *aInstancePtr = (nsISupports*)(nsISupportsWeakReference*) this; - NS_ADDREF_THIS(); - return NS_OK; - } - return EditAggregateTxn::QueryInterface(aIID, aInstancePtr); -} +NS_INTERFACE_MAP_BEGIN(PlaceholderTxn) + NS_INTERFACE_MAP_ENTRY(nsIAbsorbingTransaction) + NS_INTERFACE_MAP_ENTRY(nsISupportsWeakReference) +NS_INTERFACE_MAP_END_INHERITING(EditAggregateTxn) NS_IMETHODIMP PlaceholderTxn::Init(nsIAtom *aName, nsSelectionState *aSelState, nsIEditor *aEditor) { @@ -148,10 +135,8 @@ EditTxn *editTxn = (EditTxn*)aTransaction; //XXX: hack, not safe! need nsIEditTransaction! // determine if this incoming txn is a placeholder txn - nsCOMPtr plcTxn;// = do_QueryInterface(editTxn); - // can't do_QueryInterface() above due to our broken transaction interfaces. - // instead have to brute it below. ugh. - editTxn->QueryInterface(NS_GET_IID(nsIAbsorbingTransaction), getter_AddRefs(plcTxn)); + nsCOMPtr plcTxn = + do_QueryInterface(NS_ISUPPORTS_CAST(nsITransaction*, editTxn)); // we are absorbing all txn's if mAbsorb is lit. if (mAbsorb) @@ -199,10 +184,8 @@ (mName.get() == nsEditor::gDeleteTxnName)) && !mCommitted ) { - nsCOMPtr plcTxn;// = do_QueryInterface(editTxn); - // can't do_QueryInterface() above due to our broken transaction interfaces. - // instead have to brute it below. ugh. - editTxn->QueryInterface(NS_GET_IID(nsIAbsorbingTransaction), getter_AddRefs(plcTxn)); + nsCOMPtr plcTxn = + do_QueryInterface(NS_STATIC_CAST(nsITransaction*, editTxn)); if (plcTxn) { nsCOMPtr atom; Index: mozilla/editor/libeditor/base/nsEditor.cpp =================================================================== RCS file: /cvsroot/mozilla/editor/libeditor/base/nsEditor.cpp,v retrieving revision 1.479 diff -u -r1.479 mozilla/editor/libeditor/base/nsEditor.cpp --- mozilla/editor/libeditor/base/nsEditor.cpp +++ mozilla/editor/libeditor/base/nsEditor.cpp @@ -651,10 +651,8 @@ if (!editTxn) { return NS_ERROR_NULL_POINTER; } // Then we QI to an nsIAbsorbingTransaction to get at placeholder functionality - nsCOMPtr plcTxn; - editTxn->QueryInterface(NS_GET_IID(nsIAbsorbingTransaction), getter_AddRefs(plcTxn)); - // have to use line above instead of "plcTxn = do_QueryInterface(editTxn);" - // due to our broken interface model for transactions. + nsCOMPtr plcTxn = + do_QueryInterface(NS_STATIC_CAST(nsITransaction*, editTxn)); // save off weak reference to placeholder txn mPlaceHolderTxn = do_GetWeakReference(plcTxn); Index: mozilla/editor/libeditor/html/nsHTMLEditRules.cpp =================================================================== RCS file: /cvsroot/mozilla/editor/libeditor/html/nsHTMLEditRules.cpp,v retrieving revision 1.329 diff -u -r1.329 mozilla/editor/libeditor/html/nsHTMLEditRules.cpp --- mozilla/editor/libeditor/html/nsHTMLEditRules.cpp +++ mozilla/editor/libeditor/html/nsHTMLEditRules.cpp @@ -176,9 +176,10 @@ NS_NewHTMLEditRules(nsIEditRules** aInstancePtrResult) { nsHTMLEditRules * rules = new nsHTMLEditRules(); - if (rules) - return rules->QueryInterface(NS_GET_IID(nsIEditRules), (void**) aInstancePtrResult); - return NS_ERROR_OUT_OF_MEMORY; + if (!rules) + return NS_ERROR_OUT_OF_MEMORY; + + return CallQueryInterface(rules, aInstancePtrResult); } /******************************************************** Index: mozilla/editor/libeditor/html/nsHTMLEditorMouseListener.cpp =================================================================== RCS file: /cvsroot/mozilla/editor/libeditor/html/nsHTMLEditorMouseListener.cpp,v retrieving revision 1.18 diff -u -r1.18 mozilla/editor/libeditor/html/nsHTMLEditorMouseListener.cpp --- mozilla/editor/libeditor/html/nsHTMLEditorMouseListener.cpp +++ mozilla/editor/libeditor/html/nsHTMLEditorMouseListener.cpp @@ -315,5 +315,5 @@ if (!listener) return NS_ERROR_OUT_OF_MEMORY; - return listener->QueryInterface(NS_GET_IID(nsIDOMEventListener), (void **) aInstancePtrResult); + return CallQueryInterface(listener, aInstancePtrResult); } Index: mozilla/editor/libeditor/html/nsHTMLURIRefObject.cpp =================================================================== RCS file: /cvsroot/mozilla/editor/libeditor/html/nsHTMLURIRefObject.cpp,v retrieving revision 1.13 diff -u -r1.13 mozilla/editor/libeditor/html/nsHTMLURIRefObject.cpp --- mozilla/editor/libeditor/html/nsHTMLURIRefObject.cpp +++ mozilla/editor/libeditor/html/nsHTMLURIRefObject.cpp @@ -326,7 +326,6 @@ delete refObject; return rv; } - return refObject->QueryInterface(NS_GET_IID(nsIURIRefObject), - (void**)aResult); + return CallQueryInterface(refObject, aResult); } Index: mozilla/editor/libeditor/html/nsTableEditor.cpp =================================================================== RCS file: /cvsroot/mozilla/editor/libeditor/html/nsTableEditor.cpp,v retrieving revision 1.76 diff -u -r1.76 mozilla/editor/libeditor/html/nsTableEditor.cpp Index: mozilla/editor/libeditor/text/nsEditorEventListeners.cpp =================================================================== RCS file: /cvsroot/mozilla/editor/libeditor/text/nsEditorEventListeners.cpp,v retrieving revision 1.241 diff -u -r1.241 mozilla/editor/libeditor/text/nsEditorEventListeners.cpp --- mozilla/editor/libeditor/text/nsEditorEventListeners.cpp +++ mozilla/editor/libeditor/text/nsEditorEventListeners.cpp @@ -320,7 +320,7 @@ do_GetService(NS_PREFSERVICE_CONTRACTID, &rv); if (NS_SUCCEEDED(rv) && prefBranch) { - PRBool doMiddleMousePaste = PR_FALSE;; + PRBool doMiddleMousePaste = PR_FALSE; rv = prefBranch->GetBoolPref("middlemouse.paste", &doMiddleMousePaste); if (NS_SUCCEEDED(rv) && doMiddleMousePaste) { @@ -420,7 +420,7 @@ nsTextEditorTextListener::nsTextEditorTextListener() : mCommitText(PR_FALSE), - mInTransaction(PR_FALSE) + mInTransaction(PR_FALSE) { } @@ -433,7 +433,7 @@ nsTextEditorTextListener::HandleEvent(nsIDOMEvent* aEvent) { #ifdef DEBUG_IME - printf("nsTextEditorTextListener::HandleEvent\n"); + printf("nsTextEditorTextListener::HandleEvent\n"); #endif return NS_OK; } @@ -444,39 +444,39 @@ nsTextEditorTextListener::HandleText(nsIDOMEvent* aTextEvent) { #ifdef DEBUG_IME - printf("nsTextEditorTextListener::HandleText\n"); + printf("nsTextEditorTextListener::HandleText\n"); #endif - nsCOMPtr textEvent = do_QueryInterface(aTextEvent); - if (!textEvent) { - //non-ui event passed in. bad things. - return NS_OK; - } - - nsAutoString composedText; - nsresult result; - nsIPrivateTextRangeList *textRangeList; - nsTextEventReply *textEventReply; - - textEvent->GetText(composedText); - textEvent->GetInputRange(&textRangeList); - textEvent->GetEventReply(&textEventReply); - textRangeList->AddRef(); - nsCOMPtr imeEditor = do_QueryInterface(mEditor, &result); - if (imeEditor) { - PRUint32 flags; - // if we are readonly or disabled, then do nothing. - if (NS_SUCCEEDED(mEditor->GetFlags(&flags))) { - if (flags & nsIPlaintextEditor::eEditorReadonlyMask || - flags & nsIPlaintextEditor::eEditorDisabledMask) { + nsCOMPtr textEvent = do_QueryInterface(aTextEvent); + if (!textEvent) { + //non-ui event passed in. bad things. + return NS_OK; + } + + nsAutoString composedText; + nsresult result; + nsIPrivateTextRangeList *textRangeList; + nsTextEventReply *textEventReply; + + textEvent->GetText(composedText); + textEvent->GetInputRange(&textRangeList); + textEvent->GetEventReply(&textEventReply); + textRangeList->AddRef(); + nsCOMPtr imeEditor = do_QueryInterface(mEditor, &result); + if (imeEditor) { + PRUint32 flags; + // if we are readonly or disabled, then do nothing. + if (NS_SUCCEEDED(mEditor->GetFlags(&flags))) { + if (flags & nsIPlaintextEditor::eEditorReadonlyMask || + flags & nsIPlaintextEditor::eEditorDisabledMask) { #if DEBUG_IME - printf("nsTextEditorTextListener::HandleText, Readonly or Disabled\n"); + printf("nsTextEditorTextListener::HandleText, Readonly or Disabled\n"); #endif - return NS_OK; - } - } - result = imeEditor->SetCompositionString(composedText,textRangeList,textEventReply); - } - return result; + return NS_OK; + } + } + result = imeEditor->SetCompositionString(composedText,textRangeList,textEventReply); + } + return result; } /* @@ -785,7 +785,7 @@ nsTextEditorCompositionListener::HandleEvent(nsIDOMEvent* aEvent) { #ifdef DEBUG_IME - printf("nsTextEditorCompositionListener::HandleEvent\n"); + printf("nsTextEditorCompositionListener::HandleEvent\n"); #endif return NS_OK; } @@ -803,7 +803,7 @@ nsTextEditorCompositionListener::HandleStartComposition(nsIDOMEvent* aCompositionEvent) { #ifdef DEBUG_IME - printf("nsTextEditorCompositionListener::HandleStartComposition\n"); + printf("nsTextEditorCompositionListener::HandleStartComposition\n"); #endif nsCOMPtr pCompositionEvent = do_QueryInterface(aCompositionEvent); if (!pCompositionEvent) return NS_ERROR_FAILURE; @@ -818,7 +818,7 @@ nsTextEditorCompositionListener::HandleQueryComposition(nsIDOMEvent* aCompositionEvent) { #ifdef DEBUG_IME - printf("nsTextEditorCompositionListener::HandleQueryComposition\n"); + printf("nsTextEditorCompositionListener::HandleQueryComposition\n"); #endif nsCOMPtr pCompositionEvent = do_QueryInterface(aCompositionEvent); if (!pCompositionEvent) return NS_ERROR_FAILURE; @@ -834,9 +834,9 @@ nsTextEditorCompositionListener::HandleEndComposition(nsIDOMEvent* aCompositionEvent) { #ifdef DEBUG_IME - printf("nsTextEditorCompositionListener::HandleEndComposition\n"); + printf("nsTextEditorCompositionListener::HandleEndComposition\n"); #endif - return mEditor->EndComposition(); + return mEditor->EndComposition(); } @@ -893,7 +893,7 @@ it->SetEditor(aEditor); - return it->QueryInterface(NS_GET_IID(nsIDOMEventListener), (void **) aInstancePtrResult); + return CallQueryInterface(it, aInstancePtrResult); } @@ -909,21 +909,21 @@ it->SetEditor(aEditor); - return it->QueryInterface(NS_GET_IID(nsIDOMEventListener), (void **) aInstancePtrResult); + return CallQueryInterface(it, aInstancePtrResult); } nsresult NS_NewEditorTextListener(nsIDOMEventListener** aInstancePtrResult, nsIEditor* aEditor) { - nsTextEditorTextListener* it = new nsTextEditorTextListener(); - if (nsnull==it) { - return NS_ERROR_OUT_OF_MEMORY; - } + nsTextEditorTextListener* it = new nsTextEditorTextListener(); + if (nsnull==it) { + return NS_ERROR_OUT_OF_MEMORY; + } - it->SetEditor(aEditor); + it->SetEditor(aEditor); - return it->QueryInterface(NS_GET_IID(nsIDOMEventListener), (void **) aInstancePtrResult); + return CallQueryInterface(it, aInstancePtrResult); } @@ -940,18 +940,18 @@ it->SetEditor(aEditor); it->SetPresShell(aPresShell); - return it->QueryInterface(NS_GET_IID(nsIDOMEventListener), (void **) aInstancePtrResult); + return CallQueryInterface(it, aInstancePtrResult); } nsresult NS_NewEditorCompositionListener(nsIDOMEventListener** aInstancePtrResult, nsIEditor* aEditor) { - nsTextEditorCompositionListener* it = new nsTextEditorCompositionListener(); - if (nsnull==it) { - return NS_ERROR_OUT_OF_MEMORY; - } - it->SetEditor(aEditor); - return it->QueryInterface(NS_GET_IID(nsIDOMEventListener), (void **) aInstancePtrResult); + nsTextEditorCompositionListener* it = new nsTextEditorCompositionListener(); + if (nsnull==it) { + return NS_ERROR_OUT_OF_MEMORY; + } + it->SetEditor(aEditor); + return CallQueryInterface(it, aInstancePtrResult); } nsresult @@ -963,7 +963,7 @@ return NS_ERROR_OUT_OF_MEMORY; } it->SetEditor(aEditor); - return it->QueryInterface(NS_GET_IID(nsIDOMEventListener), (void **) aInstancePtrResult); + return CallQueryInterface(it, aInstancePtrResult); } Index: mozilla/editor/libeditor/text/nsTextEditRules.cpp =================================================================== RCS file: /cvsroot/mozilla/editor/libeditor/text/nsTextEditRules.cpp,v retrieving revision 1.205 diff -u -r1.205 mozilla/editor/libeditor/text/nsTextEditRules.cpp --- mozilla/editor/libeditor/text/nsTextEditRules.cpp +++ mozilla/editor/libeditor/text/nsTextEditRules.cpp @@ -81,9 +81,10 @@ NS_NewTextEditRules(nsIEditRules** aInstancePtrResult) { nsTextEditRules * rules = new nsTextEditRules(); - if (rules) - return rules->QueryInterface(NS_GET_IID(nsIEditRules), (void**) aInstancePtrResult); - return NS_ERROR_OUT_OF_MEMORY; + if (!rules) + return NS_ERROR_OUT_OF_MEMORY; + + return CallQueryInterface(rules, aInstancePtrResult); } Index: mozilla/editor/txmgr/tests/TestTXMgr.cpp =================================================================== RCS file: /cvsroot/mozilla/editor/txmgr/tests/TestTXMgr.cpp,v retrieving revision 1.49 diff -u -r1.49 mozilla/editor/txmgr/tests/TestTXMgr.cpp --- mozilla/editor/txmgr/tests/TestTXMgr.cpp +++ mozilla/editor/txmgr/tests/TestTXMgr.cpp @@ -684,7 +684,7 @@ } nsITransaction *tx = 0; - result = tximpl->QueryInterface(NS_GET_IID(nsITransaction), (void **)&tx); + result = CallQueryInterface(tximpl, &tx); if (NS_FAILED(result)) { printf("ERROR: QueryInterface() failed for transaction %d, level %d. (%d)\n", i, mLevel, result); @@ -1077,7 +1077,7 @@ tx = 0; - result = tximpl->QueryInterface(NS_GET_IID(nsITransaction), (void **)&tx); + result = CallQueryInterface(tximpl, &tx); if (NS_FAILED(result)) { printf("ERROR: QueryInterface() failed for initial transaction. (%d)\n", @@ -1128,7 +1128,7 @@ } tx = 0; - result = tximpl->QueryInterface(NS_GET_IID(nsITransaction), (void **)&tx); + result = CallQueryInterface(tximpl, &tx); if (NS_FAILED(result)) { printf("ERROR: QueryInterface() failed for transaction %d. (%d)\n", i, result); @@ -1227,7 +1227,7 @@ } tx = 0; - result = tximpl->QueryInterface(NS_GET_IID(nsITransaction), (void **)&tx); + result = CallQueryInterface(tximpl, &tx); if (NS_FAILED(result)) { printf("ERROR: QueryInterface() failed for transaction %d. (%d)\n", i, result); @@ -1311,7 +1311,7 @@ } tx = 0; - result = tximpl->QueryInterface(NS_GET_IID(nsITransaction), (void **)&tx); + result = CallQueryInterface(tximpl, &tx); if (NS_FAILED(result)) { printf("ERROR: QueryInterface() failed for transaction %d. (%d)\n", i, result); @@ -1496,7 +1496,7 @@ tx = 0; - result = tximpl->QueryInterface(NS_GET_IID(nsITransaction), (void **)&tx); + result = CallQueryInterface(tximpl, &tx); if (NS_FAILED(result)) { printf("ERROR: QueryInterface() failed for transaction. (%d)\n", result); @@ -1640,7 +1640,7 @@ } tx = 0; - result = tximpl->QueryInterface(NS_GET_IID(nsITransaction), (void **)&tx); + result = CallQueryInterface(tximpl, &tx); if (NS_FAILED(result)) { printf("ERROR: QueryInterface() failed for transaction %d. (%d)\n", i, result); @@ -1703,7 +1703,7 @@ tx = 0; - result = tximpl->QueryInterface(NS_GET_IID(nsITransaction), (void **)&tx); + result = CallQueryInterface(tximpl, &tx); if (NS_FAILED(result)) { printf("ERROR: QueryInterface() failed for transaction. (%d)\n", result); @@ -1814,7 +1814,7 @@ tx = 0; - result = tximpl->QueryInterface(NS_GET_IID(nsITransaction), (void **)&tx); + result = CallQueryInterface(tximpl, &tx); if (NS_FAILED(result)) { printf("ERROR: QueryInterface() failed for transaction. (%d)\n", result); @@ -1932,7 +1932,7 @@ tx = 0; - result = tximpl->QueryInterface(NS_GET_IID(nsITransaction), (void **)&tx); + result = CallQueryInterface(tximpl, &tx); if (NS_FAILED(result)) { printf("ERROR: QueryInterface() failed for RedoErrorTransaction. (%d)\n", @@ -1962,7 +1962,7 @@ tx = 0; - result = tximpl->QueryInterface(NS_GET_IID(nsITransaction), (void **)&tx); + result = CallQueryInterface(tximpl, &tx); if (NS_FAILED(result)) { printf("ERROR: QueryInterface() failed for transaction. (%d)\n", result); @@ -2133,7 +2133,7 @@ } tx = 0; - result = tximpl->QueryInterface(NS_GET_IID(nsITransaction), (void **)&tx); + result = CallQueryInterface(tximpl, &tx); if (NS_FAILED(result)) { printf("ERROR: QueryInterface() failed for transaction %d. (%d)\n", i, result); @@ -2207,7 +2207,7 @@ } tx = 0; - result = tximpl->QueryInterface(NS_GET_IID(nsITransaction), (void **)&tx); + result = CallQueryInterface(tximpl, &tx); if (NS_FAILED(result)) { printf("ERROR: QueryInterface() failed for transaction %d. (%d)\n", i, result); @@ -2589,7 +2589,7 @@ } tx = 0; - result = tximpl->QueryInterface(NS_GET_IID(nsITransaction), (void **)&tx); + result = CallQueryInterface(tximpl, &tx); if (NS_FAILED(result)) { printf("ERROR: QueryInterface() failed for transaction %d. (%d)\n", i, result); @@ -2922,7 +2922,7 @@ } tx = 0; - result = tximpl->QueryInterface(NS_GET_IID(nsITransaction), (void **)&tx); + result = CallQueryInterface(tximpl, &tx); if (NS_FAILED(result)) { printf("ERROR: QueryInterface() failed for transaction %d. (%d)\n", i, result); @@ -3020,7 +3020,7 @@ } tx = 0; - result = tximpl->QueryInterface(NS_GET_IID(nsITransaction), (void **)&tx); + result = CallQueryInterface(tximpl, &tx); if (NS_FAILED(result)) { printf("ERROR: QueryInterface() failed for transaction %d. (%d)\n", i, result); @@ -3125,7 +3125,7 @@ } tx = 0; - result = tximpl->QueryInterface(NS_GET_IID(nsITransaction), (void **)&tx); + result = CallQueryInterface(tximpl, &tx); if (NS_FAILED(result)) { printf("ERROR: QueryInterface() failed for transaction. (%d)\n", result); return result; @@ -3168,7 +3168,7 @@ } tx = 0; - result = tximpl->QueryInterface(NS_GET_IID(nsITransaction), (void **)&tx); + result = CallQueryInterface(tximpl, &tx); if (NS_FAILED(result)) { printf("ERROR: QueryInterface() failed for transaction. (%d)\n", result); return result; @@ -3211,7 +3211,7 @@ } tx = 0; - result = tximpl->QueryInterface(NS_GET_IID(nsITransaction), (void **)&tx); + result = CallQueryInterface(tximpl, &tx); if (NS_FAILED(result)) { printf("ERROR: QueryInterface() failed for transaction. (%d)\n", result); return result; @@ -3571,7 +3571,7 @@ } tx = 0; - result = tximpl->QueryInterface(NS_GET_IID(nsITransaction), (void **)&tx); + result = CallQueryInterface(tximpl, &tx); if (NS_FAILED(result)) { printf("ERROR: QueryInterface() failed for transaction %d. (%d)\n", i, result); @@ -3717,8 +3717,7 @@ } tx = 0; - - result = tximpl->QueryInterface(NS_GET_IID(nsITransaction), (void **)&tx); + result = CallQueryInterface(tximpl, &tx); if (NS_FAILED(result)) { printf("ERROR: QueryInterface() failed for transaction. (%d)\n", result); @@ -3842,8 +3841,7 @@ } tx = 0; - - result = tximpl->QueryInterface(NS_GET_IID(nsITransaction), (void **)&tx); + result = CallQueryInterface(tximpl, &tx); if (NS_FAILED(result)) { printf("ERROR: QueryInterface() failed for transaction. (%d)\n", result); @@ -3974,8 +3972,7 @@ } tx = 0; - - result = tximpl->QueryInterface(NS_GET_IID(nsITransaction), (void **)&tx); + result = CallQueryInterface(tximpl, &tx); if (NS_FAILED(result)) { printf("ERROR: QueryInterface() failed for RedoErrorTransaction. (%d)\n", @@ -4018,8 +4015,7 @@ } tx = 0; - - result = tximpl->QueryInterface(NS_GET_IID(nsITransaction), (void **)&tx); + result = CallQueryInterface(tximpl, &tx); if (NS_FAILED(result)) { printf("ERROR: QueryInterface() failed for transaction. (%d)\n", result); @@ -4190,7 +4186,7 @@ } tx = 0; - result = tximpl->QueryInterface(NS_GET_IID(nsITransaction), (void **)&tx); + result = CallQueryInterface(tximpl, &tx); if (NS_FAILED(result)) { printf("ERROR: QueryInterface() failed for transaction %d. (%d)\n", i, result); @@ -4277,7 +4273,7 @@ } tx = 0; - result = tximpl->QueryInterface(NS_GET_IID(nsITransaction), (void **)&tx); + result = CallQueryInterface(tximpl, &tx); if (NS_FAILED(result)) { printf("ERROR: QueryInterface() failed for transaction %d. (%d)\n", i, result); @@ -4498,7 +4494,7 @@ } tx = 0; - result = tximpl->QueryInterface(NS_GET_IID(nsITransaction), (void **)&tx); + result = CallQueryInterface(tximpl, &tx); if (NS_FAILED(result)) { printf("ERROR: QueryInterface() failed for transaction %d. (%d)\n", i, result); Index: mozilla/editor/txtsvc/src/nsTextServicesDocument.cpp =================================================================== RCS file: /cvsroot/mozilla/editor/txtsvc/src/nsTextServicesDocument.cpp,v retrieving revision 1.61 diff -u -r1.61 mozilla/editor/txtsvc/src/nsTextServicesDocument.cpp --- mozilla/editor/txtsvc/src/nsTextServicesDocument.cpp +++ mozilla/editor/txtsvc/src/nsTextServicesDocument.cpp @@ -2778,23 +2778,20 @@ if (!bodyElement) return NS_ERROR_FAILURE; - result = bodyElement->QueryInterface(NS_GET_IID(nsIDOMNode), (void **)aNode); + result = CallQueryInterface(bodyElement, aNode); } else { // For non-HTML documents, the content root node will be the document element. - nsCOMPtr docElement; - - result = mDOMDocument->GetDocumentElement(getter_AddRefs(docElement)); - + nsCOMPtr docElement(do_QueryInterface(mDOMDocument, &result)); if (NS_FAILED(result)) return result; if (!docElement) return NS_ERROR_FAILURE; - result = docElement->QueryInterface(NS_GET_IID(nsIDOMNode), (void **)aNode); + result = CallQueryInterface(docElement, aNode); } return result; Index: mozilla/embedding/base/nsEmbedAPI.cpp =================================================================== RCS file: /cvsroot/mozilla/embedding/base/nsEmbedAPI.cpp,v retrieving revision 1.47 diff -u -r1.47 mozilla/embedding/base/nsEmbedAPI.cpp --- mozilla/embedding/base/nsEmbedAPI.cpp +++ mozilla/embedding/base/nsEmbedAPI.cpp @@ -116,8 +116,7 @@ { #ifdef DEBUG nsIComponentRegistrar *registrar; - rv = sServiceManager->QueryInterface(NS_GET_IID(nsIComponentRegistrar), - (void **) ®istrar); + rv = CallQueryInterface(sServiceManager, ®istrar); if (NS_FAILED(rv)) { NS_WARNING("Could not QI to registrar"); @@ -161,8 +160,7 @@ } nsIComponentManager *compMgr; - rv = sServiceManager->QueryInterface(NS_GET_IID(nsIComponentManager), - (void **) &compMgr); + rv = CallQueryInterface(sServiceManager, &compMgr); if (NS_FAILED(rv)) return rv; Index: mozilla/embedding/browser/activex/src/common/IWebBrowserImpl.h =================================================================== RCS file: /cvsroot/mozilla/embedding/browser/activex/src/common/IWebBrowserImpl.h,v retrieving revision 1.5 diff -u -r1.5 mozilla/embedding/browser/activex/src/common/IWebBrowserImpl.h --- mozilla/embedding/browser/activex/src/common/IWebBrowserImpl.h +++ mozilla/embedding/browser/activex/src/common/IWebBrowserImpl.h @@ -181,8 +181,8 @@ { nsCOMPtr homePage; prefBranch->GetComplexValue("browser.startup.homepage", - NS_GET_IID(nsIPrefLocalizedString), - getter_AddRefs(homePage)); + NS_GET_IID(nsIPrefLocalizedString), + getter_AddRefs(homePage)); if (homePage) { Index: mozilla/embedding/browser/activex/src/control/MozillaBrowser.cpp =================================================================== RCS file: /cvsroot/mozilla/embedding/browser/activex/src/control/MozillaBrowser.cpp,v retrieving revision 1.115 diff -u -r1.115 mozilla/embedding/browser/activex/src/control/MozillaBrowser.cpp --- mozilla/embedding/browser/activex/src/control/MozillaBrowser.cpp +++ mozilla/embedding/browser/activex/src/control/MozillaBrowser.cpp @@ -797,7 +797,7 @@ // Load the view-source into a new url if ((bCancel == VARIANT_FALSE) && spDispNew) { - CIPtr(IWebBrowser2) spOther = spDispNew;; + CIPtr(IWebBrowser2) spOther = spDispNew; if (spOther) { // tack in the viewsource command @@ -1445,7 +1445,7 @@ hr = CoCreateInstance(clsid, NULL, CLSCTX_INPROC_SERVER, IID_IObjectWithSite, (LPVOID *) &cpObjectWithSite); if (FAILED(hr)) { - NG_TRACE(_T("Registered browser helper object cannot be created\n"));; + NG_TRACE(_T("Registered browser helper object cannot be created\n")); } else { @@ -1731,7 +1731,7 @@ { NS_ENSURE_ARG_POINTER(aWebNav); if (!mWebBrowser) return NS_ERROR_FAILURE; - return mWebBrowser->QueryInterface(NS_GET_IID(nsIWebNavigation), (void **) aWebNav); + return CallQueryInterface(mWebBrowser, aWebNav); } nsresult CMozillaBrowser::GetDOMWindow(nsIDOMWindow **aDOMWindow) Index: mozilla/embedding/browser/activex/src/plugin/XPConnect.cpp =================================================================== RCS file: /cvsroot/mozilla/embedding/browser/activex/src/plugin/XPConnect.cpp,v retrieving revision 1.32 diff -u -r1.32 mozilla/embedding/browser/activex/src/plugin/XPConnect.cpp --- mozilla/embedding/browser/activex/src/plugin/XPConnect.cpp +++ mozilla/embedding/browser/activex/src/plugin/XPConnect.cpp @@ -97,32 +97,17 @@ NS_IMPL_RELEASE(nsScriptablePeer) // Custom QueryInterface impl to deal with the IDispatch tearoff -NS_IMETHODIMP -nsScriptablePeer::QueryInterface(const nsIID & aIID, void **aInstancePtr) -{ - NS_ASSERTION(aInstancePtr, "QueryInterface requires a non-NULL destination!"); - if (!aInstancePtr) - return NS_ERROR_NULL_POINTER; - *aInstancePtr = nsnull; - - nsISupports* foundInterface = nsnull; - if (aIID.Equals(NS_GET_IID(nsISupports))) - foundInterface = NS_STATIC_CAST(nsISupports *, NS_STATIC_CAST(nsIClassInfo *, this)); - else if (aIID.Equals(NS_GET_IID(nsIClassInfo))) - foundInterface = NS_STATIC_CAST(nsIClassInfo*, this); - else if (aIID.Equals(NS_GET_IID(nsIMozAxPlugin))) - foundInterface = NS_STATIC_CAST(nsIMozAxPlugin*, this); - else if (memcmp(&aIID, &__uuidof(IDispatch), sizeof(nsID)) == 0) +NS_INTERFACE_MAP_BEGIN(nsScriptablePeer) + NS_INTERFACE_MAP_ENTRY_AMBIGUOUS(nsISupports, nsIClassInfo) + NS_INTERFACE_MAP_ENTRY(nsIClassInfo) + NS_INTERFACE_MAP_ENTRY(nsIMozAxPlugin) + if (memcmp(&aIID, &__uuidof(IDispatch), sizeof(nsID)) == 0) { HRESULT hr = mTearOff->QueryInterface(__uuidof(IDispatch), aInstancePtr); if (SUCCEEDED(hr)) return NS_OK; return E_FAIL; } - - NS_IF_ADDREF(foundInterface); - *aInstancePtr = foundInterface; - return (*aInstancePtr) ? NS_OK : NS_NOINTERFACE; -} +NS_INTERFACE_MAP_END HRESULT nsScriptablePeer::GetIDispatch(IDispatch **pdisp) Index: mozilla/embedding/browser/photon/src/nsUnknownContentTypeHandler.cpp =================================================================== RCS file: /cvsroot/mozilla/embedding/browser/photon/src/nsUnknownContentTypeHandler.cpp,v retrieving revision 1.31 diff -u -r1.31 mozilla/embedding/browser/photon/src/nsUnknownContentTypeHandler.cpp --- mozilla/embedding/browser/photon/src/nsUnknownContentTypeHandler.cpp +++ mozilla/embedding/browser/photon/src/nsUnknownContentTypeHandler.cpp @@ -172,33 +172,7 @@ #define interfaceName nsIHelperAppLauncherDialog #define contractId NS_IUNKNOWNCONTENTTYPEHANDLER_CONTRACTID -/* Component's implementation of Initialize. */ -/* nsISupports Implementation for the class */ -NS_IMPL_ADDREF( className ); -NS_IMPL_RELEASE( className ) - - -/* QueryInterface implementation for this class. */ -NS_IMETHODIMP className::QueryInterface( REFNSIID anIID, void **anInstancePtr ) { - nsresult rv = NS_OK; -///* ATENTIE */ printf("QueryInterface!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n\n\n"); - - /* Check for place to return result. */ - if( !anInstancePtr ) rv = NS_ERROR_NULL_POINTER; - else { - *anInstancePtr = 0; - if ( anIID.Equals( NS_GET_IID(nsIHelperAppLauncherDialog) ) ) { - *anInstancePtr = (void*) (nsIHelperAppLauncherDialog*)this; - NS_ADDREF_THIS(); - } - else if ( anIID.Equals( NS_GET_IID(nsISupports) ) ) { - *anInstancePtr = (void*) ( (nsISupports*) (interfaceName*)this ); - NS_ADDREF_THIS(); - } - else rv = NS_NOINTERFACE; - } - return rv; - } +NS_IMPL_ISUPPORTS1( className, nsIHelperAppLauncherDialog ); NS_GENERIC_FACTORY_CONSTRUCTOR( nsUnknownContentTypeHandler ) Index: mozilla/embedding/browser/powerplant/source/CAppFileLocationProvider.cpp =================================================================== RCS file: /cvsroot/mozilla/embedding/browser/powerplant/source/CAppFileLocationProvider.cpp,v retrieving revision 1.19 diff -u -r1.19 mozilla/embedding/browser/powerplant/source/CAppFileLocationProvider.cpp --- mozilla/embedding/browser/powerplant/source/CAppFileLocationProvider.cpp +++ mozilla/embedding/browser/powerplant/source/CAppFileLocationProvider.cpp @@ -114,7 +114,7 @@ } if (localFile && NS_SUCCEEDED(rv)) - rv = localFile->QueryInterface(NS_GET_IID(nsIFile), (void**)_retval); + rv = CallQueryInterface(localFile, _retval); return rv; } Index: mozilla/embedding/browser/powerplant/source/CBrowserShell.cpp =================================================================== RCS file: /cvsroot/mozilla/embedding/browser/powerplant/source/CBrowserShell.cpp,v retrieving revision 1.69 diff -u -r1.69 mozilla/embedding/browser/powerplant/source/CBrowserShell.cpp --- mozilla/embedding/browser/powerplant/source/CBrowserShell.cpp +++ mozilla/embedding/browser/powerplant/source/CBrowserShell.cpp @@ -921,7 +921,7 @@ NS_METHOD CBrowserShell::GetWebBrowserChrome(nsIWebBrowserChrome** aChrome) { NS_ENSURE_ARG_POINTER(aChrome); - return mChrome->QueryInterface(NS_GET_IID(nsIWebBrowserChrome), (void **)aChrome); + return CallQueryInterface(mChrome, aChrome); } NS_METHOD CBrowserShell::GetContentViewer(nsIContentViewer** aViewer) Index: mozilla/embedding/browser/webBrowser/nsCommandHandler.cpp =================================================================== RCS file: /cvsroot/mozilla/embedding/browser/webBrowser/nsCommandHandler.cpp,v retrieving revision 1.10 diff -u -r1.10 mozilla/embedding/browser/webBrowser/nsCommandHandler.cpp --- mozilla/embedding/browser/webBrowser/nsCommandHandler.cpp +++ mozilla/embedding/browser/webBrowser/nsCommandHandler.cpp @@ -87,7 +87,7 @@ if (tree->mTreeOwner) { nsresult rv; - rv = tree->mTreeOwner->QueryInterface(NS_GET_IID(nsICommandHandler), (void **)aCommandHandler); + rv = CallQueryInterface(tree->mTreeOwner, aCommandHandler); NS_RELEASE(treeOwner); return rv; } Index: mozilla/embedding/components/commandhandler/src/nsCommandGroup.cpp =================================================================== RCS file: /cvsroot/mozilla/embedding/components/commandhandler/src/nsCommandGroup.cpp,v retrieving revision 1.11 diff -u -r1.11 mozilla/embedding/components/commandhandler/src/nsCommandGroup.cpp --- mozilla/embedding/components/commandhandler/src/nsCommandGroup.cpp +++ mozilla/embedding/components/commandhandler/src/nsCommandGroup.cpp @@ -328,10 +328,10 @@ NS_IMETHODIMP nsControllerCommandGroup::GetGroupsEnumerator(nsISimpleEnumerator **_retval) { - nsGroupsEnumerator* groupsEnum = new nsGroupsEnumerator(mGroupsHash); + nsGroupsEnumerator* groupsEnum = new nsGroupsEnumerator(mGroupsHash); if (!groupsEnum) return NS_ERROR_OUT_OF_MEMORY; - return groupsEnum->QueryInterface(NS_GET_IID(nsISimpleEnumerator), (void **)_retval); + return CallQueryInterface(groupsEnum, _retval); } /* nsISimpleEnumerator getEnumeratorForGroup (in DOMString aGroup); */ @@ -341,10 +341,10 @@ nsCStringKey groupKey(aGroup); nsVoidArray* commandList = (nsVoidArray *)mGroupsHash.Get(&groupKey); // may be null - nsNamedGroupEnumerator* theGroupEnum = new nsNamedGroupEnumerator(commandList); + nsNamedGroupEnumerator* theGroupEnum = new nsNamedGroupEnumerator(commandList); if (!theGroupEnum) return NS_ERROR_OUT_OF_MEMORY; - return theGroupEnum->QueryInterface(NS_GET_IID(nsISimpleEnumerator), (void **)_retval); + return CallQueryInterface(theGroupEnum, _retval); } #if 0 Index: mozilla/embedding/components/find/src/nsFind.cpp =================================================================== RCS file: /cvsroot/mozilla/embedding/components/find/src/nsFind.cpp,v retrieving revision 1.41 diff -u -r1.41 mozilla/embedding/components/find/src/nsFind.cpp --- mozilla/embedding/components/find/src/nsFind.cpp +++ mozilla/embedding/components/find/src/nsFind.cpp @@ -441,7 +441,7 @@ if (!it) { return NS_ERROR_OUT_OF_MEMORY; } - return it->QueryInterface(NS_GET_IID(nsIContentIterator), (void **)aResult); + return CallQueryInterface(it, aResult); } // -------------------------------------------------------------------- Index: mozilla/embedding/components/find/src/nsWebBrowserFind.cpp =================================================================== RCS file: /cvsroot/mozilla/embedding/components/find/src/nsWebBrowserFind.cpp,v retrieving revision 1.49 diff -u -r1.49 mozilla/embedding/components/find/src/nsWebBrowserFind.cpp --- mozilla/embedding/components/find/src/nsWebBrowserFind.cpp +++ mozilla/embedding/components/find/src/nsWebBrowserFind.cpp @@ -477,8 +477,7 @@ rv = htmlDoc->GetBody(getter_AddRefs(bodyElement)); NS_ENSURE_SUCCESS(rv, rv); NS_ENSURE_ARG_POINTER(bodyElement); - return bodyElement->QueryInterface(NS_GET_IID(nsIDOMNode), - (void **)aNode); + return CallQueryInterface(bodyElement, aNode); } // For non-HTML documents, the content root node will be the doc element. @@ -486,7 +485,7 @@ rv = aDomDoc->GetDocumentElement(getter_AddRefs(docElement)); NS_ENSURE_SUCCESS(rv, rv); NS_ENSURE_ARG_POINTER(docElement); - return docElement->QueryInterface(NS_GET_IID(nsIDOMNode), (void **)aNode); + return CallQueryInterface(docElement, aNode); } nsresult nsWebBrowserFind::SetRangeAroundDocument(nsIDOMRange* aSearchRange, Index: mozilla/embedding/components/printingui/src/os2/nsPrintingPromptService.cpp =================================================================== RCS file: /cvsroot/mozilla/embedding/components/printingui/src/os2/nsPrintingPromptService.cpp,v retrieving revision 1.20 diff -u -r1.20 mozilla/embedding/components/printingui/src/os2/nsPrintingPromptService.cpp --- mozilla/embedding/components/printingui/src/os2/nsPrintingPromptService.cpp +++ mozilla/embedding/components/printingui/src/os2/nsPrintingPromptService.cpp @@ -130,28 +130,32 @@ nsIPrintSettings* printSettings, // ok to be null nsIObserver* openDialogObserver, // ok to be null PRBool isForPrinting, - nsIWebProgressListener** webProgressListener, - nsIPrintProgressParams** printProgressParams, - PRBool* notifyOnOpen) + nsIWebProgressListener** aWebProgressListener, + nsIPrintProgressParams** aPrintProgressParams, + PRBool* aNotifyOnOpen) { - NS_ENSURE_ARG(webProgressListener); - NS_ENSURE_ARG(printProgressParams); - NS_ENSURE_ARG(notifyOnOpen); + NS_ENSURE_ARG(aWebProgressListener); + NS_ENSURE_ARG(aPrintProgressParams); + NS_ENSURE_ARG(aNotifyOnOpen); - *notifyOnOpen = PR_FALSE; + *aNotifyOnOpen = PR_FALSE; nsPrintProgress* prtProgress = new nsPrintProgress(); - nsresult rv = prtProgress->QueryInterface(NS_GET_IID(nsIPrintProgress), (void**)getter_AddRefs(mPrintProgress)); + nsresult rv; + mPrintProgress = do_QueryInterface(prtProgress, &rv); NS_ENSURE_SUCCESS(rv, rv); - rv = prtProgress->QueryInterface(NS_GET_IID(nsIWebProgressListener), (void**)getter_AddRefs(mWebProgressListener)); + mWebProgressListener = do_QueryInterface(prtProgress, &rv); NS_ENSURE_SUCCESS(rv, rv); - nsPrintProgressParams* prtProgressParams = new nsPrintProgressParams(); - rv = prtProgressParams->QueryInterface(NS_GET_IID(nsIPrintProgressParams), (void**)printProgressParams); + nsRefPtr prtProgressParams = new nsPrintProgressParams(); + if (!prtProgressParams) + return NS_ERROR_OUT_OF_MEMORY; + + rv = CallQueryInterface(prtProgressParams.get(), aPrintProgressParams); NS_ENSURE_SUCCESS(rv, rv); - if (printProgressParams) + if (*aPrintProgressParams) { nsCOMPtr parentDOMIntl(do_QueryInterface(parent)); @@ -165,13 +169,13 @@ if (parentDOMIntl) { mPrintProgress->OpenProgressDialog(parentDOMIntl, - isForPrinting?kPrintProgressDialogURL:kPrtPrvProgressDialogURL, - *printProgressParams, openDialogObserver, notifyOnOpen); + isForPrinting ? kPrintProgressDialogURL : kPrtPrvProgressDialogURL, + *aPrintProgressParams, openDialogObserver, aNotifyOnOpen); } } - *webProgressListener = NS_STATIC_CAST(nsIWebProgressListener*, this); - NS_ADDREF(*webProgressListener); + *aWebProgressListener = NS_STATIC_CAST(nsIWebProgressListener*, this); + NS_ADDREF(*aWebProgressListener); return rv; } Index: mozilla/embedding/components/printingui/src/unixshared/nsPrintingPromptService.cpp =================================================================== RCS file: /cvsroot/mozilla/embedding/components/printingui/src/unixshared/nsPrintingPromptService.cpp,v retrieving revision 1.16 diff -u -r1.16 mozilla/embedding/components/printingui/src/unixshared/nsPrintingPromptService.cpp --- mozilla/embedding/components/printingui/src/unixshared/nsPrintingPromptService.cpp +++ mozilla/embedding/components/printingui/src/unixshared/nsPrintingPromptService.cpp @@ -125,25 +125,29 @@ nsIPrintSettings* printSettings, // ok to be null nsIObserver* openDialogObserver, // ok to be null PRBool isForPrinting, - nsIWebProgressListener** webProgressListener, - nsIPrintProgressParams** printProgressParams, - PRBool* notifyOnOpen) + nsIWebProgressListener** aWebProgressListener, + nsIPrintProgressParams** aPrintProgressParams, + PRBool* aNotifyOnOpen) { - NS_ENSURE_ARG(webProgressListener); - NS_ENSURE_ARG(printProgressParams); - NS_ENSURE_ARG(notifyOnOpen); - - *notifyOnOpen = PR_FALSE; - - nsPrintProgress* prtProgress = new nsPrintProgress(); - nsresult rv = prtProgress->QueryInterface(NS_GET_IID(nsIPrintProgress), (void**)getter_AddRefs(mPrintProgress)); + NS_ENSURE_ARG(aWebProgressListener); + NS_ENSURE_ARG(aPrintProgressParams); + NS_ENSURE_ARG(aNotifyOnOpen); + + *aNotifyOnOpen = PR_FALSE; + + nsRefPtr prtProgress = new nsPrintProgress(); + nsresult rv; + mPrintProgress = do_QueryInterface(prtProgress.get(), &rv); NS_ENSURE_SUCCESS(rv, rv); - rv = prtProgress->QueryInterface(NS_GET_IID(nsIWebProgressListener), (void**)getter_AddRefs(mWebProgressListener)); + mWebProgressListener = do_QueryInterface(prtProgress.get(), &rv); NS_ENSURE_SUCCESS(rv, rv); - nsPrintProgressParams* prtProgressParams = new nsPrintProgressParams(); - rv = prtProgressParams->QueryInterface(NS_GET_IID(nsIPrintProgressParams), (void**)printProgressParams); + nsRefPtr prtProgressParams = new nsPrintProgressParams(); + if (!prtProgressParams) + return NS_ERROR_OUT_OF_MEMORY; + + rv = CallQueryInterface(prtProgressParams.get(), aPrintProgressParams); NS_ENSURE_SUCCESS(rv, rv); if (printProgressParams) @@ -160,13 +164,13 @@ if (parentDOMIntl) { mPrintProgress->OpenProgressDialog(parentDOMIntl, - isForPrinting?kPrintProgressDialogURL:kPrtPrvProgressDialogURL, - *printProgressParams, openDialogObserver, notifyOnOpen); + isForPrinting ? kPrintProgressDialogURL : kPrtPrvProgressDialogURL, + *aPrintProgressParams, openDialogObserver, aNotifyOnOpen); } } - *webProgressListener = NS_STATIC_CAST(nsIWebProgressListener*, this); - NS_ADDREF(*webProgressListener); + *aWebProgressListener = NS_STATIC_CAST(nsIWebProgressListener*, this); + NS_ADDREF(*aWebProgressListener); return rv; } Index: mozilla/embedding/components/printingui/src/win/nsPrintingPromptService.cpp =================================================================== RCS file: /cvsroot/mozilla/embedding/components/printingui/src/win/nsPrintingPromptService.cpp,v retrieving revision 1.16 diff -u -r1.16 mozilla/embedding/components/printingui/src/win/nsPrintingPromptService.cpp --- mozilla/embedding/components/printingui/src/win/nsPrintingPromptService.cpp +++ mozilla/embedding/components/printingui/src/win/nsPrintingPromptService.cpp @@ -200,34 +200,38 @@ nsIPrintSettings* printSettings, // ok to be null nsIObserver* openDialogObserver, // ok to be null PRBool isForPrinting, - nsIWebProgressListener** webProgressListener, - nsIPrintProgressParams** printProgressParams, - PRBool* notifyOnOpen) + nsIWebProgressListener** aWebProgressListener, + nsIPrintProgressParams** aPrintProgressParams, + PRBool* aNotifyOnOpen) { - NS_ENSURE_ARG(webProgressListener); - NS_ENSURE_ARG(printProgressParams); - NS_ENSURE_ARG(notifyOnOpen); + NS_ENSURE_ARG(aWebProgressListener); + NS_ENSURE_ARG(aPrintProgressParams); + NS_ENSURE_ARG(aNotifyOnOpen); - *notifyOnOpen = PR_FALSE; + *oNotifyOnOpen = PR_FALSE; if (mPrintProgress) { - *webProgressListener = nsnull; - *printProgressParams = nsnull; + *aWebProgressListener = nsnull; + *aPrintProgressParams = nsnull; return NS_ERROR_FAILURE; } - nsPrintProgress* prtProgress = new nsPrintProgress(); - nsresult rv = prtProgress->QueryInterface(NS_GET_IID(nsIPrintProgress), (void**)getter_AddRefs(mPrintProgress)); + nsRefPtr prtProgress = new nsPrintProgress(); + nsresult rv; + mPrintProgress = do_QueryInterface(prtProgress.get(), &rv); NS_ENSURE_SUCCESS(rv, rv); - rv = prtProgress->QueryInterface(NS_GET_IID(nsIWebProgressListener), (void**)getter_AddRefs(mWebProgressListener)); + mWebProgressListener = do_QueryInterface(prtProgress.get(), &rv); NS_ENSURE_SUCCESS(rv, rv); - nsPrintProgressParams* prtProgressParams = new nsPrintProgressParams(); - rv = prtProgressParams->QueryInterface(NS_GET_IID(nsIPrintProgressParams), (void**)printProgressParams); + nsRefPtr prtProgressParams = new nsPrintProgressParams(); + if (!prtProgressParams) + return NS_ERROR_OUT_OF_MEMORY; + + rv = CallQueryInterface(prtProgressParams.get(), aPrintProgressParams); NS_ENSURE_SUCCESS(rv, rv); - if (printProgressParams) + if (*aPrintProgressParams) { nsCOMPtr parentDOMIntl(do_QueryInterface(parent)); @@ -241,13 +245,13 @@ if (parentDOMIntl) { mPrintProgress->OpenProgressDialog(parentDOMIntl, - isForPrinting?kPrintProgressDialogURL:kPrtPrvProgressDialogURL, - *printProgressParams, openDialogObserver, notifyOnOpen); + isForPrinting ? kPrintProgressDialogURL : kPrtPrvProgressDialogURL, + *aPrintProgressParams, openDialogObserver, aNotifyOnOpen); } } - *webProgressListener = NS_STATIC_CAST(nsIWebProgressListener*, this); - NS_ADDREF(*webProgressListener); + *aWebProgressListener = NS_STATIC_CAST(nsIWebProgressListener*, this); + NS_ADDREF(*aWebProgressListener); return rv; } Index: mozilla/embedding/qa/testembed/BrowserImpl.cpp =================================================================== RCS file: /cvsroot/mozilla/embedding/qa/testembed/BrowserImpl.cpp,v retrieving revision 1.38 diff -u -r1.38 mozilla/embedding/qa/testembed/BrowserImpl.cpp --- mozilla/embedding/qa/testembed/BrowserImpl.cpp +++ mozilla/embedding/qa/testembed/BrowserImpl.cpp @@ -654,7 +654,7 @@ FormatAndPrintOutput("DoContent() aIsContentPreferred = ", aIsContentPreferred, 1); RequestName(aRequest, stringMsg); // nsIRequest::GetName() test // *aContentHandler = nsnull; - QueryInterface(NS_GET_IID(nsIStreamListener), (void **) aContentHandler); + CallQueryInterface(this, aContentHandler); *_retval = PR_FALSE; FormatAndPrintOutput("_retval set to = ", *_retval, 1); @@ -722,7 +722,7 @@ *aParentContentListener = mParentContentListener; NS_IF_ADDREF(*aParentContentListener); -// QueryInterface(NS_GET_IID(nsIURIContentListener), (void **) aParentContentListener); +// CallQueryInterface(this, aParentContentListener); return NS_OK; } Index: mozilla/embedding/qa/testembed/winEmbedFileLocProvider.cpp =================================================================== RCS file: /cvsroot/mozilla/embedding/qa/testembed/winEmbedFileLocProvider.cpp,v retrieving revision 1.19 diff -u -r1.19 mozilla/embedding/qa/testembed/winEmbedFileLocProvider.cpp --- mozilla/embedding/qa/testembed/winEmbedFileLocProvider.cpp +++ mozilla/embedding/qa/testembed/winEmbedFileLocProvider.cpp @@ -92,12 +92,12 @@ NS_IMETHODIMP winEmbedFileLocProvider::GetFile(const char *prop, PRBool *persistent, nsIFile **_retval) { - nsCOMPtr localFile; - nsresult rv = NS_ERROR_FAILURE; + nsCOMPtr localFile; + nsresult rv = NS_ERROR_FAILURE; + + *_retval = nsnull; + *persistent = PR_TRUE; - *_retval = nsnull; - *persistent = PR_TRUE; - if (nsCRT::strcmp(prop, NS_APP_APPLICATION_REGISTRY_DIR) == 0) { rv = GetProductDirectory(getter_AddRefs(localFile)); @@ -181,10 +181,10 @@ rv = localFile->AppendRelativeNativePath(COMPONENTS_DIR_NAME); } - if (localFile && NS_SUCCEEDED(rv)) - return localFile->QueryInterface(NS_GET_IID(nsIFile), (void**)_retval); - - return rv; + if (localFile && NS_SUCCEEDED(rv)) + return CallQueryInterface(localFile, _retval); + + return rv; } // Get the location of the GRE version we're compatible with from @@ -253,7 +253,7 @@ if(pGreDir) { nsCOMPtr tempLocal; - rv = NS_NewNativeLocalFile(nsDependentCString(pGreDir), TRUE, getter_AddRefs(tempLocal)); + rv = NS_NewNativeLocalFile(nsDependentCString(pGreDir), TRUE, getter_AddRefs(tempLocal)); if (tempLocal) { Index: mozilla/embedding/tests/mfcembed/BrowserView.cpp =================================================================== RCS file: /cvsroot/mozilla/embedding/tests/mfcembed/BrowserView.cpp,v retrieving revision 1.51 diff -u -r1.51 mozilla/embedding/tests/mfcembed/BrowserView.cpp Index: mozilla/embedding/tests/mfcembed/EditorFrm.cpp =================================================================== RCS file: /cvsroot/mozilla/embedding/tests/mfcembed/EditorFrm.cpp,v retrieving revision 1.14 diff -u -r1.14 mozilla/embedding/tests/mfcembed/EditorFrm.cpp --- mozilla/embedding/tests/mfcembed/EditorFrm.cpp +++ mozilla/embedding/tests/mfcembed/EditorFrm.cpp @@ -652,7 +652,7 @@ return; } - editor->QueryInterface(NS_GET_IID(nsIHTMLEditor), (void**)htmlEditor); + CallQueryInterface(editor, htmlEditor); } BOOL CEditorFrame::InLink() Index: mozilla/embedding/tests/mfcembed/winEmbedFileLocProvider.cpp =================================================================== RCS file: /cvsroot/mozilla/embedding/tests/mfcembed/winEmbedFileLocProvider.cpp,v retrieving revision 1.28 diff -u -r1.28 mozilla/embedding/tests/mfcembed/winEmbedFileLocProvider.cpp --- mozilla/embedding/tests/mfcembed/winEmbedFileLocProvider.cpp +++ mozilla/embedding/tests/mfcembed/winEmbedFileLocProvider.cpp @@ -171,7 +171,7 @@ #endif if (localFile && NS_SUCCEEDED(rv)) - return localFile->QueryInterface(NS_GET_IID(nsIFile), (void**)_retval); + return CallQueryInterface(localFile, _retval); return rv; } Index: mozilla/embedding/tests/mfcembed/components/PrintingPromptService.cpp =================================================================== RCS file: /cvsroot/mozilla/embedding/tests/mfcembed/components/PrintingPromptService.cpp,v retrieving revision 1.9 diff -u -r1.9 mozilla/embedding/tests/mfcembed/components/PrintingPromptService.cpp --- mozilla/embedding/tests/mfcembed/components/PrintingPromptService.cpp +++ mozilla/embedding/tests/mfcembed/components/PrintingPromptService.cpp @@ -1,4 +1,4 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* ***** BEGIN LICENSE BLOCK ***** * Version: Mozilla-sample-code 1.0 * @@ -147,16 +147,15 @@ NS_IMETHODIMP CPrintingPromptService::ShowPrintDialog(nsIDOMWindow *parent, nsIWebBrowserPrint *webBrowserPrint, nsIPrintSettings *printSettings) { - //NS_ENSURE_ARG(parent); + //NS_ENSURE_ARG(parent); - CWnd* wnd = CWndForDOMWindow(parent); + CWnd* wnd = CWndForDOMWindow(parent); - NS_ASSERTION(wnd && wnd->m_hWnd, "Couldn't get native window for PRint Dialog!"); - if (wnd && wnd->m_hWnd) { - return NativeShowPrintDialog(wnd->m_hWnd, webBrowserPrint, printSettings); - } else { - return NS_ERROR_FAILURE; - } + NS_ASSERTION(wnd && wnd->m_hWnd, "Couldn't get native window for PRint Dialog!"); + if (!wnd || !wnd->m_hWnd) + return NS_ERROR_FAILURE; + + return NativeShowPrintDialog(wnd->m_hWnd, webBrowserPrint, printSettings); } //----------------------------------------------------------- @@ -171,59 +170,64 @@ /* void showProgress (in nsIDOMWindow parent, in nsIWebBrowserPrint webBrowserPrint, in nsIPrintSettings printSettings, in nsIObserver openDialogObserver, in boolean isForPrinting, out nsIWebProgressListener webProgressListener, out nsIPrintProgressParams printProgressParams, out boolean notifyOnOpen); */ NS_IMETHODIMP CPrintingPromptService::ShowProgress(nsIDOMWindow* parent, - nsIWebBrowserPrint* webBrowserPrint, // ok to be null - nsIPrintSettings* printSettings, // ok to be null - nsIObserver* openDialogObserver, // ok to be null - PRBool isForPrinting, - nsIWebProgressListener** webProgressListener, - nsIPrintProgressParams** printProgressParams, - PRBool* notifyOnOpen) -{ - NS_ENSURE_ARG(webProgressListener); - NS_ENSURE_ARG(printProgressParams); - NS_ENSURE_ARG(notifyOnOpen); - - ResourceState setState; - nsresult rv; - - nsPrintProgressParams* prtProgressParams = new nsPrintProgressParams(); - rv = prtProgressParams->QueryInterface(NS_GET_IID(nsIPrintProgressParams), (void**)printProgressParams); - NS_ENSURE_SUCCESS(rv, rv); - - mObserver = openDialogObserver; - - *notifyOnOpen = PR_FALSE; - if (printProgressParams) - { - CWnd *wnd = CWndForDOMWindow(parent); - m_PPDlg = new CPrintProgressDialog(wnd, isForPrinting, *printProgressParams, webBrowserPrint, printSettings); - m_PPDlg->Create(IDD_PRINT_PROGRESS_DIALOG); - m_PPDlg->ShowWindow(SW_SHOW); - m_PPDlg->UpdateWindow(); + nsIWebBrowserPrint* webBrowserPrint, // ok to be null + nsIPrintSettings* printSettings, // ok to be null + nsIObserver* openDialogObserver, // ok to be null + PRBool isForPrinting, + nsIWebProgressListener** aWebProgressListener, + nsIPrintProgressParams** aPrintProgressParams, + PRBool* aNotifyOnOpen) +{ + NS_ENSURE_ARG(aWebProgressListener); + NS_ENSURE_ARG(aPrintProgressParams); + NS_ENSURE_ARG(aNotifyOnOpen); + + ResourceState setState; + nsresult rv; + + nsRefPtr prtProgressParams = new nsPrintProgressParams(); + if (!prtProgressParams) + return NS_ERROR_OUT_OF_MEMORY; + rv = CallQueryInterface(prtProgressParams.get(), aPrintProgressParams); + NS_ENSURE_SUCCESS(rv, rv); + + mObserver = openDialogObserver; + + *aNotifyOnOpen = PR_FALSE; + if (*aPrintProgressParams) + { + CWnd *wnd = CWndForDOMWindow(parent); + m_PPDlg = new CPrintProgressDialog(wnd, isForPrinting, *aPrintProgressParams, webBrowserPrint, printSettings); + if (!m_PPDlg) + return NS_ERROR_OUT_OF_MEMORY; + + m_PPDlg->Create(IDD_PRINT_PROGRESS_DIALOG); + m_PPDlg->ShowWindow(SW_SHOW); + m_PPDlg->UpdateWindow(); - *notifyOnOpen = FirePauseEvent(); - } + *notifyOnOpen = FirePauseEvent(); + } - *webProgressListener = NS_STATIC_CAST(nsIWebProgressListener*, this); - NS_ADDREF(*webProgressListener); + *aWebProgressListener = NS_STATIC_CAST(nsIWebProgressListener*, this); + NS_ADDREF(*aWebProgressListener); - return rv; + return rv; } /* void showPageSetup (in nsIDOMWindow parent, in nsIPrintSettings printSettings); */ NS_IMETHODIMP CPrintingPromptService::ShowPageSetup(nsIDOMWindow *parent, nsIPrintSettings *printSettings, nsIObserver *aObs) { - NS_ENSURE_ARG(printSettings); + NS_ENSURE_ARG(printSettings); - return NS_ERROR_NOT_IMPLEMENTED; + return NS_ERROR_NOT_IMPLEMENTED; } /* void showPrinterProperties (in nsIDOMWindow parent, in wstring printerName, in nsIPrintSettings printSettings); */ NS_IMETHODIMP CPrintingPromptService::ShowPrinterProperties(nsIDOMWindow *parent, const PRUnichar *printerName, nsIPrintSettings *printSettings) { - return NS_ERROR_NOT_IMPLEMENTED; + return NS_ERROR_NOT_IMPLEMENTED; } //------------------------------------------------------------------------ @@ -242,42 +246,42 @@ NS_IMETHODIMP CPrintingPromptService::OnStateChange(nsIWebProgress *aWebProgress, nsIRequest *aRequest, PRUint32 aStateFlags, nsresult aStatus) { - if (aStateFlags & STATE_START) + if (aStateFlags & STATE_START) + { + if (m_PPDlg) { - if (m_PPDlg) - { - m_PPDlg->OnStartPrinting(); - } + m_PPDlg->OnStartPrinting(); } + } - if (aStateFlags & STATE_STOP) + if (aStateFlags & STATE_STOP) + { + if (m_PPDlg) { - if (m_PPDlg) - { - m_PPDlg->OnProgressPrinting(100, 100); - m_PPDlg->DestroyWindow(); - m_PPDlg = NULL; - } + m_PPDlg->OnProgressPrinting(100, 100); + m_PPDlg->DestroyWindow(); + m_PPDlg = NULL; } - return NS_OK; + } + return NS_OK; } /* void onProgressChange (in nsIWebProgress aWebProgress, in nsIRequest aRequest, in long aCurSelfProgress, in long aMaxSelfProgress, in long aCurTotalProgress, in long aMaxTotalProgress); */ NS_IMETHODIMP CPrintingPromptService::OnProgressChange(nsIWebProgress *aWebProgress, nsIRequest *aRequest, PRInt32 aCurSelfProgress, PRInt32 aMaxSelfProgress, PRInt32 aCurTotalProgress, PRInt32 aMaxTotalProgress) { - if (m_PPDlg) - { - m_PPDlg->OnProgressPrinting(aCurTotalProgress, aMaxTotalProgress); - } - return NS_OK; + if (m_PPDlg) + { + m_PPDlg->OnProgressPrinting(aCurTotalProgress, aMaxTotalProgress); + } + return NS_OK; } /* void onLocationChange (in nsIWebProgress aWebProgress, in nsIRequest aRequest, in nsIURI location); */ NS_IMETHODIMP CPrintingPromptService::OnLocationChange(nsIWebProgress *aWebProgress, nsIRequest *aRequest, nsIURI *location) { - return NS_OK; + return NS_OK; } /* void onStatusChange (in nsIWebProgress aWebProgress, in nsIRequest aRequest, in nsresult aStatus, in wstring aMessage); */ @@ -291,7 +295,7 @@ NS_IMETHODIMP CPrintingPromptService::OnSecurityChange(nsIWebProgress *aWebProgress, nsIRequest *aRequest, PRUint32 state) { - return NS_OK; + return NS_OK; } Index: mozilla/embedding/tests/wxEmbed/BrowserFrame.cpp =================================================================== RCS file: /cvsroot/mozilla/embedding/tests/wxEmbed/BrowserFrame.cpp,v retrieving revision 1.11 diff -u -r1.11 mozilla/embedding/tests/wxEmbed/BrowserFrame.cpp --- mozilla/embedding/tests/wxEmbed/BrowserFrame.cpp +++ mozilla/embedding/tests/wxEmbed/BrowserFrame.cpp @@ -247,7 +247,9 @@ return NS_ERROR_OUT_OF_MEMORY; frame->Show(TRUE); GeckoContainer *container = frame->mGeckoWnd->GetGeckoContainer(); - return container->QueryInterface(NS_GET_IID(nsIWebBrowserChrome), (void **) aNewWindow); + nsCOMPtr newWindow(do_QueryInterface(container, &rv)); + NS_IF_ADDREF(*aNewWindow = container); + return rv; } void BrowserFrame::UpdateStatusBarText(const PRUnichar* aStatusText) Index: mozilla/embedding/tests/wxEmbed/GeckoProtocolHandler.cpp =================================================================== RCS file: /cvsroot/mozilla/embedding/tests/wxEmbed/GeckoProtocolHandler.cpp,v retrieving revision 1.13 diff -u -r1.13 mozilla/embedding/tests/wxEmbed/GeckoProtocolHandler.cpp --- mozilla/embedding/tests/wxEmbed/GeckoProtocolHandler.cpp +++ mozilla/embedding/tests/wxEmbed/GeckoProtocolHandler.cpp @@ -252,9 +252,13 @@ { return NS_ERROR_OUT_OF_MEMORY; } - channel->Init(aURI); - channel->QueryInterface(NS_GET_IID(nsIChannel), (void **) _retval); - return NS_OK; + nsresult rv = channel->Init(aURI); + if (NS_FAILED(rv)) { + delete channel; + *_retval = nsnull; + return rv; + } + return CallQueryInterface(channel, _retval); } /* boolean allowPort (in long port, in string scheme); */ Index: mozilla/extensions/java/xpcom/src/nsAppFileLocProviderProxy.cpp =================================================================== RCS file: /cvsroot/mozilla/extensions/java/xpcom/src/nsAppFileLocProviderProxy.cpp,v retrieving revision 1.7 diff -u -r1.7 mozilla/extensions/java/xpcom/src/nsAppFileLocProviderProxy.cpp --- mozilla/extensions/java/xpcom/src/nsAppFileLocProviderProxy.cpp +++ mozilla/extensions/java/xpcom/src/nsAppFileLocProviderProxy.cpp @@ -93,11 +93,10 @@ // Set nsIFile result value nsCOMPtr localFile; nsresult rv = File_to_nsILocalFile(env, javaFile, getter_AddRefs(localFile)); - if (NS_SUCCEEDED(rv)) { - return localFile->QueryInterface(NS_GET_IID(nsIFile), (void**)aResult); - } + if (NS_FAILED(rv)) + return rv; - return rv; + return CallQueryInterface(localFile, aResult); } @@ -144,7 +143,7 @@ env->DeleteLocalRef(javaFile); if (NS_SUCCEEDED(rv)) { - return localFile->QueryInterface(NS_GET_IID(nsIFile), (void**)aResult); + return CallQueryInterface(localFile, aResult); } } Index: mozilla/extensions/java/xpcom/src/nsJavaXPCOMBindingUtils.cpp =================================================================== RCS file: /cvsroot/mozilla/extensions/java/xpcom/src/nsJavaXPCOMBindingUtils.cpp,v retrieving revision 1.51 diff -u -r1.51 mozilla/extensions/java/xpcom/src/nsJavaXPCOMBindingUtils.cpp --- mozilla/extensions/java/xpcom/src/nsJavaXPCOMBindingUtils.cpp +++ mozilla/extensions/java/xpcom/src/nsJavaXPCOMBindingUtils.cpp @@ -817,7 +817,7 @@ nsresult rv; nsJavaXPTCStub* stub = nsnull; - aXPCOMObject->QueryInterface(NS_GET_IID(nsJavaXPTCStub), (void**) &stub); + rv = CallQueryInterface(aXPCOMObject, &stub); if (stub) { // Get Java object directly from nsJavaXPTCStub *aResult = stub->GetJavaObject(); Index: mozilla/extensions/metrics/src/nsUICommandCollector.cpp =================================================================== RCS file: /cvsroot/mozilla/extensions/metrics/src/nsUICommandCollector.cpp,v retrieving revision 1.12 diff -u -r1.12 mozilla/extensions/metrics/src/nsUICommandCollector.cpp --- mozilla/extensions/metrics/src/nsUICommandCollector.cpp +++ mozilla/extensions/metrics/src/nsUICommandCollector.cpp @@ -56,6 +56,7 @@ #include "nsIArray.h" #include "nsComponentManagerUtils.h" #endif +#include "nsArrayUtils.h" NS_IMPL_ISUPPORTS3(nsUICommandCollector, nsIObserver, nsIDOMEventListener, nsIMetricsCollector) @@ -395,10 +396,7 @@ NS_ENSURE_STATE(bmDS); // Find the bookmark's position in its parent folder. - // do_QueryElementAt() isn't a frozen export :-( - nsCOMPtr parent; - parentChain->QueryElementAt(depth - 1, NS_GET_IID(nsIRDFResource), - getter_AddRefs(parent)); + nsCOMPtr parent(do_QueryElementAt(parentChain, depth - 1)); NS_ENSURE_STATE(parent); nsCOMPtr container = @@ -425,9 +423,7 @@ // Since the user can designate any folder as the toolbar folder, // we must walk the entire parent chain looking for it. for (PRUint32 i = 0; i < depth; ++i) { - nsCOMPtr item; - parentChain->QueryElementAt(i, NS_GET_IID(nsIRDFResource), - getter_AddRefs(item)); + nsCOMPtr item(do_QueryElementAt(parentChain, i)); if (toolbarFolder == item) { isToolbarBM = PR_TRUE; break; Index: mozilla/extensions/python/dom/src/nsPyArgArray.cpp =================================================================== RCS file: /cvsroot/mozilla/extensions/python/dom/src/nsPyArgArray.cpp,v retrieving revision 1.2 diff -u -r1.2 mozilla/extensions/python/dom/src/nsPyArgArray.cpp --- mozilla/extensions/python/dom/src/nsPyArgArray.cpp +++ mozilla/extensions/python/dom/src/nsPyArgArray.cpp @@ -127,5 +127,5 @@ nsPyArgArray *ret = new nsPyArgArray(ob); if (ret == nsnull) return NS_ERROR_OUT_OF_MEMORY; - return ret->QueryInterface(NS_GET_IID(nsIArray), (void **)aArray); + return CallQueryInterface(ret, aArray); } Index: mozilla/extensions/python/dom/src/nsPyContext.cpp =================================================================== RCS file: /cvsroot/mozilla/extensions/python/dom/src/nsPyContext.cpp,v retrieving revision 1.5 diff -u -r1.5 mozilla/extensions/python/dom/src/nsPyContext.cpp --- mozilla/extensions/python/dom/src/nsPyContext.cpp +++ mozilla/extensions/python/dom/src/nsPyContext.cpp @@ -799,7 +799,7 @@ if (!holder) return NS_ERROR_OUT_OF_MEMORY; - return holder->QueryInterface(NS_GET_IID(nsISupports), (void **)aHolder); + return CallQueryInterface(holder, aHolder); } nsresult Index: mozilla/extensions/python/dom/src/nsPyTimeout.cpp =================================================================== RCS file: /cvsroot/mozilla/extensions/python/dom/src/nsPyTimeout.cpp,v retrieving revision 1.2 diff -u -r1.2 mozilla/extensions/python/dom/src/nsPyTimeout.cpp --- mozilla/extensions/python/dom/src/nsPyTimeout.cpp +++ mozilla/extensions/python/dom/src/nsPyTimeout.cpp @@ -145,6 +145,7 @@ *aRet = new nsPyTimeoutHandler(aExpr, aFunObj, obArgs); if (!aRet) return NS_ERROR_OUT_OF_MEMORY; - return (*aRet)->QueryInterface(NS_GET_IID(nsIScriptTimeoutHandler), - NS_REINTERPRET_CAST(void **, aRet)); + /* this wasn't a good idea. + * who is responsible for aRet when QI fails? */ + return CallQueryInterface(*aRet, aRet); } Index: mozilla/extensions/python/xpcom/src/VariantUtils.cpp =================================================================== RCS file: /cvsroot/mozilla/extensions/python/xpcom/src/VariantUtils.cpp,v retrieving revision 1.32 diff -u -r1.32 mozilla/extensions/python/xpcom/src/VariantUtils.cpp --- mozilla/extensions/python/xpcom/src/VariantUtils.cpp +++ mozilla/extensions/python/xpcom/src/VariantUtils.cpp @@ -757,7 +757,7 @@ } if (NS_FAILED(nr)) return nr; - return v->QueryInterface(NS_GET_IID(nsIVariant), (void **)aRet); + return CallQueryInterface(v, aRet); } static PyObject *MyBool_FromBool(PRBool v) Index: mozilla/extensions/wallet/src/wallet.cpp =================================================================== RCS file: /cvsroot/mozilla/extensions/wallet/src/wallet.cpp,v retrieving revision 1.379 diff -u -r1.379 mozilla/extensions/wallet/src/wallet.cpp --- mozilla/extensions/wallet/src/wallet.cpp +++ mozilla/extensions/wallet/src/wallet.cpp @@ -2126,7 +2126,7 @@ nsCAutoString localSchema; localSchema.Assign(schema); /* get prefills for input element */ - result = elementNode->QueryInterface(NS_GET_IID(nsIDOMHTMLInputElement), (void**)&inputElement); + result = CallQueryInterface(elementNode, &inputElement); if ((NS_SUCCEEDED(result)) && (nsnull != inputElement)) { nsAutoString type; @@ -2186,7 +2186,7 @@ } /* get prefills for dropdown list */ - result = elementNode->QueryInterface(NS_GET_IID(nsIDOMHTMLSelectElement), (void**)&selectElement); + result = CallQueryInterface(elementNode, &selectElement); if ((NS_SUCCEEDED(result)) && (nsnull != selectElement)) { nsAutoString field; result = selectElement->GetName(field); Index: mozilla/extensions/webservices/proxy/src/wsppropertybagwrapper.cpp =================================================================== RCS file: /cvsroot/mozilla/extensions/webservices/proxy/src/wsppropertybagwrapper.cpp,v retrieving revision 1.12 diff -u -r1.12 mozilla/extensions/webservices/proxy/src/wsppropertybagwrapper.cpp --- mozilla/extensions/webservices/proxy/src/wsppropertybagwrapper.cpp +++ mozilla/extensions/webservices/proxy/src/wsppropertybagwrapper.cpp @@ -84,27 +84,15 @@ NS_IMPL_ADDREF(WSPPropertyBagWrapper) NS_IMPL_RELEASE(WSPPropertyBagWrapper) -NS_IMETHODIMP -WSPPropertyBagWrapper::QueryInterface(REFNSIID aIID, void** aInstancePtr) -{ - if (aIID.Equals(NS_GET_IID(nsISupports))) { - *aInstancePtr = NS_STATIC_CAST(nsIXPTCProxy*, this); +NS_INTERFACE_MAP_BEGIN(WSPPropertyBagWrapper) + NS_INTERFACE_MAP_ENTRY_AMBIGUOUS(nsISupports, nsIXPTCProxy) + if (mXPTCStub && mIID && aIID.Equals(*mIID)) { + foundInterface = mXPTCStub; } - if(mXPTCStub && mIID && aIID.Equals(*mIID)) { - *aInstancePtr = mXPTCStub; - } - else if (aIID.Equals(NS_GET_IID(nsIWebServicePropertyBagWrapper))) { - *aInstancePtr = NS_STATIC_CAST(nsIWebServicePropertyBagWrapper*, this); - } - else if (aIID.Equals(NS_GET_IID(nsIClassInfo))) { - *aInstancePtr = NS_STATIC_CAST(nsIClassInfo*, this); - } else { - return NS_ERROR_NO_INTERFACE; - } - - NS_ADDREF_THIS(); - return NS_OK; -} + else + NS_INTERFACE_MAP_ENTRY(nsIWebServicePropertyBagWrapper) + NS_INTERFACE_MAP_ENTRY(nsIClassInfo) +NS_INTERFACE_MAP_END NS_IMETHODIMP WSPPropertyBagWrapper::CallMethod(PRUint16 methodIndex, Index: mozilla/extensions/webservices/proxy/src/wspproxy.cpp =================================================================== RCS file: /cvsroot/mozilla/extensions/webservices/proxy/src/wspproxy.cpp,v retrieving revision 1.24 diff -u -r1.24 mozilla/extensions/webservices/proxy/src/wspproxy.cpp --- mozilla/extensions/webservices/proxy/src/wspproxy.cpp +++ mozilla/extensions/webservices/proxy/src/wspproxy.cpp @@ -136,32 +136,15 @@ NS_IMPL_ADDREF(WSPProxy) NS_IMPL_RELEASE(WSPProxy) -NS_IMETHODIMP -WSPProxy::QueryInterface(REFNSIID aIID, void** aInstancePtr) -{ - if (aIID.Equals(NS_GET_IID(nsISupports))) { - *aInstancePtr = NS_STATIC_CAST(nsIXPTCProxy*, this); - NS_ADDREF_THIS(); - return NS_OK; - } +NS_INTERFACE_MAP_BEGIN(WSPProxy) + NS_INTERFACE_MAP_ENTRY_AMBIGUOUS(nsISupports, nsIXPTCProxy) if(mXPTCStub && mIID && aIID.Equals(*mIID)) { - *aInstancePtr = mXPTCStub; - NS_ADDREF_THIS(); - return NS_OK; + foundInterface = mXPTCStub; } - else if (aIID.Equals(NS_GET_IID(nsIWebServiceProxy))) { - *aInstancePtr = NS_STATIC_CAST(nsIWebServiceProxy*, this); - NS_ADDREF_THIS(); - return NS_OK; - } - else if (aIID.Equals(NS_GET_IID(nsIClassInfo))) { - *aInstancePtr = NS_STATIC_CAST(nsIClassInfo*, this); - NS_ADDREF_THIS(); - return NS_OK; - } - - return NS_ERROR_NO_INTERFACE; -} + else + NS_INTERFACE_MAP_ENTRY(nsIWebServiceProxy) + NS_INTERFACE_MAP_ENTRY(nsIClassInfo) +NS_INTERFACE_MAP_END /////////////////////////////////////////////////// // @@ -792,8 +775,7 @@ if (NS_FAILED(rv)) { break; } - propBag->QueryInterface(NS_GET_IID(nsISupports), - (void**)outptr); + CallQueryInterface(propBag, outptr); } else { *outptr = nsnull; @@ -951,8 +933,7 @@ if (NS_FAILED(rv)) { return rv; } - wrapper->QueryInterface(NS_GET_IID(nsISupports), (void**)aComplexType); - return NS_OK; + return CallQueryInterface(wrapper.get(), aComplexType); } nsresult Index: mozilla/extensions/webservices/schema/src/nsSchemaLoader.cpp =================================================================== RCS file: /cvsroot/mozilla/extensions/webservices/schema/src/nsSchemaLoader.cpp,v retrieving revision 1.51 diff -u -r1.51 mozilla/extensions/webservices/schema/src/nsSchemaLoader.cpp --- mozilla/extensions/webservices/schema/src/nsSchemaLoader.cpp +++ mozilla/extensions/webservices/schema/src/nsSchemaLoader.cpp @@ -2076,8 +2076,7 @@ complexBase->GetSimpleBaseType(aSimpleBaseType); } else { - aBaseType->QueryInterface(NS_GET_IID(nsISchemaSimpleType), - (void**)aSimpleBaseType); + CallQueryInterface(aBaseType, aSimpleBaseType); } while (NS_SUCCEEDED(iterator.GetNextChild(getter_AddRefs(childElement), Index: mozilla/extensions/webservices/soap/src/nsSOAPCall.cpp =================================================================== RCS file: /cvsroot/mozilla/extensions/webservices/soap/src/nsSOAPCall.cpp,v retrieving revision 1.34 diff -u -r1.34 mozilla/extensions/webservices/soap/src/nsSOAPCall.cpp --- mozilla/extensions/webservices/soap/src/nsSOAPCall.cpp +++ mozilla/extensions/webservices/soap/src/nsSOAPCall.cpp @@ -151,8 +151,7 @@ return NS_OK; } - return response->QueryInterface(NS_GET_IID(nsISOAPResponse), - (void **) _retval); + return CallQueryInterface(response, _retval); } /* void asyncInvoke (in nsISOAPResponseListener listener); */ Index: mozilla/extensions/webservices/soap/src/nsSOAPUtils.cpp =================================================================== RCS file: /cvsroot/mozilla/extensions/webservices/soap/src/nsSOAPUtils.cpp,v retrieving revision 1.39 diff -u -r1.39 mozilla/extensions/webservices/soap/src/nsSOAPUtils.cpp --- mozilla/extensions/webservices/soap/src/nsSOAPUtils.cpp +++ mozilla/extensions/webservices/soap/src/nsSOAPUtils.cpp @@ -177,7 +177,7 @@ PRUint16 type; child->GetNodeType(&type); if (nsIDOMNode::ELEMENT_NODE == type) { - child->QueryInterface(NS_GET_IID(nsIDOMElement), (void **) aElement); + CallQueryInterface(child, aElement); break; } nsCOMPtr temp = child; @@ -196,8 +196,7 @@ PRUint16 type; sibling->GetNodeType(&type); if (nsIDOMNode::ELEMENT_NODE == type) { - sibling->QueryInterface(NS_GET_IID(nsIDOMElement), - (void **) aElement); + CallQueryInterface(sibling, aElement); break; } nsCOMPtr temp = sibling; Index: mozilla/extensions/xmlterm/base/mozXMLTermListeners.cpp =================================================================== RCS file: /cvsroot/mozilla/extensions/xmlterm/base/mozXMLTermListeners.cpp,v retrieving revision 1.25 diff -u -r1.25 mozilla/extensions/xmlterm/base/mozXMLTermListeners.cpp --- mozilla/extensions/xmlterm/base/mozXMLTermListeners.cpp +++ mozilla/extensions/xmlterm/base/mozXMLTermListeners.cpp @@ -66,8 +66,7 @@ // Save non-owning reference to embedding XMLTerminal object listener->SetXMLTerminal(aXMLTerminal); - return listener->QueryInterface(NS_GET_IID(nsIDOMEventListener), - (void **) aInstancePtrResult); + return CallQueryInterface(listener, aInstancePtrResult); } nsresult @@ -82,8 +81,7 @@ // Save non-owning reference to embedding XMLTerminal object listener->SetXMLTerminal(aXMLTerminal); - return listener->QueryInterface(NS_GET_IID(nsIDOMEventListener), - (void **) aInstancePtrResult); + return CallQueryInterface(listener, aInstancePtrResult); } nsresult @@ -98,8 +96,7 @@ // Save non-owning reference to embedding XMLTerminal object listener->SetXMLTerminal(aXMLTerminal); - return listener->QueryInterface(NS_GET_IID(nsIDOMEventListener), - (void **) aInstancePtrResult); + return CallQueryInterface(listener, aInstancePtrResult); } nsresult @@ -114,8 +111,7 @@ // Save non-owning reference to embedding XMLTerminal object listener->SetXMLTerminal(aXMLTerminal); - return listener->QueryInterface(NS_GET_IID(nsIDOMEventListener), - (void **) aInstancePtrResult); + return CallQueryInterface(listener, aInstancePtrResult); } ///////////////////////////////////////////////////////////////////////// @@ -139,37 +135,12 @@ NS_IMPL_RELEASE(mozXMLTermKeyListener) -NS_IMETHODIMP -mozXMLTermKeyListener::QueryInterface(REFNSIID aIID, void** aInstancePtr) -{ - if (aInstancePtr == NULL) { - return NS_ERROR_NULL_POINTER; - } - - // Always NULL result, in case of failure - *aInstancePtr = NULL; - - if (aIID.Equals(NS_GET_IID(nsISupports))) { - *aInstancePtr = NS_STATIC_CAST(nsISupports*, - NS_STATIC_CAST(nsIDOMKeyListener*,this)); - - } else if (aIID.Equals(NS_GET_IID(nsIDOMEventListener))) { - *aInstancePtr = NS_STATIC_CAST(nsIDOMEventListener*,this); - - } else if (aIID.Equals(NS_GET_IID(nsIDOMKeyListener))) { - *aInstancePtr = NS_STATIC_CAST(nsIDOMKeyListener*,this); - - } else if (aIID.Equals(NS_GET_IID(mozIXMLTermSuspend))) { - *aInstancePtr = NS_STATIC_CAST(mozIXMLTermSuspend*,this); - - } else { - return NS_ERROR_NO_INTERFACE; - } - - NS_ADDREF_THIS(); - - return NS_OK; -} +NS_INTERFACE_MAP_BEGIN(mozXMLTermKeyListener) + NS_INTERFACE_MAP_ENTRY_AMBIGUOUS(nsISupports, nsIDOMKeyListener) + NS_INTERFACE_MAP_ENTRY(nsIDOMEventListener) + NS_INTERFACE_MAP_ENTRY(nsIDOMKeyListener) + NS_INTERFACE_MAP_ENTRY(mozIXMLTermSuspend) +NS_INTERFACE_MAP_END NS_IMETHODIMP mozXMLTermKeyListener::GetSuspend(PRBool* aSuspend) @@ -463,34 +434,11 @@ NS_IMPL_RELEASE(mozXMLTermTextListener) -NS_IMETHODIMP -mozXMLTermTextListener::QueryInterface(REFNSIID aIID, void** aInstancePtr) -{ - if (aInstancePtr == NULL) { - return NS_ERROR_NULL_POINTER; - } - - // Always NULL result, in case of failure - *aInstancePtr = NULL; - - if (aIID.Equals(NS_GET_IID(nsISupports))) { - *aInstancePtr = NS_STATIC_CAST(nsISupports*, - NS_STATIC_CAST(nsIDOMTextListener*,this)); - - } else if (aIID.Equals(NS_GET_IID(nsIDOMEventListener))) { - *aInstancePtr = NS_STATIC_CAST(nsIDOMEventListener*,this); - - } else if (aIID.Equals(NS_GET_IID(nsIDOMTextListener))) { - *aInstancePtr = NS_STATIC_CAST(nsIDOMTextListener*,this); - - } else { - return NS_ERROR_NO_INTERFACE; - } - - NS_ADDREF_THIS(); - - return NS_OK; -} +NS_INTERFACE_MAP_BEGIN(mozXMLTermTextListener) + NS_INTERFACE_MAP_ENTRY_AMBIGUOUS(nsISupports, nsIDOMTextListener) + NS_INTERFACE_MAP_ENTRY(nsIDOMEventListener) + NS_INTERFACE_MAP_ENTRY(nsIDOMTextListener) +NS_INTERFACE_MAP_END NS_IMETHODIMP @@ -540,34 +488,11 @@ NS_IMPL_RELEASE(mozXMLTermMouseListener) -NS_IMETHODIMP -mozXMLTermMouseListener::QueryInterface(REFNSIID aIID, void** aInstancePtr) -{ - if (aInstancePtr == NULL) { - return NS_ERROR_NULL_POINTER; - } - - // Always NULL result, in case of failure - *aInstancePtr = NULL; - - if (aIID.Equals(NS_GET_IID(nsISupports))) { - *aInstancePtr = NS_STATIC_CAST(nsISupports*, - NS_STATIC_CAST(nsIDOMMouseListener*,this)); - - } else if (aIID.Equals(NS_GET_IID(nsIDOMEventListener))) { - *aInstancePtr = NS_STATIC_CAST(nsIDOMEventListener*,this); - - } else if (aIID.Equals(NS_GET_IID(nsIDOMMouseListener))) { - *aInstancePtr = NS_STATIC_CAST(nsIDOMMouseListener*,this); - - } else { - return NS_ERROR_NO_INTERFACE; - } - - NS_ADDREF_THIS(); - - return NS_OK; -} +NS_INTERFACE_MAP_BEGIN(mozXMLTermMouseListener) + NS_INTERFACE_MAP_ENTRY_AMBIGUOUS(nsISupports, nsIDOMMouseListener) + NS_INTERFACE_MAP_ENTRY(nsIDOMEventListener) + NS_INTERFACE_MAP_ENTRY(nsIDOMMouseListener) +NS_INTERFACE_MAP_END NS_IMETHODIMP @@ -734,34 +659,11 @@ NS_IMPL_RELEASE(mozXMLTermDragListener) -NS_IMETHODIMP -mozXMLTermDragListener::QueryInterface(REFNSIID aIID, void** aInstancePtr) -{ - if (aInstancePtr == NULL) { - return NS_ERROR_NULL_POINTER; - } - - // Always NULL result, in case of failure - *aInstancePtr = NULL; - - if (aIID.Equals(NS_GET_IID(nsISupports))) { - *aInstancePtr = NS_STATIC_CAST(nsISupports*, - NS_STATIC_CAST(nsIDOMDragListener*,this)); - - } else if (aIID.Equals(NS_GET_IID(nsIDOMEventListener))) { - *aInstancePtr = NS_STATIC_CAST(nsIDOMEventListener*,this); - - } else if (aIID.Equals(NS_GET_IID(nsIDOMDragListener))) { - *aInstancePtr = NS_STATIC_CAST(nsIDOMDragListener*,this); - - } else { - return NS_ERROR_NO_INTERFACE; - } - - NS_ADDREF_THIS(); - - return NS_OK; -} +NS_INTERFACE_MAP_BEGIN(mozXMLTermDragListener) + NS_INTERFACE_MAP_ENTRY_AMBIGUOUS(nsISupports, nsIDOMDragListener) + NS_INTERFACE_MAP_ENTRY(nsIDOMEventListener) + NS_INTERFACE_MAP_ENTRY(nsIDOMDragListener) +NS_INTERFACE_MAP_END NS_IMETHODIMP Index: mozilla/extensions/xmlterm/base/mozXMLTerminal.cpp =================================================================== RCS file: /cvsroot/mozilla/extensions/xmlterm/base/mozXMLTerminal.cpp,v retrieving revision 1.81 diff -u -r1.81 mozilla/extensions/xmlterm/base/mozXMLTerminal.cpp --- mozilla/extensions/xmlterm/base/mozXMLTerminal.cpp +++ mozilla/extensions/xmlterm/base/mozXMLTerminal.cpp @@ -291,8 +291,8 @@ if (domDoc) { // Release any event listeners for the document - nsCOMPtr eventReceiver; - nsresult result = domDoc->QueryInterface(NS_GET_IID(nsIDOMEventReceiver), getter_AddRefs(eventReceiver)); + nsresult result; + nsCOMPtr eventReceiver(do_QueryInterface(domDoc, &result)); if (NS_SUCCEEDED(result) && eventReceiver) { if (mKeyListener) { @@ -504,9 +504,7 @@ mCookie = cookie; // Get the DOM event receiver for document - nsCOMPtr eventReceiver; - result = domDoc->QueryInterface(NS_GET_IID(nsIDOMEventReceiver), - getter_AddRefs(eventReceiver)); + nsCOMPtr eventReceiver(do_QueryInterface(domDoc, &result)); if (NS_FAILED(result)) { XMLT_WARNING("mozXMLTerminal::Activate: Warning - Failed to get DOM receiver\n"); return result; @@ -838,8 +836,7 @@ if (!domDoc) return NS_ERROR_FAILURE; - return domDoc->QueryInterface(NS_GET_IID(nsIDOMDocument), - (void **)aDoc); + return CallQueryInterface(domDoc, aDoc); } @@ -861,8 +858,7 @@ return NS_ERROR_FAILURE; } - return docShell->QueryInterface(NS_GET_IID(nsIDocShell), - (void **)aDocShell); + return CallQueryInterface(docShell, aDocShell); } @@ -884,8 +880,7 @@ return NS_ERROR_FAILURE; } - return presShell->QueryInterface(NS_GET_IID(nsIPresShell), - (void **)aPresShell); + return CallQueryInterface(presShell, aPresShell); } @@ -907,8 +902,7 @@ return NS_ERROR_FAILURE; } - return domDoc->QueryInterface(NS_GET_IID(nsIDOMDocument), - (void **)aDOMDocument); + return CallQueryInterface(domDoc, aDOMDocument); } @@ -930,8 +924,7 @@ return NS_ERROR_FAILURE; } - return presShell->QueryInterface(NS_GET_IID(nsISelectionController), - (void **)aSelectionController); + return CallQueryInterface(presShell, aSelectionController); } Index: mozilla/gfx/src/beos/nsDeviceContextBeOS.cpp =================================================================== RCS file: /cvsroot/mozilla/gfx/src/beos/nsDeviceContextBeOS.cpp,v retrieving revision 1.35 diff -u -r1.35 mozilla/gfx/src/beos/nsDeviceContextBeOS.cpp --- mozilla/gfx/src/beos/nsDeviceContextBeOS.cpp +++ mozilla/gfx/src/beos/nsDeviceContextBeOS.cpp @@ -362,7 +362,7 @@ dcps->SetSpec(aDevice); dcps->InitDeviceContextPS((nsIDeviceContext*)aContext, (nsIDeviceContext*)this); - rv = dcps->QueryInterface(NS_GET_IID(nsIDeviceContext), (void **)&aContext); + rv = CallQueryInterface(dcps, &aContext); NS_RELEASE(dcps); Index: mozilla/gfx/src/gtk/nsDeviceContextGTK.cpp =================================================================== RCS file: /cvsroot/mozilla/gfx/src/gtk/nsDeviceContextGTK.cpp,v retrieving revision 1.139 diff -u -r1.139 mozilla/gfx/src/gtk/nsDeviceContextGTK.cpp --- mozilla/gfx/src/gtk/nsDeviceContextGTK.cpp +++ mozilla/gfx/src/gtk/nsDeviceContextGTK.cpp @@ -553,8 +553,7 @@ if (NS_FAILED(rv)) return rv; - rv = dcxp->QueryInterface(NS_GET_IID(nsIDeviceContext), - (void **)&aContext); + rv = CallQueryInterface(dcxp, &aContext); return rv; } else @@ -582,8 +581,7 @@ if (NS_FAILED(rv)) return rv; - rv = dcps->QueryInterface(NS_GET_IID(nsIDeviceContext), - (void **)&aContext); + rv = CallQueryInterface(dcps, &aContext); return rv; } Index: mozilla/gfx/src/photon/nsDeviceContextPh.cpp =================================================================== RCS file: /cvsroot/mozilla/gfx/src/photon/nsDeviceContextPh.cpp,v retrieving revision 1.68 diff -u -r1.68 mozilla/gfx/src/photon/nsDeviceContextPh.cpp --- mozilla/gfx/src/photon/nsDeviceContextPh.cpp +++ mozilla/gfx/src/photon/nsDeviceContextPh.cpp @@ -73,10 +73,10 @@ mSpec = nsnull; mDC = nsnull; - mGC = nsnull; + mGC = nsnull; - mIsPrintingStart = 0; - } + mIsPrintingStart = 0; +} nsDeviceContextPh :: ~nsDeviceContextPh( ) { nsDrawingSurfacePh *surf = (nsDrawingSurfacePh *)mSurface; @@ -84,17 +84,17 @@ NS_IF_RELEASE(surf); //this clears the surf pointer... mSurface = nsnull; - if( mGC ) PgDestroyGC( mGC ); /* we are always the owners of this gc */ + if( mGC ) PgDestroyGC( mGC ); /* we are always the owners of this gc */ - if( mFontLoadCache ) { + if( mFontLoadCache ) { #ifdef DEBUG_Adrian printf( "\n\n\n!!!!!!!!!!!!!!!!! ~nsDeviceContextPh is unloading the mFontLoadCache!!!!!!!!!!!!!!!!!!!\n\n" ); #endif - delete mFontLoadCache; - mFontLoadCache = nsnull; - } - NS_IF_RELEASE( mSpec ); - } + delete mFontLoadCache; + mFontLoadCache = nsnull; + } + NS_IF_RELEASE( mSpec ); +} NS_IMETHODIMP nsDeviceContextPh :: Init( nsNativeWidget aWidget ) { @@ -102,7 +102,7 @@ // Call my base class return DeviceContextImpl::Init( aWidget ); - } +} /* Called for Printing */ @@ -124,49 +124,49 @@ mAppUnitsToDevUnits = (a2d / t2d) * mTwipsToPixels; mDevUnitsToAppUnits = 1.0f / mAppUnitsToDevUnits; - int w, h; - GetPrinterRect( &w, &h ); - mWidthFloat = w; - mHeightFloat = h; + int w, h; + GetPrinterRect( &w, &h ); + mWidthFloat = w; + mHeightFloat = h; - /* Call Base Class */ - DeviceContextImpl::CommonInit( ); + /* Call Base Class */ + DeviceContextImpl::CommonInit( ); - return NS_OK; - } + return NS_OK; +} void nsDeviceContextPh :: GetPrinterRect( int *width, int *height ) { - PhDim_t dim; - const PhDim_t *psize; - const PhRect_t *non_print; - PhRect_t rect, margins; - const char *orientation = 0; - int tmp; - PpPrintContext_t *pc = ((nsDeviceContextSpecPh *)mSpec)->GetPrintContext(); - - memset( &rect, 0, sizeof(rect)); - memset( &margins, 0, sizeof(margins)); - - PpPrintGetPC(pc, Pp_PC_PAPER_SIZE, (const void **)&psize ); - PpPrintGetPC(pc, Pp_PC_NONPRINT_MARGINS, (const void **)&non_print ); - dim.w = (psize->w - ( non_print->ul.x + non_print->lr.x )) * 100 / 1000; - dim.h = (psize->h - ( non_print->ul.x + non_print->lr.x )) * 100 / 1000; - - PpPrintGetPC(pc, Pp_PC_ORIENTATION, (const void **)&orientation ); - - if( *orientation ) { - tmp = dim.w; - dim.w = dim.h; - dim.h = tmp; - } - - /* set these to 0 since we do the margins */ - PpPrintSetPC(pc, INITIAL_PC, 0 , Pp_PC_MARGINS, &rect ); - PpPrintSetPC(pc, INITIAL_PC, 0 , Pp_PC_SOURCE_SIZE, &dim ); - - *width = dim.w; - *height = dim.h; - } + PhDim_t dim; + const PhDim_t *psize; + const PhRect_t *non_print; + PhRect_t rect, margins; + const char *orientation = 0; + int tmp; + PpPrintContext_t *pc = ((nsDeviceContextSpecPh *)mSpec)->GetPrintContext(); + + memset( &rect, 0, sizeof(rect)); + memset( &margins, 0, sizeof(margins)); + + PpPrintGetPC(pc, Pp_PC_PAPER_SIZE, (const void **)&psize ); + PpPrintGetPC(pc, Pp_PC_NONPRINT_MARGINS, (const void **)&non_print ); + dim.w = (psize->w - ( non_print->ul.x + non_print->lr.x )) * 100 / 1000; + dim.h = (psize->h - ( non_print->ul.x + non_print->lr.x )) * 100 / 1000; + + PpPrintGetPC(pc, Pp_PC_ORIENTATION, (const void **)&orientation ); + + if( *orientation ) { + tmp = dim.w; + dim.w = dim.h; + dim.h = tmp; + } + + /* set these to 0 since we do the margins */ + PpPrintSetPC(pc, INITIAL_PC, 0 , Pp_PC_MARGINS, &rect ); + PpPrintSetPC(pc, INITIAL_PC, 0 , Pp_PC_SOURCE_SIZE, &dim ); + + *width = dim.w; + *height = dim.h; +} void nsDeviceContextPh :: CommonInit( nsNativeDeviceContext aDC ) { @@ -174,7 +174,8 @@ static int initialized = 0; - if( !mScreenManager ) mScreenManager = do_GetService("@mozilla.org/gfx/screenmanager;1"); + if( !mScreenManager ) + mScreenManager = do_GetService("@mozilla.org/gfx/screenmanager;1"); if( !initialized ) { initialized = 1; @@ -191,60 +192,64 @@ res = prefs->GetIntPref("layout.css.dpi", &prefVal); if( NS_FAILED( res ) ) { prefVal = 96; - } + } prefs->RegisterCallback( "layout.css.dpi", prefChanged, (void *)this ); if( prefVal >0 ) mDpi = prefVal; - } - } + } + } SetDPI( mDpi ); - GetDisplayInfo(aWidth, aHeight, mDepth); + GetDisplayInfo(aWidth, aHeight, mDepth); - /* Turn off virtual console support... */ - mWidthFloat = (float) aWidth; - mHeightFloat = (float) aHeight; - + /* Turn off virtual console support... */ + mWidthFloat = (float) aWidth; + mHeightFloat = (float) aHeight; + /* Revisit: the scroll bar sizes is a gross guess based on Phab */ mScrollbarHeight = 17; mScrollbarWidth = 17; - } +} NS_IMETHODIMP nsDeviceContextPh :: CreateRenderingContext( nsIRenderingContext *&aContext ) { #ifdef NS_PRINT_PREVIEW - // Defer to Alt when there is one - if(mAltDC && ((mUseAltDC & kUseAltDCFor_CREATERC_PAINT) || (mUseAltDC & kUseAltDCFor_CREATERC_REFLOW))) { - return mAltDC->CreateRenderingContext(aContext); - } + // Defer to Alt when there is one + if(mAltDC && ((mUseAltDC & kUseAltDCFor_CREATERC_PAINT) || (mUseAltDC & kUseAltDCFor_CREATERC_REFLOW))) { + return mAltDC->CreateRenderingContext(aContext); + } #endif nsIRenderingContext *pContext; nsresult rv; nsDrawingSurfacePh *surf; - pContext = new nsRenderingContextPh(); - - if( nsnull != pContext ) { - NS_ADDREF(pContext); - - surf = new nsDrawingSurfacePh(); - if( nsnull != surf ) { - PpPrintContext_t *pc = ((nsDeviceContextSpecPh *)mSpec)->GetPrintContext(); - mGC = PgCreateGC( 0 ); - rv = surf->Init( (PhDrawContext_t*)pc, mGC ); - if( NS_OK == rv ) rv = pContext->Init(this, surf); - else rv = NS_ERROR_OUT_OF_MEMORY; - } - } - else rv = NS_ERROR_OUT_OF_MEMORY; - - if( NS_OK != rv ) NS_IF_RELEASE( pContext ); - - aContext = pContext; - return rv; - } + pContext = new nsRenderingContextPh(); + + if( nsnull != pContext ) { + NS_ADDREF(pContext); + + surf = new nsDrawingSurfacePh(); + if( nsnull != surf ) { + PpPrintContext_t *pc = ((nsDeviceContextSpecPh *)mSpec)->GetPrintContext(); + mGC = PgCreateGC( 0 ); + rv = surf->Init( (PhDrawContext_t*)pc, mGC ); + if( NS_OK == rv ) + rv = pContext->Init(this, surf); + else + rv = NS_ERROR_OUT_OF_MEMORY; + } + } + else + rv = NS_ERROR_OUT_OF_MEMORY; + + if( NS_OK != rv ) + NS_IF_RELEASE( pContext ); + + aContext = pContext; + return rv; +} static char *FaceMessageFont, *FaceMenuFont, *FaceBalloonFont, *FaceGeneralFont; @@ -256,159 +261,162 @@ /* load the file /usr/share/mozilla/system_fonts */ int nsDeviceContextPh :: ReadSystemFonts( ) const { - FILE *fp; - char buffer[512]; + FILE *fp; + char buffer[512]; - fp = fopen( "/usr/share/mozilla/system_fonts", "r" ); - if( !fp ) return -1; + fp = fopen( "/usr/share/mozilla/system_fonts", "r" ); + if( !fp ) return -1; - while ( fgets( buffer, 512, fp ) != NULL ) { - int len, code; - char *p, **face; - int *size; - short *style, *weight; - - /* skip comments and blank lines */ - if( buffer[0] == '#' || buffer[0] == ' ' || buffer[0] == '\n' ) continue; - len = strlen( buffer ); - if( len<3 ) continue; - - if( buffer[len-1] == '\n' ) buffer[ len-1 ] = 0; - - code = buffer[0] << 8 | buffer[1]; - p = &buffer[2]; - switch( code ) { - case 'h=': - if( !strcmp( p, "General" ) ) { - style = &StyleGeneralFont; - face = &FaceGeneralFont; - weight = &WeightGeneralFont; - size = &SizeGeneralFont; - } - else if( !strcmp( p, "Message" ) ) { - style = &StyleMessageFont; - face = &FaceMessageFont; - weight = &WeightMessageFont; - size = &SizeMessageFont; - } - else if( !strcmp( p, "Menu" ) ) { - style = &StyleMenuFont; - face = &FaceMenuFont; - weight = &WeightMenuFont; - size = &SizeMenuFont; - } - else if( !strcmp( p, "Balloon" ) ) { - style = &StyleBalloonFont; - face = &FaceBalloonFont; - weight = &WeightBalloonFont; - size = &SizeBalloonFont; - } - break; - case 'f=': - *face = strdup( p ); - break; - case 's=': - *size = atoi( p ); - break; - case 'w=': - *weight = 0; - if( strstr( p, "bold" ) ) - *weight = NS_FONT_WEIGHT_BOLD; - else - *weight = NS_FONT_WEIGHT_NORMAL; - break; - case 'S=': - *style = 0; - if( strstr( p, "italic" ) ) - *style = NS_FONT_STYLE_ITALIC; - else - *style = NS_FONT_STYLE_NORMAL; - if( strstr( p, "antialias" ) ) - *style |= NS_FONT_STYLE_ANTIALIAS; - - break; - } - } + while ( fgets( buffer, 512, fp ) != NULL ) { + int len, code; + char *p, **face; + int *size; + short *style, *weight; + + /* skip comments and blank lines */ + if( buffer[0] == '#' || buffer[0] == ' ' || buffer[0] == '\n' ) + continue; + len = strlen( buffer ); + if( len<3 ) + continue; + + if( buffer[len-1] == '\n' ) + buffer[ len-1 ] = 0; + + code = buffer[0] << 8 | buffer[1]; + p = &buffer[2]; + switch( code ) { + case 'h=': + if( !strcmp( p, "General" ) ) { + style = &StyleGeneralFont; + face = &FaceGeneralFont; + weight = &WeightGeneralFont; + size = &SizeGeneralFont; + } + else if( !strcmp( p, "Message" ) ) { + style = &StyleMessageFont; + face = &FaceMessageFont; + weight = &WeightMessageFont; + size = &SizeMessageFont; + } + else if( !strcmp( p, "Menu" ) ) { + style = &StyleMenuFont; + face = &FaceMenuFont; + weight = &WeightMenuFont; + size = &SizeMenuFont; + } + else if( !strcmp( p, "Balloon" ) ) { + style = &StyleBalloonFont; + face = &FaceBalloonFont; + weight = &WeightBalloonFont; + size = &SizeBalloonFont; + } + break; + case 'f=': + *face = strdup( p ); + break; + case 's=': + *size = atoi( p ); + break; + case 'w=': + *weight = 0; + if( strstr( p, "bold" ) ) + *weight = NS_FONT_WEIGHT_BOLD; + else + *weight = NS_FONT_WEIGHT_NORMAL; + break; + case 'S=': + *style = 0; + if( strstr( p, "italic" ) ) + *style = NS_FONT_STYLE_ITALIC; + else + *style = NS_FONT_STYLE_NORMAL; + if( strstr( p, "antialias" ) ) + *style |= NS_FONT_STYLE_ANTIALIAS; + + break; + } + } - fclose( fp ); + fclose( fp ); - return 0; + return 0; } void nsDeviceContextPh :: DefaultSystemFonts( ) const { - FaceMessageFont = "MessageFont"; - SizeMessageFont = 8; - StyleMessageFont = NS_FONT_STYLE_NORMAL; - WeightMessageFont = NS_FONT_WEIGHT_NORMAL; - - FaceMenuFont = "MenuFont"; - SizeMenuFont = 8; - StyleMenuFont = NS_FONT_STYLE_NORMAL; - WeightMenuFont = NS_FONT_WEIGHT_NORMAL; - - FaceBalloonFont = "BalloonFont"; - SizeBalloonFont = 8; - StyleBalloonFont = NS_FONT_STYLE_NORMAL; - WeightBalloonFont = NS_FONT_WEIGHT_NORMAL; - - FaceGeneralFont = "TextFont"; - SizeGeneralFont = 8; - StyleGeneralFont = NS_FONT_STYLE_NORMAL; - WeightGeneralFont = NS_FONT_WEIGHT_NORMAL; + FaceMessageFont = "MessageFont"; + SizeMessageFont = 8; + StyleMessageFont = NS_FONT_STYLE_NORMAL; + WeightMessageFont = NS_FONT_WEIGHT_NORMAL; + + FaceMenuFont = "MenuFont"; + SizeMenuFont = 8; + StyleMenuFont = NS_FONT_STYLE_NORMAL; + WeightMenuFont = NS_FONT_WEIGHT_NORMAL; + + FaceBalloonFont = "BalloonFont"; + SizeBalloonFont = 8; + StyleBalloonFont = NS_FONT_STYLE_NORMAL; + WeightBalloonFont = NS_FONT_WEIGHT_NORMAL; + + FaceGeneralFont = "TextFont"; + SizeGeneralFont = 8; + StyleGeneralFont = NS_FONT_STYLE_NORMAL; + WeightGeneralFont = NS_FONT_WEIGHT_NORMAL; } NS_IMETHODIMP nsDeviceContextPh :: GetSystemFont( nsSystemFontID aID, nsFont *aFont) const { - if( !InitSystemFonts ) { - InitSystemFonts = 1; - DefaultSystemFonts( ); - ReadSystemFonts( ); - } + if( !InitSystemFonts ) { + InitSystemFonts = 1; + DefaultSystemFonts( ); + ReadSystemFonts( ); + } - aFont->decorations = NS_FONT_DECORATION_NONE; + aFont->decorations = NS_FONT_DECORATION_NONE; switch (aID) { case eSystemFont_Caption: // css2 - case eSystemFont_Icon: - case eSystemFont_SmallCaption: - case eSystemFont_StatusBar: - case eSystemFont_Window: // css3 - case eSystemFont_Document: - case eSystemFont_Workspace: - case eSystemFont_Desktop: - case eSystemFont_Info: - case eSystemFont_Dialog: - case eSystemFont_Button: - case eSystemFont_PullDownMenu: - case eSystemFont_List: - case eSystemFont_Field: - case eSystemFont_Widget: - aFont->name.AssignWithConversion( FaceGeneralFont ); - aFont->style = StyleGeneralFont; - aFont->weight = WeightGeneralFont; - aFont->size = SizeGeneralFont / ( mAppUnitsToDevUnits * 0.68 ); /* see nsFontMetricsPh::Init */ - break; - case eSystemFont_MessageBox: - aFont->name.AssignWithConversion( FaceMessageFont ); - aFont->style = StyleMessageFont; - aFont->weight = WeightMessageFont; - aFont->size = SizeMessageFont / ( mAppUnitsToDevUnits * 0.68 ); /* see nsFontMetricsPh::Init */ - break; - case eSystemFont_Tooltips: // moz - aFont->name.AssignWithConversion( FaceBalloonFont ); - aFont->style = StyleBalloonFont; - aFont->weight = WeightBalloonFont; - aFont->size = SizeBalloonFont / ( mAppUnitsToDevUnits * 0.68 ); /* see nsFontMetricsPh::Init */ - break; - case eSystemFont_Menu: - aFont->name.AssignWithConversion( FaceMenuFont ); - aFont->style = StyleMenuFont; - aFont->weight = WeightMenuFont; - aFont->size = SizeMenuFont / ( mAppUnitsToDevUnits * 0.68 ); /* see nsFontMetricsPh::Init */ - break; - } + case eSystemFont_Icon: + case eSystemFont_SmallCaption: + case eSystemFont_StatusBar: + case eSystemFont_Window: // css3 + case eSystemFont_Document: + case eSystemFont_Workspace: + case eSystemFont_Desktop: + case eSystemFont_Info: + case eSystemFont_Dialog: + case eSystemFont_Button: + case eSystemFont_PullDownMenu: + case eSystemFont_List: + case eSystemFont_Field: + case eSystemFont_Widget: + aFont->name.AssignWithConversion( FaceGeneralFont ); + aFont->style = StyleGeneralFont; + aFont->weight = WeightGeneralFont; + aFont->size = SizeGeneralFont / ( mAppUnitsToDevUnits * 0.68 ); /* see nsFontMetricsPh::Init */ + break; + case eSystemFont_MessageBox: + aFont->name.AssignWithConversion( FaceMessageFont ); + aFont->style = StyleMessageFont; + aFont->weight = WeightMessageFont; + aFont->size = SizeMessageFont / ( mAppUnitsToDevUnits * 0.68 ); /* see nsFontMetricsPh::Init */ + break; + case eSystemFont_Tooltips: // moz + aFont->name.AssignWithConversion( FaceBalloonFont ); + aFont->style = StyleBalloonFont; + aFont->weight = WeightBalloonFont; + aFont->size = SizeBalloonFont / ( mAppUnitsToDevUnits * 0.68 ); /* see nsFontMetricsPh::Init */ + break; + case eSystemFont_Menu: + aFont->name.AssignWithConversion( FaceMenuFont ); + aFont->style = StyleMenuFont; + aFont->weight = WeightMenuFont; + aFont->size = SizeMenuFont / ( mAppUnitsToDevUnits * 0.68 ); /* see nsFontMetricsPh::Init */ + break; + } aFont->systemFont = PR_TRUE; @@ -425,56 +433,56 @@ printf( "\tCheckFontExistence for fontName=%s\n", fontName ); #endif - nsCStringKey key( fontName ); - if( !mFontLoadCache ) mFontLoadCache = new nsHashtable(); - else { - int value = ( int ) mFontLoadCache->Get( &key ); - if( value == 1 ) { /* the font exists and you already asked this before */ - delete [] fontName; + nsCStringKey key( fontName ); + if( !mFontLoadCache ) mFontLoadCache = new nsHashtable(); + else { + int value = ( int ) mFontLoadCache->Get( &key ); + if( value == 1 ) { /* the font exists and you already asked this before */ + delete [] fontName; #ifdef DEBUG_Adrian printf( "\t\tFound it in cache it exists\n" ); #endif - return NS_OK; - } - else if( value == 2 ) { /* the font doesn't exist and you already asked this before */ - delete [] fontName; + return NS_OK; + } + else if( value == 2 ) { /* the font doesn't exist and you already asked this before */ + delete [] fontName; #ifdef DEBUG_Adrian printf( "\t\tFound it in cache it doesn't exist\n" ); #endif - return NS_ERROR_FAILURE; - } - /* else you didn't ask this before */ + return NS_ERROR_FAILURE; + } + /* else you didn't ask this before */ #ifdef DEBUG_Adrian printf( "\t\t Not Found in cache\n" ); #endif - } + } - /* here either the mFontLoadCache was not allocated ( first time ) or this is the first time you ask about it */ - - nsresult res; - if( PfFindFont( (char *)fontName, 0, 0 ) ) { - mFontLoadCache->Put( &key, (void*)1 ); - res = NS_OK; - } - else { - mFontLoadCache->Put( &key, (void*)2 ); - res = NS_ERROR_FAILURE; - } - delete [] fontName; - return res; - } + /* here either the mFontLoadCache was not allocated ( first time ) or this is the first time you ask about it */ + + nsresult res; + if( PfFindFont( (char *)fontName, 0, 0 ) ) { + mFontLoadCache->Put( &key, (void*)1 ); + res = NS_OK; + } + else { + mFontLoadCache->Put( &key, (void*)2 ); + res = NS_ERROR_FAILURE; + } + delete [] fontName; + return res; + } - return NS_ERROR_FAILURE; - } + return NS_ERROR_FAILURE; + } NS_IMETHODIMP nsDeviceContextPh :: GetDeviceSurfaceDimensions( PRInt32 &aWidth, PRInt32 &aHeight ) { #ifdef NS_PRINT_PREVIEW - // Defer to Alt when there is one - if (mAltDC && (mUseAltDC & kUseAltDCFor_SURFACE_DIM)) { - return mAltDC->GetDeviceSurfaceDimensions(aWidth, aHeight); - } + // Defer to Alt when there is one + if (mAltDC && (mUseAltDC & kUseAltDCFor_SURFACE_DIM)) { + return mAltDC->GetDeviceSurfaceDimensions(aWidth, aHeight); + } #endif if( mWidth == -1 ) mWidth = NSToIntRound(mWidthFloat * mDevUnitsToAppUnits); @@ -484,10 +492,10 @@ aHeight = mHeight; return NS_OK; - } + } NS_IMETHODIMP nsDeviceContextPh::GetRect( nsRect &aRect ) { - if( mScreenManager ) { + if( mScreenManager ) { nsCOMPtr screen; mScreenManager->GetPrimaryScreen( getter_AddRefs( screen ) ); screen->GetRect(&aRect.x, &aRect.y, &aRect.width, &aRect.height); @@ -495,32 +503,32 @@ aRect.y = NSToIntRound(mDevUnitsToAppUnits * aRect.y); aRect.width = NSToIntRound(mDevUnitsToAppUnits * aRect.width); aRect.height = NSToIntRound(mDevUnitsToAppUnits * aRect.height); - } - else { - PRInt32 width, height; - GetDeviceSurfaceDimensions( width, height ); - aRect.x = 0; - aRect.y = 0; - aRect.width = width; - aRect.height = height; - } + } + else { + PRInt32 width, height; + GetDeviceSurfaceDimensions( width, height ); + aRect.x = 0; + aRect.y = 0; + aRect.width = width; + aRect.height = height; + } return NS_OK; - } + } NS_IMETHODIMP nsDeviceContextPh :: GetDeviceContextFor( nsIDeviceContextSpec *aDevice, nsIDeviceContext *&aContext ) { - nsDeviceContextPh* devConPh = new nsDeviceContextPh(); //ref count 0 - if (devConPh != nsnull) { - // this will ref count it - nsresult rv = devConPh->QueryInterface(NS_GET_IID(nsIDeviceContext), (void**)&aContext); - NS_ASSERTION(NS_SUCCEEDED(rv), "This has to support nsIDeviceContext"); - } else { - return NS_ERROR_OUT_OF_MEMORY; - } - - devConPh->mSpec = aDevice; - NS_ADDREF(aDevice); - return devConPh->Init(NULL, this); - } + nsDeviceContextPh* devConPh = new nsDeviceContextPh(); //ref count 0 + if (devConPh != nsnull) { + // this will ref count it + nsresult rv = CallQueryInterface(devConPh, &aContext); + NS_ASSERTION(NS_SUCCEEDED(rv), "This has to support nsIDeviceContext"); + } else { + return NS_ERROR_OUT_OF_MEMORY; + } + + devConPh->mSpec = aDevice; + NS_ADDREF(aDevice); + return devConPh->Init(NULL, this); + } nsresult nsDeviceContextPh::SetDPI( PRInt32 aDpi ) { const int pt2t = 82;//72 @@ -532,7 +540,7 @@ mTwipsToPixels = 1.0f / mPixelsToTwips; // XXX need to reflow all documents return NS_OK; - } + } int nsDeviceContextPh::prefChanged( const char *aPref, void *aClosure ) { nsDeviceContextPh *context = (nsDeviceContextPh*)aClosure; @@ -543,54 +551,54 @@ nsCOMPtr prefs(do_GetService(NS_PREF_CONTRACTID, &rv)); rv = prefs->GetIntPref(aPref, &dpi); if( NS_SUCCEEDED( rv ) ) context->SetDPI( dpi ); - } + } return 0; - } + } NS_IMETHODIMP nsDeviceContextPh :: BeginDocument(PRUnichar *t, PRUnichar* aPrintToFileName, PRInt32 aStartPage, PRInt32 aEndPage) { - if( mSpec ) { - PpPrintContext_t *pc = ((nsDeviceContextSpecPh *)mSpec)->GetPrintContext(); - PpStartJob(pc); - mIsPrintingStart = 1; - } - return NS_OK; - } + if( mSpec ) { + PpPrintContext_t *pc = ((nsDeviceContextSpecPh *)mSpec)->GetPrintContext(); + PpStartJob(pc); + mIsPrintingStart = 1; + } + return NS_OK; + } NS_IMETHODIMP nsDeviceContextPh :: EndDocument( void ) { - if( mSpec ) { - PpPrintContext_t *pc = ((nsDeviceContextSpecPh *)mSpec)->GetPrintContext(); - PpEndJob(pc); - } + if( mSpec ) { + PpPrintContext_t *pc = ((nsDeviceContextSpecPh *)mSpec)->GetPrintContext(); + PpEndJob(pc); + } return NS_OK; - } + } NS_IMETHODIMP nsDeviceContextPh :: AbortDocument( void ) { return EndDocument(); - } + } NS_IMETHODIMP nsDeviceContextPh :: BeginPage( void ) { - if( mSpec ) { - PpPrintContext_t *pc = ((nsDeviceContextSpecPh *)mSpec)->GetPrintContext(); - PpContinueJob( pc ); - if( !mIsPrintingStart ) PpPrintNewPage( pc ); - mIsPrintingStart = 0; - } - return NS_OK; - } + if( mSpec ) { + PpPrintContext_t *pc = ((nsDeviceContextSpecPh *)mSpec)->GetPrintContext(); + PpContinueJob( pc ); + if( !mIsPrintingStart ) PpPrintNewPage( pc ); + mIsPrintingStart = 0; + } + return NS_OK; + } NS_IMETHODIMP nsDeviceContextPh :: EndPage( void ) { - if( mSpec ) { - PpPrintContext_t *pc = ((nsDeviceContextSpecPh *)mSpec)->GetPrintContext(); - PpSuspendJob(pc); - } - return NS_OK; - } + if( mSpec ) { + PpPrintContext_t *pc = ((nsDeviceContextSpecPh *)mSpec)->GetPrintContext(); + PpSuspendJob(pc); + } + return NS_OK; + } /* Get the size and color depth of the display */ nsresult nsDeviceContextPh :: GetDisplayInfo( PRInt32 &aWidth, PRInt32 &aHeight, PRUint32 &aDepth ) { - nsresult res = NS_ERROR_FAILURE; + nsresult res = NS_ERROR_FAILURE; PhSysInfo_t SysInfo; PhRect_t rect; char *p = NULL; @@ -602,23 +610,23 @@ aHeight = 0; aDepth = 0; - /* Get the Screen Size and Depth*/ - p = getenv("PHIG"); - if( p ) inp_grp = atoi( p ); - else inp_grp = 1; - - PhQueryRids( 0, 0, inp_grp, Ph_GRAFX_REGION, 0, 0, 0, &rid, 1 ); - PhWindowQueryVisible( Ph_QUERY_IG_POINTER, 0, inp_grp, &rect ); - aWidth = rect.lr.x - rect.ul.x + 1; - aHeight = rect.lr.y - rect.ul.y + 1; - - /* Get the System Info for the RID */ - if( PhQuerySystemInfo( rid, NULL, &SysInfo ) ) { - /* Make sure the "color_bits" field is valid */ - if( SysInfo.gfx.valid_fields & Ph_GFX_COLOR_BITS ) { - aDepth = SysInfo.gfx.color_bits; - res = NS_OK; - } - } + /* Get the Screen Size and Depth*/ + p = getenv("PHIG"); + if( p ) inp_grp = atoi( p ); + else inp_grp = 1; + + PhQueryRids( 0, 0, inp_grp, Ph_GRAFX_REGION, 0, 0, 0, &rid, 1 ); + PhWindowQueryVisible( Ph_QUERY_IG_POINTER, 0, inp_grp, &rect ); + aWidth = rect.lr.x - rect.ul.x + 1; + aHeight = rect.lr.y - rect.ul.y + 1; + + /* Get the System Info for the RID */ + if( PhQuerySystemInfo( rid, NULL, &SysInfo ) ) { + /* Make sure the "color_bits" field is valid */ + if( SysInfo.gfx.valid_fields & Ph_GFX_COLOR_BITS ) { + aDepth = SysInfo.gfx.color_bits; + res = NS_OK; + } + } return res; - } + } Index: mozilla/gfx/src/qt/nsDeviceContextQt.cpp =================================================================== RCS file: /cvsroot/mozilla/gfx/src/qt/nsDeviceContextQt.cpp,v retrieving revision 1.5 diff -u -r1.5 mozilla/gfx/src/qt/nsDeviceContextQt.cpp --- mozilla/gfx/src/qt/nsDeviceContextQt.cpp +++ mozilla/gfx/src/qt/nsDeviceContextQt.cpp @@ -344,8 +344,7 @@ if (NS_FAILED(rv)) return rv; - rv = dcxp->QueryInterface(NS_GET_IID(nsIDeviceContext), - (void **)&aContext); + rv = CallQueryInterface(dcxp, &aContext); return rv; } else @@ -370,8 +369,7 @@ if (NS_FAILED(rv)) return rv; - rv = dcps->QueryInterface(NS_GET_IID(nsIDeviceContext), - (void **)&aContext); + rv = CallQueryInterface(dcps, &aContext); return rv; } #endif /* USE_POSTSCRIPT */ Index: mozilla/gfx/src/thebes/nsThebesDeviceContext.cpp =================================================================== RCS file: /cvsroot/mozilla/gfx/src/thebes/nsThebesDeviceContext.cpp,v retrieving revision 1.40 diff -u -r1.40 mozilla/gfx/src/thebes/nsThebesDeviceContext.cpp --- mozilla/gfx/src/thebes/nsThebesDeviceContext.cpp +++ mozilla/gfx/src/thebes/nsThebesDeviceContext.cpp @@ -550,7 +550,7 @@ if (newDevCon) { // this will ref count it - nsresult rv = newDevCon->QueryInterface(NS_GET_IID(nsIDeviceContext), (void**)&aContext); + nsresult rv = CallQueryInterface(newDevCon, &aContext); NS_ASSERTION(NS_SUCCEEDED(rv), "This has to support nsIDeviceContext"); } else { return NS_ERROR_OUT_OF_MEMORY; Index: mozilla/gfx/src/windows/nsDeviceContextWin.cpp =================================================================== RCS file: /cvsroot/mozilla/gfx/src/windows/nsDeviceContextWin.cpp,v retrieving revision 3.126 diff -u -r3.126 mozilla/gfx/src/windows/nsDeviceContextWin.cpp --- mozilla/gfx/src/windows/nsDeviceContextWin.cpp +++ mozilla/gfx/src/windows/nsDeviceContextWin.cpp @@ -698,7 +698,7 @@ nsDeviceContextWin* devConWin = new nsDeviceContextWin(); //ref count 0 if (devConWin != nsnull) { // this will ref count it - nsresult rv = devConWin->QueryInterface(NS_GET_IID(nsIDeviceContext), (void**)&aContext); + nsresult rv = CallQueryInterface(devConWin, &aContext); NS_ASSERTION(NS_SUCCEEDED(rv), "This has to support nsIDeviceContext"); } else { return NS_ERROR_OUT_OF_MEMORY; Index: mozilla/gfx/src/xlib/nsDeviceContextXlib.cpp =================================================================== RCS file: /cvsroot/mozilla/gfx/src/xlib/nsDeviceContextXlib.cpp,v retrieving revision 1.72 diff -u -r1.72 mozilla/gfx/src/xlib/nsDeviceContextXlib.cpp --- mozilla/gfx/src/xlib/nsDeviceContextXlib.cpp +++ mozilla/gfx/src/xlib/nsDeviceContextXlib.cpp @@ -158,7 +158,7 @@ nsresult nsDeviceContextXlib::CommonInit(void) { - nsresult rv = NS_OK;; + nsresult rv = NS_OK; // FIXME: PeterH // This was set to 100 dpi, then later on in the function is was changed @@ -442,8 +442,7 @@ if (NS_FAILED(rv)) return rv; - rv = dcxp->QueryInterface(NS_GET_IID(nsIDeviceContext), - (void **)&aContext); + rv = CallQueryInterface(dcxp, &aContext); return rv; } else @@ -468,8 +467,7 @@ if (NS_FAILED(rv)) return rv; - rv = dcps->QueryInterface(NS_GET_IID(nsIDeviceContext), - (void **)&aContext); + rv = CallQueryInterface(dcps, &aContext); return rv; } #endif /* USE_POSTSCRIPT */ Index: mozilla/intl/chardet/tests/DetectCharset.cpp =================================================================== RCS file: /cvsroot/mozilla/intl/chardet/tests/DetectCharset.cpp,v retrieving revision 1.21 diff -u -r1.21 mozilla/intl/chardet/tests/DetectCharset.cpp --- mozilla/intl/chardet/tests/DetectCharset.cpp +++ mozilla/intl/chardet/tests/DetectCharset.cpp @@ -292,13 +292,13 @@ nsresult GetObserver(nsICharsetDetectionObserver** aRes) { - *aRes = nsnull; nsReporter* rep = new nsReporter(); - if(rep) { - return rep->QueryInterface(NS_GET_IID(nsICharsetDetectionObserver) , - (void**)aRes); + if(!rep) { + *aRes = nsnull; + return NS_ERROR_OUT_OF_MEMORY; } - return NS_ERROR_OUT_OF_MEMORY; + + return CallQueryInterface(rep, aRes); } int main(int argc, char** argv) { Index: mozilla/intl/locale/src/nsLocaleService.cpp =================================================================== RCS file: /cvsroot/mozilla/intl/locale/src/nsLocaleService.cpp,v retrieving revision 1.63 diff -u -r1.63 mozilla/intl/locale/src/nsLocaleService.cpp --- mozilla/intl/locale/src/nsLocaleService.cpp +++ mozilla/intl/locale/src/nsLocaleService.cpp @@ -67,16 +67,16 @@ const int LocaleListLength = 6; const char* LocaleList[LocaleListLength] = { - NSILOCALE_COLLATE, - NSILOCALE_CTYPE, - NSILOCALE_MONETARY, - NSILOCALE_NUMERIC, - NSILOCALE_TIME, - NSILOCALE_MESSAGE + NSILOCALE_COLLATE, + NSILOCALE_CTYPE, + NSILOCALE_MONETARY, + NSILOCALE_NUMERIC, + NSILOCALE_TIME, + NSILOCALE_MESSAGE }; -#define NSILOCALE_MAX_ACCEPT_LANGUAGE 16 -#define NSILOCALE_MAX_ACCEPT_LENGTH 18 +#define NSILOCALE_MAX_ACCEPT_LANGUAGE 16 +#define NSILOCALE_MAX_ACCEPT_LENGTH 18 #if (defined(XP_UNIX) && !defined(XP_MACOSX)) || defined(XP_BEOS) || defined(XP_OS2) static int posix_locale_category[LocaleListLength] = @@ -108,28 +108,28 @@ class nsLocaleService: public nsILocaleService { public: - - // - // nsISupports - // - NS_DECL_ISUPPORTS - - // - // nsILocaleService - // + + // + // nsISupports + // + NS_DECL_ISUPPORTS + + // + // nsILocaleService + // NS_DECL_NSILOCALESERVICE - nsLocaleService(void); - virtual ~nsLocaleService(void); + nsLocaleService(void); + virtual ~nsLocaleService(void); protected: - nsresult SetSystemLocale(void); - nsresult SetApplicationLocale(void); + nsresult SetSystemLocale(void); + nsresult SetApplicationLocale(void); - nsCOMPtr mSystemLocale; - nsCOMPtr mApplicationLocale; + nsCOMPtr mSystemLocale; + nsCOMPtr mApplicationLocale; }; @@ -137,26 +137,26 @@ // nsILocaleDefinition implementation // class nsLocaleDefinition: public nsILocaleDefinition { - friend class nsLocaleService; + friend class nsLocaleService; public: - // - // nsISupports - // - NS_DECL_ISUPPORTS - - // - // nsILocaleDefintion - // - NS_IMETHOD SetLocaleCategory(const nsAString &category, const nsAString &value); + // + // nsISupports + // + NS_DECL_ISUPPORTS + + // + // nsILocaleDefintion + // + NS_IMETHOD SetLocaleCategory(const nsAString &category, const nsAString &value); protected: - nsLocaleDefinition(); - virtual ~nsLocaleDefinition(); + nsLocaleDefinition(); + virtual ~nsLocaleDefinition(); - nsLocale* mLocaleDefinition; + nsLocale* mLocaleDefinition; }; @@ -384,58 +384,58 @@ NS_IMETHODIMP nsLocaleService::NewLocale(const nsAString &aLocale, nsILocale **_retval) { - int i; - nsresult result; + int i; + nsresult result; - *_retval = (nsILocale*)nsnull; - - nsLocale* resultLocale = new nsLocale(); - if (!resultLocale) return NS_ERROR_OUT_OF_MEMORY; - - for(i=0;iAddCategory(category, aLocale); - if (NS_FAILED(result)) { delete resultLocale; return result;} - } + *_retval = (nsILocale*)nsnull; + + nsLocale* resultLocale = new nsLocale(); + if (!resultLocale) return NS_ERROR_OUT_OF_MEMORY; + + for(i=0;iAddCategory(category, aLocale); + if (NS_FAILED(result)) { delete resultLocale; return result;} + } - return resultLocale->QueryInterface(NS_GET_IID(nsILocale),(void**)_retval); + return CallQueryInterface(resultLocale, _retval); } NS_IMETHODIMP nsLocaleService::NewLocaleObject(nsILocaleDefinition *localeDefinition, nsILocale **_retval) { - if (!localeDefinition || !_retval) return NS_ERROR_INVALID_ARG; + if (!localeDefinition || !_retval) return NS_ERROR_INVALID_ARG; - nsLocale* new_locale = new nsLocale(NS_STATIC_CAST(nsLocaleDefinition*,localeDefinition)->mLocaleDefinition); - if (!new_locale) return NS_ERROR_OUT_OF_MEMORY; + nsLocale* new_locale = new nsLocale(NS_STATIC_CAST(nsLocaleDefinition*,localeDefinition)->mLocaleDefinition); + if (!new_locale) return NS_ERROR_OUT_OF_MEMORY; - return new_locale->QueryInterface(NS_GET_IID(nsILocale),(void**)_retval); + return CallQueryInterface(new_locale, _retval); } NS_IMETHODIMP nsLocaleService::GetSystemLocale(nsILocale **_retval) { - if (mSystemLocale) { - NS_ADDREF(*_retval = mSystemLocale); - return NS_OK; - } + if (mSystemLocale) { + NS_ADDREF(*_retval = mSystemLocale); + return NS_OK; + } - *_retval = (nsILocale*)nsnull; - return NS_ERROR_FAILURE; + *_retval = (nsILocale*)nsnull; + return NS_ERROR_FAILURE; } NS_IMETHODIMP nsLocaleService::GetApplicationLocale(nsILocale **_retval) { - if (mApplicationLocale) { - NS_ADDREF(*_retval = mApplicationLocale); - return NS_OK; - } + if (mApplicationLocale) { + NS_ADDREF(*_retval = mApplicationLocale); + return NS_OK; + } - *_retval=(nsILocale*)nsnull; - return NS_ERROR_FAILURE; + *_retval=(nsILocale*)nsnull; + return NS_ERROR_FAILURE; } NS_IMETHODIMP @@ -448,8 +448,8 @@ int i; int j; int countLang = 0; - char acceptLanguageList[NSILOCALE_MAX_ACCEPT_LANGUAGE][NSILOCALE_MAX_ACCEPT_LENGTH]; - nsresult result; + char acceptLanguageList[NSILOCALE_MAX_ACCEPT_LANGUAGE][NSILOCALE_MAX_ACCEPT_LENGTH]; + nsresult result; input = new char[strlen(acceptLanguage)+1]; NS_ASSERTION(input!=nsnull,"nsLocaleFactory::GetLocaleFromAcceptLanguage: memory allocation failed."); @@ -532,7 +532,7 @@ // result = NS_ERROR_FAILURE; if (countLang>0) { - result = NewLocale(NS_ConvertASCIItoUTF16(acceptLanguageList[0]), _retval); + result = NewLocale(NS_ConvertASCIItoUTF16(acceptLanguageList[0]), _retval); } // @@ -583,22 +583,22 @@ nsLocaleDefinition::nsLocaleDefinition(void) { - mLocaleDefinition = new nsLocale; - if (mLocaleDefinition) - mLocaleDefinition->AddRef(); + mLocaleDefinition = new nsLocale; + if (mLocaleDefinition) + mLocaleDefinition->AddRef(); } nsLocaleDefinition::~nsLocaleDefinition(void) { - if (mLocaleDefinition) - mLocaleDefinition->Release(); + if (mLocaleDefinition) + mLocaleDefinition->Release(); } NS_IMETHODIMP nsLocaleDefinition::SetLocaleCategory(const nsAString &category, const nsAString &value) { - if (mLocaleDefinition) - return mLocaleDefinition->AddCategory(category,value); - - return NS_ERROR_FAILURE; + if (mLocaleDefinition) + return mLocaleDefinition->AddCategory(category,value); + + return NS_ERROR_FAILURE; } Index: mozilla/intl/strres/src/nsStringBundle.cpp =================================================================== RCS file: /cvsroot/mozilla/intl/strres/src/nsStringBundle.cpp,v retrieving revision 1.150 diff -u -r1.150 mozilla/intl/strres/src/nsStringBundle.cpp --- mozilla/intl/strres/src/nsStringBundle.cpp +++ mozilla/intl/strres/src/nsStringBundle.cpp @@ -742,7 +742,7 @@ return res; } - res = bundle->QueryInterface(NS_GET_IID(nsIStringBundle), (void**) aResult); + res = CallQueryInterface(bundle, aResult); if (NS_FAILED(res)) delete bundle; return res; Index: mozilla/intl/uconv/tests/nsTestUConv.cpp =================================================================== RCS file: /cvsroot/mozilla/intl/uconv/tests/nsTestUConv.cpp,v retrieving revision 1.51 diff -u -r1.51 mozilla/intl/uconv/tests/nsTestUConv.cpp --- mozilla/intl/uconv/tests/nsTestUConv.cpp +++ mozilla/intl/uconv/tests/nsTestUConv.cpp @@ -220,7 +220,7 @@ #ifdef TEST_IS_REPRESENTABLE nsICharRepresentable* rp = nsnull; - res = aEnc->QueryInterface(NS_GET_IID(nsICharRepresentable),(void**) &rp); + res = CallQueryInterface(aEnc, &rp); if(NS_SUCCEEDED(res)) { PRUint32 *info= (PRUint32*)PR_Calloc((0x10000 >> 5), 4); rp->FillInfo(info); Index: mozilla/intl/uconv/ucvko/nsUnicodeToX11Johab.cpp =================================================================== RCS file: /cvsroot/mozilla/intl/uconv/ucvko/nsUnicodeToX11Johab.cpp,v retrieving revision 1.12 diff -u -r1.12 mozilla/intl/uconv/ucvko/nsUnicodeToX11Johab.cpp --- mozilla/intl/uconv/ucvko/nsUnicodeToX11Johab.cpp +++ mozilla/intl/uconv/ucvko/nsUnicodeToX11Johab.cpp @@ -49,35 +49,11 @@ // XPCOM stuff NS_IMPL_ADDREF(nsUnicodeToX11Johab) NS_IMPL_RELEASE(nsUnicodeToX11Johab) -nsresult nsUnicodeToX11Johab::QueryInterface(REFNSIID aIID, - void** aInstancePtr) -{ - if (NULL == aInstancePtr) { - return NS_ERROR_NULL_POINTER; - } - - *aInstancePtr = NULL; - - static NS_DEFINE_IID(kISupportsIID, NS_ISUPPORTS_IID); - - if (aIID.Equals(NS_GET_IID(nsIUnicodeEncoder))) { - *aInstancePtr = (void*) ((nsIUnicodeEncoder*)this); - NS_ADDREF_THIS(); - return NS_OK; - } - if (aIID.Equals(NS_GET_IID(nsICharRepresentable))) { - *aInstancePtr = (void*) ((nsICharRepresentable*)this); - NS_ADDREF_THIS(); - return NS_OK; - } - if (aIID.Equals(kISupportsIID)) { - *aInstancePtr = (void*) ((nsISupports*)((nsIUnicodeEncoder*)this)); - NS_ADDREF_THIS(); - return NS_OK; - } - - return NS_NOINTERFACE; -} +NS_INTERFACE_MAP_BEGIN(nsUnicodeToX11Johab) + NS_INTERFACE_MAP_ENTRY(nsIUnicodeEncoder) + NS_INTERFACE_MAP_ENTRY(nsICharRepresentable) + NS_INTERFACE_MAP_ENTRY_AMBIGUOUS(nsISupports, nsIUnicodeEncoder) +NS_INTERFACE_MAP_END NS_IMETHODIMP nsUnicodeToX11Johab::SetOutputErrorBehavior( Index: mozilla/js/src/xpconnect/src/nsXPConnect.cpp =================================================================== RCS file: /cvsroot/mozilla/js/src/xpconnect/src/nsXPConnect.cpp,v retrieving revision 1.89 diff -u -r1.89 mozilla/js/src/xpconnect/src/nsXPConnect.cpp --- mozilla/js/src/xpconnect/src/nsXPConnect.cpp +++ mozilla/js/src/xpconnect/src/nsXPConnect.cpp @@ -1407,29 +1407,25 @@ nsIXPConnectWrappedNative* wn; nsIXPConnectWrappedJS* wjs; - if(NS_SUCCEEDED(p->QueryInterface(NS_GET_IID(nsIXPConnect), - (void**)&xpc))) + if(NS_SUCCEEDED(CallQueryInterface(p, &xpc))) { XPC_LOG_ALWAYS(("Dumping a nsIXPConnect...")); xpc->DebugDump(depth); NS_RELEASE(xpc); } - else if(NS_SUCCEEDED(p->QueryInterface(NS_GET_IID(nsIXPCWrappedJSClass), - (void**)&wjsc))) + else if(NS_SUCCEEDED(CallQueryInterface(p, &wjsc))) { XPC_LOG_ALWAYS(("Dumping a nsIXPCWrappedJSClass...")); wjsc->DebugDump(depth); NS_RELEASE(wjsc); } - else if(NS_SUCCEEDED(p->QueryInterface(NS_GET_IID(nsIXPConnectWrappedNative), - (void**)&wn))) + else if(NS_SUCCEEDED(CallQueryInterface(p, &wn))) { XPC_LOG_ALWAYS(("Dumping a nsIXPConnectWrappedNative...")); wn->DebugDump(depth); NS_RELEASE(wn); } - else if(NS_SUCCEEDED(p->QueryInterface(NS_GET_IID(nsIXPConnectWrappedJS), - (void**)&wjs))) + else if(NS_SUCCEEDED(CallQueryInterface(p, &wjs))) { XPC_LOG_ALWAYS(("Dumping a nsIXPConnectWrappedJS...")); wjs->DebugDump(depth); Index: mozilla/js/src/xpconnect/src/xpcconvert.cpp =================================================================== RCS file: /cvsroot/mozilla/js/src/xpconnect/src/xpcconvert.cpp,v retrieving revision 1.110 diff -u -r1.110 mozilla/js/src/xpconnect/src/xpcconvert.cpp --- mozilla/js/src/xpconnect/src/xpcconvert.cpp +++ mozilla/js/src/xpconnect/src/xpcconvert.cpp @@ -1075,9 +1075,7 @@ nsCOMPtr wrapper; if(NS_FAILED(src->QueryInterface(*iid,(void**)getter_AddRefs(wrapper)))) return JS_FALSE; - return NS_SUCCEEDED(wrapper->QueryInterface( - NS_GET_IID(nsIXPConnectJSObjectHolder), - (void**) dest)); + return NS_SUCCEEDED(CallQueryInterface(wrapper, dest)); } else #endif /* XPC_DO_DOUBLE_WRAP */ Index: mozilla/js/src/xpconnect/src/xpcexception.cpp =================================================================== RCS file: /cvsroot/mozilla/js/src/xpconnect/src/xpcexception.cpp,v retrieving revision 1.32 diff -u -r1.32 mozilla/js/src/xpconnect/src/xpcexception.cpp --- mozilla/js/src/xpconnect/src/xpcexception.cpp +++ mozilla/js/src/xpconnect/src/xpcexception.cpp @@ -468,7 +468,7 @@ if(NS_FAILED(location->GetCaller(getter_AddRefs(caller))) || !caller) break; NS_RELEASE(location); - caller->QueryInterface(NS_GET_IID(nsIStackFrame), (void **)&location); + CallQueryInterface(caller, &location); } // at this point we have non-null location with one extra addref, // or no location at all Index: mozilla/js/src/xpconnect/src/xpcjsid.cpp =================================================================== RCS file: /cvsroot/mozilla/js/src/xpconnect/src/xpcjsid.cpp,v retrieving revision 1.69 diff -u -r1.69 mozilla/js/src/xpconnect/src/xpcjsid.cpp --- mozilla/js/src/xpconnect/src/xpcjsid.cpp +++ mozilla/js/src/xpconnect/src/xpcjsid.cpp @@ -330,8 +330,7 @@ rv = NS_NewGenericFactory(getter_AddRefs(factory), &CI_nsJSIID); if(NS_FAILED(rv)) goto return_failure; - rv = factory->QueryInterface(NS_GET_IID(nsIClassInfo), - (void**)&NS_CLASSINFO_NAME(nsJSIID)); + rv = CallQueryInterface(factory, &NS_CLASSINFO_NAME(nsJSIID)); if(NS_FAILED(rv)) goto return_failure; } @@ -342,8 +341,7 @@ rv = NS_NewGenericFactory(getter_AddRefs(factory), &CI_nsJSCID); if(NS_FAILED(rv)) goto return_failure; - rv = factory->QueryInterface(NS_GET_IID(nsIClassInfo), - (void**)&NS_CLASSINFO_NAME(nsJSCID)); + rv = CallQueryInterface(factory, &NS_CLASSINFO_NAME(nsJSCID)); if(NS_FAILED(rv)) goto return_failure; } Index: mozilla/layout/base/nsCSSFrameConstructor.cpp =================================================================== RCS file: /cvsroot/mozilla/layout/base/nsCSSFrameConstructor.cpp,v retrieving revision 1.1286 diff -u -r1.1286 mozilla/layout/base/nsCSSFrameConstructor.cpp --- mozilla/layout/base/nsCSSFrameConstructor.cpp +++ mozilla/layout/base/nsCSSFrameConstructor.cpp @@ -2494,7 +2494,7 @@ AdjustCaptionParentFrame(nsIFrame* aParentFrame) { if (nsLayoutAtoms::tableFrame == aParentFrame->GetType()) { - return aParentFrame->GetParent();; + return aParentFrame->GetParent(); } return aParentFrame; } @@ -5882,6 +5882,7 @@ PRBool aAppendToExisting, nsFrameItems& aChildItems) { + nsresult rv; nsCOMPtr creator(do_QueryInterface(aParentFrame)); if (!creator) @@ -5929,13 +5930,12 @@ for (PRUint32 i=0; i < count; i++) { // get our child's content and set its parent to our content - nsCOMPtr content; - if (NS_FAILED(anonymousItems->QueryElementAt(i, NS_GET_IID(nsIContent), getter_AddRefs(content)))) + nsCOMPtr content(do_QueryElementAt(anonymousItems, i, &rv)); + if (NS_FAILED(rv)) continue; content->SetNativeAnonymous(PR_TRUE); - nsresult rv; nsIContent* bindingParent = content; #ifdef MOZ_XUL // Only cut XUL scrollbars off if they're not in a XUL document. @@ -6588,7 +6588,7 @@ aState.mPresContext->SetScalingOfTwips(PR_TRUE); } - return aScrolledChildStyle;; + return aScrolledChildStyle; } void @@ -12364,7 +12364,7 @@ } nsIFrame* newTextFrame = NS_NewTextFrame(aPresShell, newSC); if (NS_UNLIKELY(!newTextFrame)) { - return NS_ERROR_OUT_OF_MEMORY;; + return NS_ERROR_OUT_OF_MEMORY; } newTextFrame->Init(textContent, parentFrame, nsnull); Index: mozilla/layout/base/nsCaret.cpp =================================================================== RCS file: /cvsroot/mozilla/layout/base/nsCaret.cpp,v retrieving revision 1.167 diff -u -r1.167 mozilla/layout/base/nsCaret.cpp --- mozilla/layout/base/nsCaret.cpp +++ mozilla/layout/base/nsCaret.cpp @@ -1163,6 +1163,6 @@ if (nsnull == caret) return NS_ERROR_OUT_OF_MEMORY; - return caret->QueryInterface(NS_GET_IID(nsICaret), (void**) aInstancePtrResult); + return CallQueryInterface(caret, aInstancePtrResult); } Index: mozilla/layout/base/nsLayoutDebugger.cpp =================================================================== RCS file: /cvsroot/mozilla/layout/base/nsLayoutDebugger.cpp,v retrieving revision 1.13 diff -u -r1.13 mozilla/layout/base/nsLayoutDebugger.cpp --- mozilla/layout/base/nsLayoutDebugger.cpp +++ mozilla/layout/base/nsLayoutDebugger.cpp @@ -85,7 +85,7 @@ if (!it) { return NS_ERROR_OUT_OF_MEMORY; } - return it->QueryInterface(NS_GET_IID(nsILayoutDebugger), (void**)aResult); + return CallQueryInterface(it, aResult); } nsLayoutDebugger::nsLayoutDebugger() Index: mozilla/layout/base/nsPresShell.cpp =================================================================== RCS file: /cvsroot/mozilla/layout/base/nsPresShell.cpp,v retrieving revision 3.950 diff -u -r3.950 mozilla/layout/base/nsPresShell.cpp --- mozilla/layout/base/nsPresShell.cpp +++ mozilla/layout/base/nsPresShell.cpp @@ -1650,8 +1650,7 @@ if (nsnull == it) { return NS_ERROR_OUT_OF_MEMORY; } - return it->QueryInterface(NS_GET_IID(nsIPresShell), - (void **) aInstancePtrResult); + return CallQueryInterface(it, aInstancePtrResult); } PresShell::PresShell() @@ -4492,7 +4491,7 @@ ScrollViewToShowRect(scrollingView, frameBounds, aVPercent, aHPercent); } } - frameBounds += closestView->GetPosition();; + frameBounds += closestView->GetPosition(); closestView = parent; } Index: mozilla/layout/forms/nsSelectsAreaFrame.cpp =================================================================== RCS file: /cvsroot/mozilla/layout/forms/nsSelectsAreaFrame.cpp,v retrieving revision 1.24 diff -u -r1.24 mozilla/layout/forms/nsSelectsAreaFrame.cpp --- mozilla/layout/forms/nsSelectsAreaFrame.cpp +++ mozilla/layout/forms/nsSelectsAreaFrame.cpp @@ -76,9 +76,9 @@ nsSelectsAreaFrame::IsOptionElement(nsIContent* aContent) { PRBool result = PR_FALSE; - - nsCOMPtr optElem; - if (NS_SUCCEEDED(aContent->QueryInterface(NS_GET_IID(nsIDOMHTMLOptionElement),(void**) getter_AddRefs(optElem)))) { + nsresult rv; + nsCOMPtr optElem(do_QueryInterface(aContent, &rv)); + if (NS_SUCCEEDED(rv)) { if (optElem != nsnull) { result = PR_TRUE; } Index: mozilla/layout/generic/nsBulletFrame.cpp =================================================================== RCS file: /cvsroot/mozilla/layout/generic/nsBulletFrame.cpp,v retrieving revision 1.151 diff -u -r1.151 mozilla/layout/generic/nsBulletFrame.cpp --- mozilla/layout/generic/nsBulletFrame.cpp +++ mozilla/layout/generic/nsBulletFrame.cpp @@ -137,7 +137,7 @@ NS_NEWXPCOM(listener, nsBulletListener); NS_ADDREF(listener); listener->SetFrame(this); - listener->QueryInterface(NS_GET_IID(imgIDecoderObserver), getter_AddRefs(mListener)); + mListener = do_QueryInterface(listener); NS_ASSERTION(mListener, "queryinterface for the listener failed"); NS_RELEASE(listener); } Index: mozilla/layout/generic/nsFrameUtil.cpp =================================================================== RCS file: /cvsroot/mozilla/layout/generic/nsFrameUtil.cpp,v retrieving revision 1.35 diff -u -r1.35 mozilla/layout/generic/nsFrameUtil.cpp --- mozilla/layout/generic/nsFrameUtil.cpp +++ mozilla/layout/generic/nsFrameUtil.cpp @@ -522,7 +522,7 @@ if (nsnull == it) { return NS_ERROR_OUT_OF_MEMORY; } - return it->QueryInterface(NS_GET_IID(nsIFrameUtil), (void**) aResult); + return CallQueryInterface(it, aResult); } nsFrameUtil::nsFrameUtil() Index: mozilla/layout/html/tests/TestAttributes.cpp =================================================================== RCS file: /cvsroot/mozilla/layout/html/tests/TestAttributes.cpp,v retrieving revision 3.61 diff -u -r3.61 mozilla/layout/html/tests/TestAttributes.cpp --- mozilla/layout/html/tests/TestAttributes.cpp +++ mozilla/layout/html/tests/TestAttributes.cpp @@ -257,7 +257,7 @@ } nsIDOMText* txt = nsnull; - text->QueryInterface(NS_GET_IID(nsIDOMText), (void**) &txt); + CallQueryInterface(text, &txt); nsAutoString tmp(destStr); txt->AppendData(tmp); NS_RELEASE(txt); @@ -272,7 +272,7 @@ #if 0 // Query IContent interface nsIContent* textContent; - rv = text->QueryInterface(NS_GET_IID(nsIContent),(void **)&textContent); + rv = CallQueryInterface(text, &textContent); if (NS_OK != rv) { printf("Created text content does not have the IContent interface.\n"); return -1; Index: mozilla/layout/style/nsCSSParser.cpp =================================================================== RCS file: /cvsroot/mozilla/layout/style/nsCSSParser.cpp,v retrieving revision 3.330 diff -u -r3.330 mozilla/layout/style/nsCSSParser.cpp --- mozilla/layout/style/nsCSSParser.cpp +++ mozilla/layout/style/nsCSSParser.cpp @@ -486,7 +486,7 @@ return NS_ERROR_OUT_OF_MEMORY; } - return it->QueryInterface(NS_GET_IID(nsICSSParser), (void **) aInstancePtrResult); + return CallQueryInterface(it, aInstancePtrResult); } #ifdef CSS_REPORT_PARSE_ERRORS Index: mozilla/layout/style/nsCSSStyleSheet.cpp =================================================================== RCS file: /cvsroot/mozilla/layout/style/nsCSSStyleSheet.cpp,v retrieving revision 3.367 diff -u -r3.367 mozilla/layout/style/nsCSSStyleSheet.cpp --- mozilla/layout/style/nsCSSStyleSheet.cpp +++ mozilla/layout/style/nsCSSStyleSheet.cpp @@ -937,7 +937,8 @@ if (aContains) { // if we found it and the out-param is there, set it and addref if (aTheChild) { - rv = QueryInterface( NS_GET_IID(nsIStyleSheet), (void **)aTheChild); + rv = CallQueryInterface(NS_ISUPPORTS_CAST(nsICSSStyleSheet*, this), + aTheChild); } } else { nsCSSStyleSheet* child = mFirstChild; @@ -1371,8 +1372,7 @@ nsresult rv = NS_OK; if (mParent) { - rv = mParent->QueryInterface(NS_GET_IID(nsIDOMStyleSheet), - (void **)aParentStyleSheet); + rv = CallQueryInterface(mParent, aParentStyleSheet); } else { *aParentStyleSheet = nsnull; } @@ -1858,7 +1858,7 @@ nsCOMPtr parentSheet; aSheet->GetParentSheet(*getter_AddRefs(parentSheet)); nsCOMPtr thisSheet; - QueryInterface(NS_GET_IID(nsIStyleSheet), getter_AddRefs(thisSheet)); + thisSheet = do_QueryInterface(NS_ISUPPORTS_CAST(nsICSSStyleSheet*, this)); NS_ASSERTION(thisSheet == parentSheet, "We are being notified of a sheet load for a sheet that is not our child!\n"); #endif Index: mozilla/layout/tables/nsTableColGroupFrame.cpp =================================================================== RCS file: /cvsroot/mozilla/layout/tables/nsTableColGroupFrame.cpp,v retrieving revision 3.160 diff -u -r3.160 mozilla/layout/tables/nsTableColGroupFrame.cpp --- mozilla/layout/tables/nsTableColGroupFrame.cpp +++ mozilla/layout/tables/nsTableColGroupFrame.cpp @@ -370,7 +370,7 @@ if (collapseGroup) { nsTableFrame* tableFrame = nsTableFrame::GetTableFrame(this); if (tableFrame) { - tableFrame->SetNeedToCollapse(PR_TRUE);; + tableFrame->SetNeedToCollapse(PR_TRUE); } } // for every content child that (is a column thingy and does not already have a frame) @@ -534,8 +534,7 @@ // col group element derives from col element nsIDOMHTMLTableColElement* cgContent = nsnull; - nsresult rv = iContent->QueryInterface(NS_GET_IID(nsIDOMHTMLTableColElement), - (void **)&cgContent); + nsresult rv = CallQueryInterface(iContent, &cgContent); if (cgContent && NS_SUCCEEDED(rv)) { cgContent->GetSpan(&span); // XXX why does this work!! Index: mozilla/layout/xul/base/src/nsImageBoxFrame.cpp =================================================================== RCS file: /cvsroot/mozilla/layout/xul/base/src/nsImageBoxFrame.cpp,v retrieving revision 1.114 diff -u -r1.114 mozilla/layout/xul/base/src/nsImageBoxFrame.cpp --- mozilla/layout/xul/base/src/nsImageBoxFrame.cpp +++ mozilla/layout/xul/base/src/nsImageBoxFrame.cpp @@ -230,9 +230,11 @@ if (!mListener) { nsImageBoxListener *listener; NS_NEWXPCOM(listener, nsImageBoxListener); + if (!listener) + return NS_ERROR_OUT_OF_MEMORY; NS_ADDREF(listener); listener->SetFrame(this); - listener->QueryInterface(NS_GET_IID(imgIDecoderObserver), getter_AddRefs(mListener)); + mListener = do_QueryInterface(listener); NS_RELEASE(listener); } Index: mozilla/layout/xul/base/src/tree/src/nsTreeContentView.cpp =================================================================== RCS file: /cvsroot/mozilla/layout/xul/base/src/tree/src/nsTreeContentView.cpp,v retrieving revision 1.63 diff -u -r1.63 mozilla/layout/xul/base/src/tree/src/nsTreeContentView.cpp --- mozilla/layout/xul/base/src/tree/src/nsTreeContentView.cpp +++ mozilla/layout/xul/base/src/tree/src/nsTreeContentView.cpp @@ -763,7 +763,7 @@ return NS_ERROR_INVALID_ARG; Row* row = (Row*)mRows[aIndex]; - row->mContent->QueryInterface(NS_GET_IID(nsIDOMElement), (void**)_retval); + CallQueryInterface(row->mContent, _retval); return NS_OK; } Index: mozilla/mailnews/addrbook/src/nsAbAutoCompleteSession.cpp =================================================================== RCS file: /cvsroot/mozilla/mailnews/addrbook/src/nsAbAutoCompleteSession.cpp,v retrieving revision 1.76 diff -u -r1.76 mozilla/mailnews/addrbook/src/nsAbAutoCompleteSession.cpp --- mozilla/mailnews/addrbook/src/nsAbAutoCompleteSession.cpp +++ mozilla/mailnews/addrbook/src/nsAbAutoCompleteSession.cpp @@ -248,9 +248,7 @@ for (; insertPosition < nbrOfItems && !pDefaultMatch; insertPosition++) { nsCOMPtr currentItemParams; - nsCOMPtr resultItem; - nsresult rv = array->QueryElementAt(insertPosition, NS_GET_IID(nsIAutoCompleteItem), - getter_AddRefs(resultItem)); + nsCOMPtr resultItem(do_QueryElementAt(array, insertPosition, &rv)); if (NS_FAILED(rv)) continue; rv = resultItem->GetParam(getter_AddRefs(currentItemParams)); @@ -603,8 +601,7 @@ for (i = 0, pos = 0; i < nbrOfItems; i ++, pos ++) { - rv = array->QueryElementAt(pos, NS_GET_IID(nsIAutoCompleteItem), - getter_AddRefs(resultItem)); + resultItem = do_QueryElementAt(array, pos, &rv); NS_ENSURE_SUCCESS(rv, rv); rv = resultItem->GetParam(getter_AddRefs(item)); Index: mozilla/mailnews/addrbook/src/nsAbMDBCard.cpp =================================================================== RCS file: /cvsroot/mozilla/mailnews/addrbook/src/nsAbMDBCard.cpp,v retrieving revision 1.12 diff -u -r1.12 mozilla/mailnews/addrbook/src/nsAbMDBCard.cpp --- mozilla/mailnews/addrbook/src/nsAbMDBCard.cpp +++ mozilla/mailnews/addrbook/src/nsAbMDBCard.cpp @@ -36,7 +36,7 @@ * * ***** END LICENSE BLOCK ***** */ -#include "nsAbMDBCard.h" +#include "nsAbMDBCard.h" #include "nsIRDFService.h" #include "nsIServiceManager.h" #include "nsRDFCID.h" @@ -61,15 +61,15 @@ nsresult nsAbMDBCard::NotifyPropertyChanged(const char *property, const PRUnichar* oldValue, const PRUnichar* newValue) { - nsCOMPtr supports; - if(NS_SUCCEEDED(QueryInterface(NS_GET_IID(nsISupports), getter_AddRefs(supports)))) - { - nsresult rv; - nsCOMPtr abSession = - do_GetService(NS_ADDRBOOKSESSION_CONTRACTID, &rv); - if(NS_SUCCEEDED(rv)) - abSession->NotifyItemPropertyChanged(supports, property, oldValue, newValue); - } + nsCOMPtr supports(do_QueryInterface(NS_ISUPPORTS_CAST(nsIAbMDBCard*, this), &rv)); + if(NS_SUCCEEDED(rv)) + { + nsresult rv; + nsCOMPtr abSession = + do_GetService(NS_ADDRBOOKSESSION_CONTRACTID, &rv); + if(NS_SUCCEEDED(rv)) + abSession->NotifyItemPropertyChanged(supports, property, oldValue, newValue); + } - return NS_OK; + return NS_OK; } Index: mozilla/mailnews/addrbook/src/nsAddrBookSession.cpp =================================================================== RCS file: /cvsroot/mozilla/mailnews/addrbook/src/nsAddrBookSession.cpp,v retrieving revision 1.31 diff -u -r1.31 mozilla/mailnews/addrbook/src/nsAddrBookSession.cpp --- mozilla/mailnews/addrbook/src/nsAddrBookSession.cpp +++ mozilla/mailnews/addrbook/src/nsAddrBookSession.cpp @@ -99,8 +99,7 @@ for(i = 0; i < count; i++) { if (mListenerNotifyFlags[i] & changed) { - nsCOMPtr listener; - mListeners->QueryElementAt(i, NS_GET_IID(nsIAbListener), (void **) getter_AddRefs(listener)); + nsCOMPtr listener(do_QueryElementAt(mListeners, i)); NS_ASSERTION(listener, "listener is null"); if (listener) listener->OnItemPropertyChanged(item, property, oldValue, newValue); @@ -120,8 +119,7 @@ for(i = 0; i < count; i++) { if (mListenerNotifyFlags[i] & added) { - nsCOMPtr listener; - mListeners->QueryElementAt(i, NS_GET_IID(nsIAbListener), (void **) getter_AddRefs(listener)); + nsCOMPtr listener(do_QueryElementAt(mListeners, i)); NS_ASSERTION(listener, "listener is null"); if (listener) listener->OnItemAdded(directory, item); @@ -143,8 +141,7 @@ for(i = 0; i < count; i++) { if (mListenerNotifyFlags[i] & directoryItemRemoved) { - nsCOMPtr listener; - mListeners->QueryElementAt(i, NS_GET_IID(nsIAbListener), (void **) getter_AddRefs(listener)); + nsCOMPtr listener(do_QueryElementAt(mListeners, i)); NS_ASSERTION(listener, "listener is null"); if (listener) listener->OnItemRemoved(directory, item); @@ -165,8 +162,7 @@ for(i = 0; i < count; i++) { if (mListenerNotifyFlags[i] & directoryRemoved) { - nsCOMPtr listener; - mListeners->QueryElementAt(i, NS_GET_IID(nsIAbListener), (void **) getter_AddRefs(listener)); + nsCOMPtr listener(do_QueryElementAt(mListeners, i)); NS_ASSERTION(listener, "listener is null"); if (listener) listener->OnItemRemoved(directory, item); Index: mozilla/mailnews/addrbook/src/nsAddrDatabase.cpp =================================================================== RCS file: /cvsroot/mozilla/mailnews/addrbook/src/nsAddrDatabase.cpp,v retrieving revision 1.148 diff -u -r1.148 mozilla/mailnews/addrbook/src/nsAddrDatabase.cpp --- mozilla/mailnews/addrbook/src/nsAddrDatabase.cpp +++ mozilla/mailnews/addrbook/src/nsAddrDatabase.cpp @@ -208,20 +208,7 @@ return count; } -NS_IMETHODIMP nsAddrDatabase::QueryInterface(REFNSIID aIID, void** aResult) -{ - if (aResult == NULL) - return NS_ERROR_NULL_POINTER; - - if (aIID.Equals(NS_GET_IID(nsIAddrDatabase)) || - aIID.Equals(NS_GET_IID(nsIAddrDBAnnouncer)) || - aIID.Equals(NS_GET_IID(nsISupports))) { - *aResult = NS_STATIC_CAST(nsIAddrDatabase*, this); - NS_ADDREF_THIS(); - return NS_OK; - } - return NS_NOINTERFACE; -} +NS_IMPL_QUERY_INTERFACE2(nsAddrDatabase, nsIAddrDatabase, nsIAddrDBAnnouncer) NS_IMETHODIMP nsAddrDatabase::AddListener(nsIAddrDBListener *listener) { Index: mozilla/mailnews/addrbook/src/nsDirectoryDataSource.cpp =================================================================== RCS file: /cvsroot/mozilla/mailnews/addrbook/src/nsDirectoryDataSource.cpp,v retrieving revision 1.78 diff -u -r1.78 mozilla/mailnews/addrbook/src/nsDirectoryDataSource.cpp --- mozilla/mailnews/addrbook/src/nsDirectoryDataSource.cpp +++ mozilla/mailnews/addrbook/src/nsDirectoryDataSource.cpp @@ -238,7 +238,7 @@ { return directory->GetChildNodes(targets); } - else if((kNC_DirName == property) || + else if ((kNC_DirName == property) || (kNC_DirUri == property) || (kNC_IsMailList == property) || (kNC_IsRemote == property) || @@ -258,13 +258,13 @@ nsIRDFNode* target, PRBool tv) { - nsresult rv; - nsCOMPtr directory(do_QueryInterface(source, &rv)); - //We don't handle tv = PR_FALSE at the moment. - if(NS_SUCCEEDED(rv) && tv) - return DoDirectoryAssert(directory, property, target); - else - return NS_ERROR_FAILURE; + nsresult rv; + nsCOMPtr directory(do_QueryInterface(source, &rv)); + //We don't handle tv = PR_FALSE at the moment. + if (NS_SUCCEEDED(rv) && tv) + return DoDirectoryAssert(directory, property, target); + else + return NS_ERROR_FAILURE; } NS_IMETHODIMP nsAbDirectoryDataSource::HasAssertion(nsIRDFResource* source, @@ -273,13 +273,13 @@ PRBool tv, PRBool* hasAssertion) { - nsresult rv; - nsCOMPtr directory(do_QueryInterface(source, &rv)); - if(NS_SUCCEEDED(rv)) - return DoDirectoryHasAssertion(directory, property, target, tv, hasAssertion); - else - *hasAssertion = PR_FALSE; - return NS_OK; + nsresult rv; + nsCOMPtr directory(do_QueryInterface(source, &rv)); + if (NS_SUCCEEDED(rv)) + return DoDirectoryHasAssertion(directory, property, target, tv, hasAssertion); + else + *hasAssertion = PR_FALSE; + return NS_OK; } NS_IMETHODIMP @@ -355,7 +355,7 @@ PRUint32 i, cnt; rv = aSources->Count(&cnt); for (i = 0; i < cnt; i++) { - directory = do_QueryElementAt(aSources, i, &rv); + directory = do_QueryElementAt(aSources, i, &rv); if (NS_SUCCEEDED(rv)) { // we don't care about the arguments -- directory commands are always enabled if (!((aCommand == kNC_Delete) || (aCommand == kNC_DeleteCards) @@ -374,17 +374,17 @@ nsIRDFResource* aCommand, nsISupportsArray/**/* aArguments) { - PRUint32 i, cnt; - nsresult rv = aSources->Count(&cnt); - NS_ENSURE_SUCCESS(rv, rv); + PRUint32 i, cnt; + nsresult rv = aSources->Count(&cnt); + NS_ENSURE_SUCCESS(rv, rv); - if (aCommand == kNC_Modify) { + if (aCommand == kNC_Modify) { rv = DoModifyDirectory(aSources,aArguments); } else { - if ((aCommand == kNC_Delete)) - rv = DoDeleteFromDirectory(aSources, aArguments); + if ((aCommand == kNC_Delete)) + rv = DoDeleteFromDirectory(aSources, aArguments); else { for (i = 0; i < cnt; i++) { nsCOMPtr directory = do_QueryElementAt(aSources, i, &rv); @@ -396,31 +396,32 @@ } } } - //for the moment return NS_OK, because failure stops entire DoCommand process. - return NS_OK; + //for the moment return NS_OK, because failure stops entire DoCommand process. + return NS_OK; } NS_IMETHODIMP nsAbDirectoryDataSource::OnItemAdded(nsISupports *parentDirectory, nsISupports *item) { - nsresult rv; - nsCOMPtr directory; - nsCOMPtr parentResource; - - if(NS_SUCCEEDED(parentDirectory->QueryInterface(NS_GET_IID(nsIRDFResource), getter_AddRefs(parentResource)))) - { - //If we are adding a directory - if (NS_SUCCEEDED(item->QueryInterface(NS_GET_IID(nsIAbDirectory), getter_AddRefs(directory)))) - { - nsCOMPtr itemNode(do_QueryInterface(item, &rv)); - if(NS_SUCCEEDED(rv)) - { - //Notify a directory was added. - NotifyObservers(parentResource, kNC_Child, itemNode, PR_TRUE, PR_FALSE); - } - } - } + nsresult rv; + nsCOMPtr directory; + nsCOMPtr parentResource(do_QueryInterface(parentDirectory, &rv)); + + if (NS_SUCCEEDED(rv)) + { + //If we are adding a directory + directory = do_QueryInterface(item, &rv); + if (NS_SUCCEEDED(rv)) + { + nsCOMPtr itemNode(do_QueryInterface(item, &rv)); + if (NS_SUCCEEDED(rv)) + { + //Notify a directory was added. + NotifyObservers(parentResource, kNC_Child, itemNode, PR_TRUE, PR_FALSE); + } + } + } - return NS_OK; + return NS_OK; } nsresult nsAbDirectoryDataSource::DoModifyDirectory(nsISupportsArray *parentDir, nsISupportsArray *arguments) @@ -456,41 +457,42 @@ NS_IMETHODIMP nsAbDirectoryDataSource::OnItemRemoved(nsISupports *parentDirectory, nsISupports *item) { - nsresult rv; - nsCOMPtr directory; - nsCOMPtr parentResource; - - if(NS_SUCCEEDED(parentDirectory->QueryInterface(NS_GET_IID(nsIRDFResource), getter_AddRefs(parentResource)))) - { - //If we are removing a directory - if (NS_SUCCEEDED(item->QueryInterface(NS_GET_IID(nsIAbDirectory), getter_AddRefs(directory)))) - { - nsCOMPtr itemNode(do_QueryInterface(item, &rv)); - if(NS_SUCCEEDED(rv)) - { - //Notify a directory was deleted. - NotifyObservers(parentResource, kNC_Child, itemNode, PR_FALSE, PR_FALSE); - } - } - } - return NS_OK; + nsresult rv; + nsCOMPtr directory; + nsCOMPtr parentResource(do_QueryInterface(parentDirectory, &rv)); + + if (NS_SUCCEEDED(rv)) + { + //If we are removing a directory + item = do_QueryInterface(item, &rv); + if (NS_SUCCEEDED(rv)) + { + nsCOMPtr itemNode(do_QueryInterface(item, &rv)); + if (NS_SUCCEEDED(rv)) + { + //Notify a directory was deleted. + NotifyObservers(parentResource, kNC_Child, itemNode, PR_FALSE, PR_FALSE); + } + } + } + return NS_OK; } NS_IMETHODIMP nsAbDirectoryDataSource::OnItemPropertyChanged(nsISupports *item, const char *property, - const PRUnichar *oldValue, const PRUnichar *newValue) + const PRUnichar *oldValue, const PRUnichar *newValue) { - nsresult rv; - nsCOMPtr resource(do_QueryInterface(item, &rv)); + nsresult rv; + nsCOMPtr resource(do_QueryInterface(item, &rv)); - if(NS_SUCCEEDED(rv)) - { - if(PL_strcmp("DirName", property) == 0) - { - NotifyPropertyChanged(resource, kNC_DirName, oldValue, newValue); - } - } - return NS_OK; + if (NS_SUCCEEDED(rv)) + { + if (PL_strcmp("DirName", property) == 0) + { + NotifyPropertyChanged(resource, kNC_DirName, oldValue, newValue); + } + } + return NS_OK; } nsresult nsAbDirectoryDataSource::createDirectoryNode(nsIAbDirectory* directory, @@ -500,19 +502,19 @@ nsresult rv = NS_RDF_NO_VALUE; if ((kNC_DirName == property)) - rv = createDirectoryNameNode(directory, target); + rv = createDirectoryNameNode(directory, target); else if ((kNC_DirUri == property)) - rv = createDirectoryUriNode(directory, target); + rv = createDirectoryUriNode(directory, target); else if ((kNC_Child == property)) - rv = createDirectoryChildNode(directory, target); + rv = createDirectoryChildNode(directory, target); else if ((kNC_IsMailList == property)) - rv = createDirectoryIsMailListNode(directory, target); + rv = createDirectoryIsMailListNode(directory, target); else if ((kNC_IsRemote == property)) - rv = createDirectoryIsRemoteNode(directory, target); + rv = createDirectoryIsRemoteNode(directory, target); else if ((kNC_IsSecure == property)) - rv = createDirectoryIsSecureNode(directory, target); + rv = createDirectoryIsSecureNode(directory, target); else if ((kNC_IsWriteable == property)) - rv = createDirectoryIsWriteableNode(directory, target); + rv = createDirectoryIsWriteableNode(directory, target); else if ((kNC_DirTreeNameSort == property)) rv = createDirectoryTreeNameSortNode(directory, target); else if ((kNC_SupportsMailingLists == property)) @@ -550,19 +552,19 @@ nsAbDirectoryDataSource::createDirectoryChildNode(nsIAbDirectory *directory, nsIRDFNode **target) { - nsCOMPtr pAddressLists; - directory->GetAddressLists(getter_AddRefs(pAddressLists)); + nsCOMPtr pAddressLists; + directory->GetAddressLists(getter_AddRefs(pAddressLists)); + + if (pAddressLists) + { + PRUint32 total = 0; + pAddressLists->Count(&total); - if (pAddressLists) - { - PRUint32 total = 0; - pAddressLists->Count(&total); - - if (total) - { - PRBool isMailList = PR_FALSE; - directory->GetIsMailList(&isMailList); - if (!isMailList) + if (total) + { + PRBool isMailList = PR_FALSE; + directory->GetIsMailList(&isMailList); + if (!isMailList) { // fetch the last element nsCOMPtr mailList = do_QueryElementAt(pAddressLists, total - 1); @@ -570,7 +572,7 @@ } } // if total } // if pAddressLists - + return (*target ? NS_OK : NS_RDF_NO_VALUE); } @@ -639,7 +641,7 @@ { nsXPIDLString name; nsresult rv = directory->GetDirName(getter_Copies(name)); - NS_ENSURE_SUCCESS(rv, rv); + NS_ENSURE_SUCCESS(rv, rv); /* sort addressbooks in this order - Personal Addressbook, Collected Addresses, MDB, LDAP - * by prefixing address book names with numbers and using the xul sort service. @@ -747,119 +749,119 @@ nsresult nsAbDirectoryDataSource::DoDeleteFromDirectory(nsISupportsArray *parentDirs, nsISupportsArray *delDirs) { - PRUint32 item, itemCount; - nsresult rv = parentDirs->Count(&itemCount); - NS_ENSURE_SUCCESS(rv, rv); - - for (item = 0; item < itemCount; item++) - { - nsCOMPtr parent = do_QueryElementAt(parentDirs, item, &rv); - if (NS_SUCCEEDED(rv)) - { - nsCOMPtr deletedDir(do_QueryElementAt(delDirs, item)); - if(deletedDir) - { - rv = parent->DeleteDirectory(deletedDir); - } - } - } - return rv; + PRUint32 item, itemCount; + nsresult rv = parentDirs->Count(&itemCount); + NS_ENSURE_SUCCESS(rv, rv); + + for (item = 0; item < itemCount; item++) + { + nsCOMPtr parent = do_QueryElementAt(parentDirs, item, &rv); + if (NS_SUCCEEDED(rv)) + { + nsCOMPtr deletedDir(do_QueryElementAt(delDirs, item)); + if (deletedDir) + { + rv = parent->DeleteDirectory(deletedDir); + } + } + } + return rv; } nsresult nsAbDirectoryDataSource::DoDeleteCardsFromDirectory(nsIAbDirectory *directory, nsISupportsArray *arguments) { - nsresult rv = NS_OK; - PRUint32 itemCount; - rv = arguments->Count(&itemCount); - NS_ENSURE_SUCCESS(rv, rv); - - nsCOMPtr cardArray; - NS_NewISupportsArray(getter_AddRefs(cardArray)); - - //Split up deleted items into different type arrays to be passed to the folder - //for deletion. - PRUint32 item; - for(item = 0; item < itemCount; item++) - { + nsresult rv = NS_OK; + PRUint32 itemCount; + rv = arguments->Count(&itemCount); + NS_ENSURE_SUCCESS(rv, rv); + + nsCOMPtr cardArray; + NS_NewISupportsArray(getter_AddRefs(cardArray)); + + //Split up deleted items into different type arrays to be passed to the folder + //for deletion. + PRUint32 item; + for(item = 0; item < itemCount; item++) + { nsCOMPtr deletedCard(do_QueryElementAt(arguments, item)); - if (deletedCard) - { + if (deletedCard) + { rv = cardArray->AppendElement(deletedCard); NS_ENSURE_SUCCESS(rv, rv); - } - } - PRUint32 cnt; - rv = cardArray->Count(&cnt); - NS_ENSURE_SUCCESS(rv, rv); - if (cnt > 0) - rv = directory->DeleteCards(cardArray); - return rv; + } + } + PRUint32 cnt; + rv = cardArray->Count(&cnt); + NS_ENSURE_SUCCESS(rv, rv); + if (cnt > 0) + rv = directory->DeleteCards(cardArray); + return rv; } nsresult nsAbDirectoryDataSource::DoDirectoryAssert(nsIAbDirectory *directory, nsIRDFResource *property, nsIRDFNode *target) { - nsresult rv = NS_ERROR_FAILURE; - return rv; + nsresult rv = NS_ERROR_FAILURE; + return rv; } nsresult nsAbDirectoryDataSource::DoDirectoryHasAssertion(nsIAbDirectory *directory, nsIRDFResource *property, nsIRDFNode *target, - PRBool tv, PRBool *hasAssertion) + PRBool tv, PRBool *hasAssertion) { - nsresult rv = NS_OK; - if (!hasAssertion) - return NS_ERROR_NULL_POINTER; - - //We're not keeping track of negative assertions on directory. - if (!tv) - { - *hasAssertion = PR_FALSE; - return NS_OK; - } + nsresult rv = NS_OK; + if (!hasAssertion) + return NS_ERROR_NULL_POINTER; + + //We're not keeping track of negative assertions on directory. + if (!tv) + { + *hasAssertion = PR_FALSE; + return NS_OK; + } if ((kNC_Child == property)) - { - nsCOMPtr newDirectory(do_QueryInterface(target, &rv)); - if(NS_SUCCEEDED(rv)) - rv = directory->HasDirectory(newDirectory, hasAssertion); - } - else if ((kNC_IsMailList == property) || (kNC_IsRemote == property) || + { + nsCOMPtr newDirectory(do_QueryInterface(target, &rv)); + if (NS_SUCCEEDED(rv)) + rv = directory->HasDirectory(newDirectory, hasAssertion); + } + else if ((kNC_IsMailList == property) || (kNC_IsRemote == property) || (kNC_IsSecure == property) || (kNC_IsWriteable == property) || (kNC_SupportsMailingLists == property)) - { - nsCOMPtr dirResource(do_QueryInterface(directory, &rv)); - NS_ENSURE_SUCCESS(rv, rv); - rv = GetTargetHasAssertion(this, dirResource, property, tv, target, hasAssertion); - } - else - *hasAssertion = PR_FALSE; + { + nsCOMPtr dirResource(do_QueryInterface(directory, &rv)); + NS_ENSURE_SUCCESS(rv, rv); + rv = GetTargetHasAssertion(this, dirResource, property, tv, target, hasAssertion); + } + else + *hasAssertion = PR_FALSE; - return rv; + return rv; } nsresult nsAbDirectoryDataSource::GetTargetHasAssertion(nsIRDFDataSource *dataSource, nsIRDFResource* dirResource, - nsIRDFResource *property,PRBool tv, nsIRDFNode *target,PRBool* hasAssertion) + nsIRDFResource *property,PRBool tv, nsIRDFNode *target,PRBool* hasAssertion) { - nsresult rv; - if(!hasAssertion) - return NS_ERROR_NULL_POINTER; - - nsCOMPtr currentTarget; - - rv = dataSource->GetTarget(dirResource, property,tv, getter_AddRefs(currentTarget)); - if(NS_SUCCEEDED(rv)) - { - nsCOMPtr value1(do_QueryInterface(target)); - nsCOMPtr value2(do_QueryInterface(currentTarget)); - if(value1 && value2) - //If the two values are equal then it has this assertion - *hasAssertion = (value1 == value2); - } - else - rv = NS_NOINTERFACE; + nsresult rv; + if (!hasAssertion) + return NS_ERROR_NULL_POINTER; - return rv; + nsCOMPtr currentTarget; + + rv = dataSource->GetTarget(dirResource, property,tv, getter_AddRefs(currentTarget)); + if (NS_SUCCEEDED(rv)) + { + nsCOMPtr value1(do_QueryInterface(target)); + nsCOMPtr value2(do_QueryInterface(currentTarget)); + if (value1 && value2) + //If the two values are equal then it has this assertion + *hasAssertion = (value1 == value2); + } + else + rv = NS_NOINTERFACE; + + return rv; } Index: mozilla/mailnews/base/search/src/nsMsgFilter.cpp =================================================================== RCS file: /cvsroot/mozilla/mailnews/base/search/src/nsMsgFilter.cpp,v retrieving revision 1.110 diff -u -r1.110 mozilla/mailnews/base/search/src/nsMsgFilter.cpp --- mozilla/mailnews/base/search/src/nsMsgFilter.cpp +++ mozilla/mailnews/base/search/src/nsMsgFilter.cpp @@ -287,8 +287,7 @@ for (PRUint32 index =0; index < numActions; index++) { - nsCOMPtr action; - err = m_actionList->QueryElementAt(index, NS_GET_IID(nsIMsgRuleAction), (void **)getter_AddRefs(action)); + nsCOMPtr action(do_QueryElementAt(m_actionList, index, &err)); if (!action) continue; @@ -366,9 +365,7 @@ char ** arbitraryHeader) /* arbitrary header specified by user.ignore unless attrib = attribOtherHeader */ { nsresult rv; - nsCOMPtr term; - rv = m_termList->QueryElementAt(termIndex, NS_GET_IID(nsIMsgSearchTerm), - (void **)getter_AddRefs(term)); + nsCOMPtr term(do_QueryElementAt(m_termList, termIndex, &rv)); if (NS_SUCCEEDED(rv) && term) { if(attrib) @@ -725,8 +722,7 @@ for (PRUint32 index =0; index < numActions; index++) { - nsCOMPtr action; - err = m_actionList->QueryElementAt(index, NS_GET_IID(nsIMsgRuleAction), (void **)getter_AddRefs(action)); + nsCOMPtr action(do_QueryElementAt(m_actionList, index, &err)); if (!action) continue; @@ -791,13 +787,11 @@ PRUint32 count; m_termList->Count(&count); for (searchIndex = 0; searchIndex < count && NS_SUCCEEDED(err); - searchIndex++) + searchIndex++) { nsCAutoString stream; - nsCOMPtr term; - m_termList->QueryElementAt(searchIndex, NS_GET_IID(nsIMsgSearchTerm), - (void **)getter_AddRefs(term)); + nsCOMPtr term(do_QueryElementAt(m_termList, searchIndex)); if (!term) continue; Index: mozilla/mailnews/base/search/src/nsMsgFilterService.cpp =================================================================== RCS file: /cvsroot/mozilla/mailnews/base/search/src/nsMsgFilterService.cpp,v retrieving revision 1.53 diff -u -r1.53 mozilla/mailnews/base/search/src/nsMsgFilterService.cpp --- mozilla/mailnews/base/search/src/nsMsgFilterService.cpp +++ mozilla/mailnews/base/search/src/nsMsgFilterService.cpp @@ -144,9 +144,9 @@ NS_ENSURE_ARG_POINTER(filterList); nsresult ret = NS_OK; - nsCOMPtr tmpFiltersFile; - nsCOMPtr realFiltersFile; - nsCOMPtr parentDir; + nsCOMPtr tmpFiltersFile; + nsCOMPtr realFiltersFile; + nsCOMPtr parentDir; ret = GetSpecialDirectoryWithFileName(NS_OS_TEMP_DIR, "tmprules.dat", @@ -219,7 +219,7 @@ NS_ENSURE_SUCCESS(rv,rv); nsCOMPtr localParentDir; - nsCOMPtr parentDir; + nsCOMPtr parentDir; rv = aFilterFile->GetParent(getter_AddRefs(parentDir)); NS_ENSURE_SUCCESS(rv,rv); @@ -230,7 +230,7 @@ NS_ENSURE_SUCCESS(rv,rv); //if back-up file exists delete the back up file otherwise copy fails. - nsCOMPtr backupFile; + nsCOMPtr backupFile; rv = NS_FileSpecToIFile(&parentDirSpec, getter_AddRefs(backupFile)); NS_ENSURE_SUCCESS(rv,rv); backupFile->AppendNative(NS_LITERAL_CSTRING("rulesbackup.dat")); @@ -252,7 +252,7 @@ { nsresult rv=NS_OK; NS_ENSURE_ARG_POINTER(aResult); - nsCOMPtr bundle; + nsCOMPtr bundle; rv = GetFilterStringBundle(getter_AddRefs(bundle)); if (NS_SUCCEEDED(rv) && bundle) rv=bundle->GetStringFromName(NS_ConvertASCIItoUTF16(aMsgName).get(), aResult); @@ -282,7 +282,7 @@ nsresult rv = GetStringFromBundle(aMsgName, getter_Copies(alertString)); if (NS_SUCCEEDED(rv) && alertString && aMsgWindow) { - nsCOMPtr docShell; + nsCOMPtr docShell; aMsgWindow->GetRootDocShell(getter_AddRefs(docShell)); if (docShell) { @@ -329,19 +329,19 @@ nsresult OnEndExecution(nsresult executionStatus); // do what we have to do to cleanup. PRBool ContinueExecutionPrompt(); nsresult DisplayConfirmationPrompt(nsIMsgWindow *msgWindow, const PRUnichar *confirmString, PRBool *confirmed); - nsCOMPtr m_msgWindow; - nsCOMPtr m_filters; - nsCOMPtr m_folders; - nsCOMPtr m_curFolder; - nsCOMPtr m_curFolderDB; - nsCOMPtr m_curFilter; - PRUint32 m_curFilterIndex; - PRUint32 m_curFolderIndex; - PRUint32 m_numFilters; - PRUint32 m_numFolders; - nsMsgKeyArray m_searchHits; - nsCOMPtr m_searchHitHdrs; - nsCOMPtr m_searchSession; + nsCOMPtr m_msgWindow; + nsCOMPtr m_filters; + nsCOMPtr m_folders; + nsCOMPtr m_curFolder; + nsCOMPtr m_curFolderDB; + nsCOMPtr m_curFilter; + PRUint32 m_curFilterIndex; + PRUint32 m_curFolderIndex; + PRUint32 m_numFilters; + PRUint32 m_numFolders; + nsMsgKeyArray m_searchHits; + nsCOMPtr m_searchHitHdrs; + nsCOMPtr m_searchSession; }; NS_IMPL_ISUPPORTS3(nsMsgFilterAfterTheFact, nsIUrlListener, nsIMsgSearchNotify, nsIMsgCopyServiceListener) @@ -386,7 +386,7 @@ rv = m_filters->GetFilterAt(m_curFilterIndex++, getter_AddRefs(m_curFilter)); NS_ENSURE_SUCCESS(rv, rv); - nsCOMPtr searchTerms; + nsCOMPtr searchTerms; rv = m_curFilter->GetSearchTerms(getter_AddRefs(searchTerms)); NS_ENSURE_SUCCESS(rv, rv); if (m_searchSession) @@ -399,8 +399,7 @@ searchTerms->Count(&termCount); for (PRUint32 termIndex = 0; termIndex < termCount; termIndex++) { - nsCOMPtr term; - rv = searchTerms->QueryElementAt(termIndex, NS_GET_IID(nsIMsgSearchTerm), getter_AddRefs(term)); + nsCOMPtr term(do_QueryElementAt(searchTerms, termIndex, &rv)); NS_ENSURE_SUCCESS(rv, rv); rv = m_searchSession->AppendTerm(term); NS_ENSURE_SUCCESS(rv, rv); @@ -422,9 +421,10 @@ if (m_curFolderIndex >= m_numFolders) return OnEndExecution(NS_OK); - nsresult rv = m_folders->QueryElementAt(m_curFolderIndex++, NS_GET_IID(nsIMsgFolder), getter_AddRefs(m_curFolder)); + nsresult rv; + m_curFolder = do_QueryElementAt(m_folders, m_curFolderIndex++, &rv); NS_ENSURE_SUCCESS(rv, rv); - nsCOMPtr dbFolderInfo; + nsCOMPtr dbFolderInfo; rv = m_curFolder->GetDBFolderInfoAndDB(getter_AddRefs(dbFolderInfo), getter_AddRefs(m_curFolderDB)); if (rv == NS_MSG_ERROR_FOLDER_SUMMARY_MISSING || rv == NS_MSG_ERROR_FOLDER_SUMMARY_OUT_OF_DATE) { @@ -500,8 +500,7 @@ for (PRUint32 actionIndex =0; actionIndex < numActions && applyMoreActions; actionIndex++) { - nsCOMPtr filterAction; - actionList->QueryElementAt(actionIndex, NS_GET_IID(nsIMsgRuleAction), (void **)getter_AddRefs(filterAction)); + nsCOMPtr filterAction(do_QueryElementAt(actionList, actionIndex)); nsMsgRuleActionType actionType; if (filterAction) filterAction->GetType(&actionType); @@ -524,8 +523,7 @@ { for (PRUint32 msgIndex = 0; msgIndex < m_searchHits.GetSize(); msgIndex++) { - nsCOMPtr msgHdr; - m_searchHitHdrs->QueryElementAt(msgIndex, NS_GET_IID(nsIMsgDBHdr), getter_AddRefs(msgHdr)); + nsCOMPtr msgHdr(do_QueryElementAt(m_searchHitHdrs, msgIndex)); if (msgHdr) (void)m_curFilter->LogRuleHit(filterAction, msgHdr); } @@ -607,11 +605,10 @@ { for (PRUint32 msgIndex = 0; msgIndex < m_searchHits.GetSize(); msgIndex++) { - nsCOMPtr msgHdr; - m_searchHitHdrs->QueryElementAt(msgIndex, NS_GET_IID(nsIMsgDBHdr), getter_AddRefs(msgHdr)); + nsCOMPtr msgHdr(do_QueryElementAt(m_searchHitHdrs, msgIndex)); if (msgHdr) { - nsCOMPtr msgThread; + nsCOMPtr msgThread; nsMsgKey threadKey; m_curFolderDB->GetThreadContainingMsgHdr(msgHdr, getter_AddRefs(msgThread)); if (msgThread) @@ -632,8 +629,7 @@ filterAction->GetPriority(&filterPriority); for (PRUint32 msgIndex = 0; msgIndex < m_searchHits.GetSize(); msgIndex++) { - nsCOMPtr msgHdr; - m_searchHitHdrs->QueryElementAt(msgIndex, NS_GET_IID(nsIMsgDBHdr), getter_AddRefs(msgHdr)); + nsCOMPtr msgHdr(do_QueryElementAt(m_searchHitHdrs, msgIndex)); if (msgHdr) msgHdr->SetPriority(filterPriority); } @@ -666,18 +662,17 @@ { nsXPIDLCString forwardTo; filterAction->GetStrValue(getter_Copies(forwardTo)); - nsCOMPtr server; + nsCOMPtr server; rv = m_curFolder->GetServer(getter_AddRefs(server)); NS_ENSURE_SUCCESS(rv, rv); if (!forwardTo.IsEmpty()) { - nsCOMPtr compService = do_GetService (NS_MSGCOMPOSESERVICE_CONTRACTID) ; + nsCOMPtr compService = do_GetService (NS_MSGCOMPOSESERVICE_CONTRACTID) ; if (compService) { for (PRUint32 msgIndex = 0; msgIndex < m_searchHits.GetSize(); msgIndex++) { - nsCOMPtr msgHdr; - m_searchHitHdrs->QueryElementAt(msgIndex, NS_GET_IID(nsIMsgDBHdr), getter_AddRefs(msgHdr)); + nsCOMPtr msgHdr(do_QueryElementAt(m_searchHitHdrs, msgIndex)); if (msgHdr) { nsAutoString forwardStr; @@ -693,18 +688,17 @@ { nsXPIDLCString replyTemplateUri; filterAction->GetStrValue(getter_Copies(replyTemplateUri)); - nsCOMPtr server; + nsCOMPtr server; rv = m_curFolder->GetServer(getter_AddRefs(server)); NS_ENSURE_SUCCESS(rv, rv); if (!replyTemplateUri.IsEmpty()) { - nsCOMPtr compService = do_GetService (NS_MSGCOMPOSESERVICE_CONTRACTID) ; + nsCOMPtr compService = do_GetService (NS_MSGCOMPOSESERVICE_CONTRACTID) ; if (compService) { for (PRUint32 msgIndex = 0; msgIndex < m_searchHits.GetSize(); msgIndex++) { - nsCOMPtr msgHdr; - m_searchHitHdrs->QueryElementAt(msgIndex, NS_GET_IID(nsIMsgDBHdr), getter_AddRefs(msgHdr)); + nsCOMPtr msgHdr(do_QueryElementAt(m_searchHitHdrs, msgIndex)); if (msgHdr) rv = compService->ReplyWithTemplate(msgHdr, replyTemplateUri, m_msgWindow, server); } @@ -714,19 +708,18 @@ break; case nsMsgFilterAction::DeleteFromPop3Server: { - nsCOMPtr localFolder = do_QueryInterface(m_curFolder); + nsCOMPtr localFolder = do_QueryInterface(m_curFolder); if (localFolder) { // This action ignores the deleteMailLeftOnServer preference localFolder->MarkMsgsOnPop3Server(m_searchHitHdrs, POP3_FORCE_DEL); - nsCOMPtr partialMsgs; + nsCOMPtr partialMsgs; // Delete the partial headers. They're useless now // that the server copy is being deleted. for (PRUint32 msgIndex = 0; msgIndex < m_searchHits.GetSize(); msgIndex++) { - nsCOMPtr msgHdr; - m_searchHitHdrs->QueryElementAt(msgIndex, NS_GET_IID(nsIMsgDBHdr), getter_AddRefs(msgHdr)); + nsCOMPtr msgHdr(do_QueryElementAt(m_searchHitHdrs, msgIndex)); if (msgHdr) { PRUint32 flags; @@ -747,15 +740,14 @@ break; case nsMsgFilterAction::FetchBodyFromPop3Server: { - nsCOMPtr localFolder = do_QueryInterface(m_curFolder); + nsCOMPtr localFolder = do_QueryInterface(m_curFolder); if (localFolder) { nsCOMPtr messages = do_CreateInstance(NS_SUPPORTSARRAY_CONTRACTID, &rv); NS_ENSURE_SUCCESS(rv, rv); for (PRUint32 msgIndex = 0; msgIndex < m_searchHits.GetSize(); msgIndex++) { - nsCOMPtr msgHdr; - m_searchHitHdrs->QueryElementAt(msgIndex, NS_GET_IID(nsIMsgDBHdr), getter_AddRefs(msgHdr)); + nsCOMPtr msgHdr(do_QueryElementAt(m_searchHitHdrs, msgIndex)); if (msgHdr) { PRUint32 flags = 0; @@ -839,7 +831,7 @@ { PRBool returnVal = PR_FALSE; nsresult rv; - nsCOMPtr bundle; + nsCOMPtr bundle; nsCOMPtr bundleService = do_GetService(NS_STRINGBUNDLE_CONTRACTID, &rv); if (bundleService && NS_SUCCEEDED(rv)) bundleService->CreateBundle("chrome://messenger/locale/filter.properties", @@ -869,7 +861,7 @@ nsresult rv=NS_OK; if (msgWindow) { - nsCOMPtr docShell; + nsCOMPtr docShell; msgWindow->GetRootDocShell(getter_AddRefs(docShell)); if (docShell) { Index: mozilla/mailnews/base/search/src/nsMsgImapSearch.cpp =================================================================== RCS file: /cvsroot/mozilla/mailnews/base/search/src/nsMsgImapSearch.cpp,v retrieving revision 1.47 diff -u -r1.47 mozilla/mailnews/base/search/src/nsMsgImapSearch.cpp --- mozilla/mailnews/base/search/src/nsMsgImapSearch.cpp +++ mozilla/mailnews/base/search/src/nsMsgImapSearch.cpp @@ -90,7 +90,7 @@ m_scope->GetSearchSession(getter_AddRefs(searchSession)); if (searchSession) { - nsCOMPtr scopeFolder; + nsCOMPtr scopeFolder; err = m_scope->GetFolder(getter_AddRefs(scopeFolder)); searchSession->AddSearchHit(pHeaders, scopeFolder); } @@ -125,16 +125,14 @@ for (i = 0; i < termCount && asciiOnly; i++) { - nsCOMPtr pTerm; - searchTerms->QueryElementAt(i, NS_GET_IID(nsIMsgSearchTerm), - (void **)getter_AddRefs(pTerm)); + nsCOMPtr pTerm(do_QueryElementAt(searchTerms, i)); nsMsgSearchAttribValue attribute; pTerm->GetAttrib(&attribute); if (IsStringAttribute(attribute)) { nsXPIDLString pchar; - nsCOMPtr searchValue; + nsCOMPtr searchValue; nsresult rv = pTerm->GetValue(getter_AddRefs(searchValue)); if (NS_FAILED(rv) || !searchValue) Index: mozilla/mailnews/base/search/src/nsMsgLocalSearch.cpp =================================================================== RCS file: /cvsroot/mozilla/mailnews/base/search/src/nsMsgLocalSearch.cpp,v retrieving revision 1.77 diff -u -r1.77 mozilla/mailnews/base/search/src/nsMsgLocalSearch.cpp --- mozilla/mailnews/base/search/src/nsMsgLocalSearch.cpp +++ mozilla/mailnews/base/search/src/nsMsgLocalSearch.cpp @@ -375,8 +375,7 @@ while (aStartPosInList < termCount) { - nsCOMPtr pTerm; - termList->QueryElementAt(aStartPosInList, NS_GET_IID(nsIMsgSearchTerm), (void **)getter_AddRefs(pTerm)); + nsCOMPtr pTerm(do_QueryElementAt(termList, aStartPosInList)); NS_ASSERTION (pTerm, "couldn't get term to match"); PRBool beginsGrouping; Index: mozilla/mailnews/base/search/src/nsMsgSearchAdapter.cpp =================================================================== RCS file: /cvsroot/mozilla/mailnews/base/search/src/nsMsgSearchAdapter.cpp,v retrieving revision 1.86 diff -u -r1.86 mozilla/mailnews/base/search/src/nsMsgSearchAdapter.cpp --- mozilla/mailnews/base/search/src/nsMsgSearchAdapter.cpp +++ mozilla/mailnews/base/search/src/nsMsgSearchAdapter.cpp @@ -1,4 +1,4 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * @@ -60,7 +60,7 @@ // km - the NOT and HEADER strings are not encoded with a trailing // because they always precede a mnemonic that has a // preceding and double characters cause some -// imap servers to return an error. +// imap servers to return an error. const char *nsMsgSearchAdapter::m_kImapBefore = " SENTBEFORE "; const char *nsMsgSearchAdapter::m_kImapBody = " BODY "; const char *nsMsgSearchAdapter::m_kImapCC = " CC "; @@ -92,23 +92,23 @@ NS_IMETHODIMP nsMsgSearchAdapter::FindTargetFolder(const nsMsgResultElement *,nsIMsgFolder * *) { - return NS_ERROR_NOT_IMPLEMENTED; + return NS_ERROR_NOT_IMPLEMENTED; } NS_IMETHODIMP nsMsgSearchAdapter::ModifyResultElement(nsMsgResultElement *, nsMsgSearchValue *) { - return NS_ERROR_NOT_IMPLEMENTED; + return NS_ERROR_NOT_IMPLEMENTED; } NS_IMETHODIMP nsMsgSearchAdapter::OpenResultElement(nsMsgResultElement *) { - return NS_ERROR_NOT_IMPLEMENTED; + return NS_ERROR_NOT_IMPLEMENTED; } NS_IMPL_ISUPPORTS1(nsMsgSearchAdapter, nsIMsgSearchAdapter) nsMsgSearchAdapter::nsMsgSearchAdapter(nsIMsgSearchScopeTerm *scope, nsISupportsArray *searchTerms) - : m_searchTerms(searchTerms) + : m_searchTerms(searchTerms) { m_scope = scope; } @@ -120,12 +120,12 @@ NS_IMETHODIMP nsMsgSearchAdapter::ValidateTerms () { // all this used to do is check if the object had been deleted - we can skip that. - return NS_OK; + return NS_OK; } NS_IMETHODIMP nsMsgSearchAdapter::Abort () { - return NS_ERROR_NOT_IMPLEMENTED; + return NS_ERROR_NOT_IMPLEMENTED; } NS_IMETHODIMP nsMsgSearchAdapter::Search (PRBool *aDone) @@ -152,8 +152,8 @@ NS_IMETHODIMP nsMsgSearchAdapter::AddResultElement (nsIMsgDBHdr *pHeaders) { - NS_ASSERTION(PR_FALSE, "shouldn't call this base class impl"); - return NS_ERROR_FAILURE; + NS_ASSERTION(PR_FALSE, "shouldn't call this base class impl"); + return NS_ERROR_FAILURE; } @@ -167,13 +167,13 @@ char * nsMsgSearchAdapter::GetImapCharsetParam(const PRUnichar *destCharset) { - char *result = nsnull; + char *result = nsnull; - // Specify a character set unless we happen to be US-ASCII. + // Specify a character set unless we happen to be US-ASCII. if (nsCRT::strcmp(destCharset, NS_LITERAL_STRING("us-ascii").get())) - result = PR_smprintf("%s%s", nsMsgSearchAdapter::m_kImapCharset, NS_ConvertUTF16toUTF8(destCharset).get()); + result = PR_smprintf("%s%s", nsMsgSearchAdapter::m_kImapCharset, NS_ConvertUTF16toUTF8(destCharset).get()); - return result; + return result; } /* @@ -184,35 +184,35 @@ */ PRUnichar *nsMsgSearchAdapter::EscapeSearchUrl (const PRUnichar *nntpCommand) { - return nsCRT::strdup(nntpCommand); + return nsCRT::strdup(nntpCommand); #if 0 - PRUnichar *result = nsnull; - // max escaped length is two extra characters for every character in the cmd. + PRUnichar *result = nsnull; + // max escaped length is two extra characters for every character in the cmd. PRUnichar *scratchBuf = (PRUnichar*) PR_Malloc(sizeof(PRUnichar) * (3*nsCRT::strlen(nntpCommand) + 1)); - if (scratchBuf) - { - PRUnichar *scratchPtr = scratchBuf; - while (PR_TRUE) - { - PRUnichar ch = *nntpCommand++; - if (!ch) - break; - if (ch == '#' || ch == '?' || ch == '@' || ch == '\\') - { - *scratchPtr++ = '\\'; - nsTextFormatter::snprintf(scratchPtr, 2, - NS_LITERAL_STRING("%2.2X").get(), ch); - /* Reviewed 4.51 safe use of sprintf */ - scratchPtr += 2; - } - else - *scratchPtr++ = ch; - } - *scratchPtr = '\0'; - result = nsCRT::strdup (scratchBuf); // realloc down to smaller size - nsCRT::free (scratchBuf); - } - return result; + if (scratchBuf) + { + PRUnichar *scratchPtr = scratchBuf; + while (PR_TRUE) + { + PRUnichar ch = *nntpCommand++; + if (!ch) + break; + if (ch == '#' || ch == '?' || ch == '@' || ch == '\\') + { + *scratchPtr++ = '\\'; + nsTextFormatter::snprintf(scratchPtr, 2, + NS_LITERAL_STRING("%2.2X").get(), ch); + /* Reviewed 4.51 safe use of sprintf */ + scratchPtr += 2; + } + else + *scratchPtr++ = ch; + } + *scratchPtr = '\0'; + result = nsCRT::strdup (scratchBuf); // realloc down to smaller size + nsCRT::free (scratchBuf); + } + return result; #endif } @@ -225,33 +225,33 @@ PRUnichar * nsMsgSearchAdapter::EscapeImapSearchProtocol(const PRUnichar *imapCommand) { - return nsCRT::strdup(imapCommand); + return nsCRT::strdup(imapCommand); #if 0 - PRUnichar *result = nsnull; - // max escaped length is one extra character for every character in the cmd. - PRUnichar *scratchBuf = - (PRUnichar*) PR_Malloc (sizeof(PRUnichar) * (2*nsCRT::strlen(imapCommand) + 1)); - if (scratchBuf) - { - PRUnichar *scratchPtr = scratchBuf; - while (1) - { - PRUnichar ch = *imapCommand++; - if (!ch) - break; - if (ch == (PRUnichar)'\\') - { - *scratchPtr++ = (PRUnichar)'\\'; - *scratchPtr++ = (PRUnichar)'\\'; - } - else - *scratchPtr++ = ch; - } - *scratchPtr = 0; - result = nsCRT::strdup (scratchBuf); // realloc down to smaller size - nsCRT::free (scratchBuf); - } - return result; + PRUnichar *result = nsnull; + // max escaped length is one extra character for every character in the cmd. + PRUnichar *scratchBuf = + (PRUnichar*) PR_Malloc (sizeof(PRUnichar) * (2*nsCRT::strlen(imapCommand) + 1)); + if (scratchBuf) + { + PRUnichar *scratchPtr = scratchBuf; + while (1) + { + PRUnichar ch = *imapCommand++; + if (!ch) + break; + if (ch == (PRUnichar)'\\') + { + *scratchPtr++ = (PRUnichar)'\\'; + *scratchPtr++ = (PRUnichar)'\\'; + } + else + *scratchPtr++ = ch; + } + *scratchPtr = 0; + result = nsCRT::strdup (scratchBuf); // realloc down to smaller size + nsCRT::free (scratchBuf); + } + return result; #endif } @@ -264,33 +264,33 @@ PRUnichar * nsMsgSearchAdapter::EscapeQuoteImapSearchProtocol(const PRUnichar *imapCommand) { - return nsCRT::strdup(imapCommand); + return nsCRT::strdup(imapCommand); #if 0 - PRUnichar *result = nsnull; - // max escaped length is one extra character for every character in the cmd. - PRUnichar *scratchBuf = - (PRUnichar*) PR_Malloc (sizeof(PRUnichar) * (2*nsCRT::strlen(imapCommand) + 1)); - if (scratchBuf) - { - PRUnichar *scratchPtr = scratchBuf; - while (1) - { - PRUnichar ch = *imapCommand++; - if (!ch) - break; - if (ch == '"') - { - *scratchPtr++ = '\\'; - *scratchPtr++ = '"'; - } - else - *scratchPtr++ = ch; - } - *scratchPtr = '\0'; + PRUnichar *result = nsnull; + // max escaped length is one extra character for every character in the cmd. + PRUnichar *scratchBuf = + (PRUnichar*) PR_Malloc (sizeof(PRUnichar) * (2*nsCRT::strlen(imapCommand) + 1)); + if (scratchBuf) + { + PRUnichar *scratchPtr = scratchBuf; + while (1) + { + PRUnichar ch = *imapCommand++; + if (!ch) + break; + if (ch == '"') + { + *scratchPtr++ = '\\'; + *scratchPtr++ = '"'; + } + else + *scratchPtr++ = ch; + } + *scratchPtr = '\0'; result = nsCRT::strdup (scratchBuf); // realloc down to smaller size nsCRT::free (scratchBuf); - } - return result; + } + return result; #endif } @@ -298,30 +298,30 @@ char *nsMsgSearchAdapter::UnEscapeSearchUrl (const char *commandSpecificData) { char *result = (char*) PR_Malloc (strlen(commandSpecificData) + 1); - if (result) - { - char *resultPtr = result; - while (1) - { - char ch = *commandSpecificData++; - if (!ch) - break; - if (ch == '\\') - { - char scratchBuf[3]; - scratchBuf[0] = (char) *commandSpecificData++; - scratchBuf[1] = (char) *commandSpecificData++; - scratchBuf[2] = '\0'; - unsigned int accum = 0; - sscanf (scratchBuf, "%X", &accum); - *resultPtr++ = (char) accum; - } - else - *resultPtr++ = ch; - } - *resultPtr = '\0'; - } - return result; + if (result) + { + char *resultPtr = result; + while (1) + { + char ch = *commandSpecificData++; + if (!ch) + break; + if (ch == '\\') + { + char scratchBuf[3]; + scratchBuf[0] = (char) *commandSpecificData++; + scratchBuf[1] = (char) *commandSpecificData++; + scratchBuf[2] = '\0'; + unsigned int accum = 0; + sscanf (scratchBuf, "%X", &accum); + *resultPtr++ = (char) accum; + } + else + *resultPtr++ = ch; + } + *resultPtr = '\0'; + } + return result; } @@ -478,263 +478,263 @@ return NS_ERROR_INVALID_ARG; } break; - case nsMsgSearchAttrib::Date: - switch (op) - { - case nsMsgSearchOp::IsBefore: - whichMnemonic = m_kImapBefore; - break; - case nsMsgSearchOp::IsAfter: - whichMnemonic = m_kImapSince; - break; - case nsMsgSearchOp::Isnt: /* we've already added the "Not" so just process it like it was a date is search */ - case nsMsgSearchOp::Is: - whichMnemonic = m_kImapSentOn; - break; - default: - NS_ASSERTION(PR_FALSE, "invalid search operator"); - return NS_ERROR_INVALID_ARG; - } + case nsMsgSearchAttrib::Date: + switch (op) + { + case nsMsgSearchOp::IsBefore: + whichMnemonic = m_kImapBefore; break; - case nsMsgSearchAttrib::AnyText: - whichMnemonic = m_kImapAnyText; + case nsMsgSearchOp::IsAfter: + whichMnemonic = m_kImapSince; break; - case nsMsgSearchAttrib::Keywords: - whichMnemonic = m_kImapKeyword; + case nsMsgSearchOp::Isnt: /* we've already added the "Not" so just process it like it was a date is search */ + case nsMsgSearchOp::Is: + whichMnemonic = m_kImapSentOn; break; - case nsMsgSearchAttrib::MsgStatus: - useNot = PR_FALSE; // bizarrely, NOT SEEN is wrong, but UNSEEN is right. - ignoreValue = PR_TRUE; // the mnemonic is all we need - PRUint32 status; - searchValue->GetStatus(&status); + default: + NS_ASSERTION(PR_FALSE, "invalid search operator"); + return NS_ERROR_INVALID_ARG; + } + break; + case nsMsgSearchAttrib::AnyText: + whichMnemonic = m_kImapAnyText; + break; + case nsMsgSearchAttrib::Keywords: + whichMnemonic = m_kImapKeyword; + break; + case nsMsgSearchAttrib::MsgStatus: + useNot = PR_FALSE; // bizarrely, NOT SEEN is wrong, but UNSEEN is right. + ignoreValue = PR_TRUE; // the mnemonic is all we need + PRUint32 status; + searchValue->GetStatus(&status); - switch (status) - { - case MSG_FLAG_READ: - whichMnemonic = op == nsMsgSearchOp::Is ? m_kImapSeen : m_kImapNotSeen; - break; - case MSG_FLAG_REPLIED: - whichMnemonic = op == nsMsgSearchOp::Is ? m_kImapAnswered : m_kImapNotAnswered; - break; - case MSG_FLAG_NEW: - whichMnemonic = op == nsMsgSearchOp::Is ? m_kImapNew : m_kImapNotNew; - break; - case MSG_FLAG_MARKED: - whichMnemonic = op == nsMsgSearchOp::Is ? m_kImapFlagged : m_kImapNotFlagged; - break; - default: - NS_ASSERTION(PR_FALSE, "invalid search operator"); - return NS_ERROR_INVALID_ARG; - } + switch (status) + { + case MSG_FLAG_READ: + whichMnemonic = op == nsMsgSearchOp::Is ? m_kImapSeen : m_kImapNotSeen; + break; + case MSG_FLAG_REPLIED: + whichMnemonic = op == nsMsgSearchOp::Is ? m_kImapAnswered : m_kImapNotAnswered; + break; + case MSG_FLAG_NEW: + whichMnemonic = op == nsMsgSearchOp::Is ? m_kImapNew : m_kImapNotNew; + break; + case MSG_FLAG_MARKED: + whichMnemonic = op == nsMsgSearchOp::Is ? m_kImapFlagged : m_kImapNotFlagged; break; default: - if ( attrib > nsMsgSearchAttrib::OtherHeader && attrib < nsMsgSearchAttrib::kNumMsgSearchAttributes) + NS_ASSERTION(PR_FALSE, "invalid search operator"); + return NS_ERROR_INVALID_ARG; + } + break; + default: + if ( attrib > nsMsgSearchAttrib::OtherHeader && attrib < nsMsgSearchAttrib::kNumMsgSearchAttributes) + { + nsXPIDLCString arbitraryHeaderTerm; + term->GetArbitraryHeader(getter_Copies(arbitraryHeaderTerm)); + if (!arbitraryHeaderTerm.IsEmpty()) { - nsXPIDLCString arbitraryHeaderTerm; - term->GetArbitraryHeader(getter_Copies(arbitraryHeaderTerm)); - if (!arbitraryHeaderTerm.IsEmpty()) - { - arbitraryHeader.AssignLiteral(" \""); - arbitraryHeader.Append(arbitraryHeaderTerm); - arbitraryHeader.AppendLiteral("\" "); - whichMnemonic = arbitraryHeader.get(); - } - else - return NS_ERROR_FAILURE; + arbitraryHeader.AssignLiteral(" \""); + arbitraryHeader.Append(arbitraryHeaderTerm); + arbitraryHeader.AppendLiteral("\" "); + whichMnemonic = arbitraryHeader.get(); } else - { - NS_ASSERTION(PR_FALSE, "invalid search operator"); - return NS_ERROR_INVALID_ARG; - } + return NS_ERROR_FAILURE; + } + else + { + NS_ASSERTION(PR_FALSE, "invalid search operator"); + return NS_ERROR_INVALID_ARG; } + } - char *value = nsnull; - char dateBuf[100]; - dateBuf[0] = '\0'; - - PRBool valueWasAllocated = PR_FALSE; - if (attrib == nsMsgSearchAttrib::Date) - { - // note that there used to be code here that encoded an RFC822 date for imap searches. - // The IMAP RFC 2060 is misleading to the point that it looks like it requires an RFC822 - // date but really it expects dd-mmm-yyyy, like dredd, and refers to the RFC822 date only in that the - // dd-mmm-yyyy date will match the RFC822 date within the message. - - PRTime adjustedDate; - searchValue->GetDate(&adjustedDate); - if (whichMnemonic == m_kImapSince) - { - // it looks like the IMAP server searches on Since includes the date in question... - // our UI presents Is, IsGreater and IsLessThan. For the IsGreater case (m_kImapSince) - // we need to adjust the date so we get greater than and not greater than or equal to which - // is what the IMAP server wants to search on - // won't work on Mac. - // ack, is this right? is PRTime seconds or microseconds? - PRInt64 microSecondsPerSecond, secondsInDay, microSecondsInDay; - - LL_I2L(microSecondsPerSecond, PR_USEC_PER_SEC); - LL_UI2L(secondsInDay, 60 * 60 * 24); - LL_MUL(microSecondsInDay, secondsInDay, microSecondsPerSecond); - LL_ADD(adjustedDate, adjustedDate, microSecondsInDay); // bump up to the day after this one... - } + char *value = nsnull; + char dateBuf[100]; + dateBuf[0] = '\0'; + + PRBool valueWasAllocated = PR_FALSE; + if (attrib == nsMsgSearchAttrib::Date) + { + // note that there used to be code here that encoded an RFC822 date for imap searches. + // The IMAP RFC 2060 is misleading to the point that it looks like it requires an RFC822 + // date but really it expects dd-mmm-yyyy, like dredd, and refers to the RFC822 date only in that the + // dd-mmm-yyyy date will match the RFC822 date within the message. + + PRTime adjustedDate; + searchValue->GetDate(&adjustedDate); + if (whichMnemonic == m_kImapSince) + { + // it looks like the IMAP server searches on Since includes the date in question... + // our UI presents Is, IsGreater and IsLessThan. For the IsGreater case (m_kImapSince) + // we need to adjust the date so we get greater than and not greater than or equal to which + // is what the IMAP server wants to search on + // won't work on Mac. + // ack, is this right? is PRTime seconds or microseconds? + PRInt64 microSecondsPerSecond, secondsInDay, microSecondsInDay; + + LL_I2L(microSecondsPerSecond, PR_USEC_PER_SEC); + LL_UI2L(secondsInDay, 60 * 60 * 24); + LL_MUL(microSecondsInDay, secondsInDay, microSecondsPerSecond); + LL_ADD(adjustedDate, adjustedDate, microSecondsInDay); // bump up to the day after this one... + } + + PRExplodedTime exploded; + PR_ExplodeTime(adjustedDate, PR_LocalTimeParameters, &exploded); + PR_FormatTimeUSEnglish(dateBuf, sizeof(dateBuf), "%d-%b-%Y", &exploded); + // strftime (dateBuf, sizeof(dateBuf), "%d-%b-%Y", localtime (/* &term->m_value.u.date */ &adjustedDate)); + value = dateBuf; + } + else + { + if (attrib == nsMsgSearchAttrib::AgeInDays) + { + // okay, take the current date, subtract off the age in days, then do an appropriate Date search on + // the resulting day. + PRUint32 ageInDays; + + searchValue->GetAge(&ageInDays); + + PRTime now = PR_Now(); + PRTime matchDay; + + PRInt64 microSecondsPerSecond, secondsInDays, microSecondsInDay; + LL_I2L(microSecondsPerSecond, PR_USEC_PER_SEC); + LL_UI2L(secondsInDays, 60 * 60 * 24 * ageInDays); + LL_MUL(microSecondsInDay, secondsInDays, microSecondsPerSecond); + + LL_SUB(matchDay, now, microSecondsInDay); // = now - term->m_value.u.age * 60 * 60 * 24; PRExplodedTime exploded; - PR_ExplodeTime(adjustedDate, PR_LocalTimeParameters, &exploded); + PR_ExplodeTime(matchDay, PR_LocalTimeParameters, &exploded); PR_FormatTimeUSEnglish(dateBuf, sizeof(dateBuf), "%d-%b-%Y", &exploded); - // strftime (dateBuf, sizeof(dateBuf), "%d-%b-%Y", localtime (/* &term->m_value.u.date */ &adjustedDate)); + // strftime (dateBuf, sizeof(dateBuf), "%d-%b-%Y", localtime (&matchDay)); value = dateBuf; } - else + else if (attrib == nsMsgSearchAttrib::Size) { - if (attrib == nsMsgSearchAttrib::AgeInDays) - { - // okay, take the current date, subtract off the age in days, then do an appropriate Date search on - // the resulting day. - PRUint32 ageInDays; - - searchValue->GetAge(&ageInDays); - - PRTime now = PR_Now(); - PRTime matchDay; - - PRInt64 microSecondsPerSecond, secondsInDays, microSecondsInDay; - - LL_I2L(microSecondsPerSecond, PR_USEC_PER_SEC); - LL_UI2L(secondsInDays, 60 * 60 * 24 * ageInDays); - LL_MUL(microSecondsInDay, secondsInDays, microSecondsPerSecond); - - LL_SUB(matchDay, now, microSecondsInDay); // = now - term->m_value.u.age * 60 * 60 * 24; - PRExplodedTime exploded; - PR_ExplodeTime(matchDay, PR_LocalTimeParameters, &exploded); - PR_FormatTimeUSEnglish(dateBuf, sizeof(dateBuf), "%d-%b-%Y", &exploded); - // strftime (dateBuf, sizeof(dateBuf), "%d-%b-%Y", localtime (&matchDay)); - value = dateBuf; - } - else if (attrib == nsMsgSearchAttrib::Size) - { - PRUint32 sizeValue; - nsCAutoString searchTermValue; - searchValue->GetSize(&sizeValue); - - // Multiply by 1024 to get into kb resolution - sizeValue *= 1024; - - // Ensure that greater than is really greater than - // in kb resolution. - if (op == nsMsgSearchOp::IsGreaterThan) - sizeValue += 1024; + PRUint32 sizeValue; + nsCAutoString searchTermValue; + searchValue->GetSize(&sizeValue); + + // Multiply by 1024 to get into kb resolution + sizeValue *= 1024; + + // Ensure that greater than is really greater than + // in kb resolution. + if (op == nsMsgSearchOp::IsGreaterThan) + sizeValue += 1024; - searchTermValue.AppendInt(sizeValue); + searchTermValue.AppendInt(sizeValue); - value = nsCRT::strdup(searchTermValue.get()); - valueWasAllocated = PR_TRUE; - } - else - - if (IsStringAttribute(attrib)) - { - PRUnichar *convertedValue; // = reallyDredd ? MSG_EscapeSearchUrl (term->m_value.u.string) : msg_EscapeImapSearchProtocol(term->m_value.u.string); - nsXPIDLString searchTermValue; - searchValue->GetStr(getter_Copies(searchTermValue)); - // Ugly switch for Korean mail/news charsets. - // We want to do this here because here is where - // we know what charset we want to use. + value = nsCRT::strdup(searchTermValue.get()); + valueWasAllocated = PR_TRUE; + } + else + + if (IsStringAttribute(attrib)) + { + PRUnichar *convertedValue; // = reallyDredd ? MSG_EscapeSearchUrl (term->m_value.u.string) : msg_EscapeImapSearchProtocol(term->m_value.u.string); + nsXPIDLString searchTermValue; + searchValue->GetStr(getter_Copies(searchTermValue)); + // Ugly switch for Korean mail/news charsets. + // We want to do this here because here is where + // we know what charset we want to use. #ifdef DOING_CHARSET - if (reallyDredd) - dest_csid = INTL_DefaultNewsCharSetID(dest_csid); - else - dest_csid = INTL_DefaultMailCharSetID(dest_csid); + if (reallyDredd) + dest_csid = INTL_DefaultNewsCharSetID(dest_csid); + else + dest_csid = INTL_DefaultMailCharSetID(dest_csid); #endif - // do all sorts of crazy escaping - convertedValue = reallyDredd ? EscapeSearchUrl (searchTermValue) : - EscapeImapSearchProtocol(searchTermValue); - useQuotes = ((!reallyDredd || - (nsDependentString(convertedValue).FindChar(PRUnichar(' ')) != -1)) && - (attrib != nsMsgSearchAttrib::Keywords)); - // now convert to char* and escape quoted_specials - nsCAutoString valueStr; - nsresult rv = ConvertFromUnicode(NS_LossyConvertUTF16toASCII(destCharset).get(), - nsDependentString(convertedValue), valueStr); - if (NS_SUCCEEDED(rv)) + // do all sorts of crazy escaping + convertedValue = reallyDredd ? EscapeSearchUrl (searchTermValue) : + EscapeImapSearchProtocol(searchTermValue); + useQuotes = ((!reallyDredd || + (nsDependentString(convertedValue).FindChar(PRUnichar(' ')) != -1)) && + (attrib != nsMsgSearchAttrib::Keywords)); + // now convert to char* and escape quoted_specials + nsCAutoString valueStr; + nsresult rv = ConvertFromUnicode(NS_LossyConvertUTF16toASCII(destCharset).get(), + nsDependentString(convertedValue), valueStr); + if (NS_SUCCEEDED(rv)) + { + const char *vptr = valueStr.get(); + // max escaped length is one extra character for every character in the cmd. + nsAutoArrayPtr newValue(new char[2*strlen(vptr) + 1]); + if (newValue) { - const char *vptr = valueStr.get(); - // max escaped length is one extra character for every character in the cmd. - nsAutoArrayPtr newValue(new char[2*strlen(vptr) + 1]); - if (newValue) + char *p = newValue; + while (1) { - char *p = newValue; - while (1) - { - char ch = *vptr++; - if (!ch) - break; - if ((useQuotes ? ch == '"' : 0) || ch == '\\') - *p++ = '\\'; - *p++ = ch; - } - *p = '\0'; - value = nsCRT::strdup(newValue); // realloc down to smaller size + char ch = *vptr++; + if (!ch) + break; + if ((useQuotes ? ch == '"' : 0) || ch == '\\') + *p++ = '\\'; + *p++ = ch; } + *p = '\0'; + value = nsCRT::strdup(newValue); // realloc down to smaller size } - else - value = nsCRT::strdup(""); - nsCRT::free(convertedValue); - valueWasAllocated = PR_TRUE; - } - } + else + value = nsCRT::strdup(""); + nsCRT::free(convertedValue); + valueWasAllocated = PR_TRUE; - // this should be rewritten to use nsCString - int subLen = - (value ? strlen(value) : 0) + - (useNot ? strlen(m_kImapNot) : 0) + - strlen(m_kImapHeader); - int len = strlen(whichMnemonic) + subLen + (useQuotes ? 2 : 0) + - (orHeaderMnemonic - ? (subLen + strlen(m_kImapOr) + strlen(orHeaderMnemonic) + 2 /*""*/) - : 0) + - 10; // add slough for imap string literals - char *encoding = new char[len]; - if (encoding) - { - encoding[0] = '\0'; - // Remember: if ToOrCC and useNot then the expression becomes NOT To AND Not CC as opposed to (NOT TO) || (NOT CC) - if (orHeaderMnemonic && !useNot) - PL_strcat(encoding, m_kImapOr); - if (useNot) - PL_strcat (encoding, m_kImapNot); - if (!arbitraryHeader.IsEmpty()) - PL_strcat (encoding, m_kImapHeader); - PL_strcat (encoding, whichMnemonic); - if (!ignoreValue) - err = EncodeImapValue(encoding, value, useQuotes, reallyDredd); + } + } - if (orHeaderMnemonic) - { - if (useNot) - PL_strcat(encoding, m_kImapNot); + // this should be rewritten to use nsCString + int subLen = + (value ? strlen(value) : 0) + + (useNot ? strlen(m_kImapNot) : 0) + + strlen(m_kImapHeader); + int len = strlen(whichMnemonic) + subLen + (useQuotes ? 2 : 0) + + (orHeaderMnemonic + ? (subLen + strlen(m_kImapOr) + strlen(orHeaderMnemonic) + 2 /*""*/) + : 0) + + 10; // add slough for imap string literals + char *encoding = new char[len]; + if (encoding) + { + encoding[0] = '\0'; + // Remember: if ToOrCC and useNot then the expression becomes NOT To AND Not CC as opposed to (NOT TO) || (NOT CC) + if (orHeaderMnemonic && !useNot) + PL_strcat(encoding, m_kImapOr); + if (useNot) + PL_strcat (encoding, m_kImapNot); + if (!arbitraryHeader.IsEmpty()) + PL_strcat (encoding, m_kImapHeader); + PL_strcat (encoding, whichMnemonic); + if (!ignoreValue) + err = EncodeImapValue(encoding, value, useQuotes, reallyDredd); - PL_strcat (encoding, m_kImapHeader); + if (orHeaderMnemonic) + { + if (useNot) + PL_strcat(encoding, m_kImapNot); - PL_strcat (encoding, orHeaderMnemonic); - if (!ignoreValue) - err = EncodeImapValue(encoding, value, useQuotes, reallyDredd); - } + PL_strcat (encoding, m_kImapHeader); - // kmcentee, don't let the encoding end with whitespace, - // this throws off later url STRCMP - if (*encoding && *(encoding + strlen(encoding) - 1) == ' ') - *(encoding + strlen(encoding) - 1) = '\0'; + PL_strcat (encoding, orHeaderMnemonic); + if (!ignoreValue) + err = EncodeImapValue(encoding, value, useQuotes, reallyDredd); } - if (value && valueWasAllocated) - nsCRT::free (value); + // kmcentee, don't let the encoding end with whitespace, + // this throws off later url STRCMP + if (*encoding && *(encoding + strlen(encoding) - 1) == ' ') + *(encoding + strlen(encoding) - 1) = '\0'; + } + + if (value && valueWasAllocated) + nsCRT::free (value); - *ppOutTerm = encoding; + *ppOutTerm = encoding; - return err; + return err; } nsresult nsMsgSearchAdapter::EncodeImapValue(char *encoding, const char *value, PRBool useQuotes, PRBool reallyDredd) @@ -787,9 +787,7 @@ for (i = 0; i < termCount && NS_SUCCEEDED(err); i++) { char *termEncoding; - nsCOMPtr pTerm; - searchTerms->QueryElementAt(i, NS_GET_IID(nsIMsgSearchTerm), - (void **)getter_AddRefs(pTerm)); + nsCOMPtr pTerm(do_QueryElementAt(searchTerms, i)); err = EncodeImapTerm (pTerm, reallyDredd, srcCharset, destCharset, &termEncoding); if (NS_SUCCEEDED(err) && nsnull != termEncoding) { @@ -818,63 +816,63 @@ char *nsMsgSearchAdapter::TransformSpacesToStars (const char *spaceString, msg_TransformType transformType) { - char *starString; - - if (transformType == kOverwrite) - { - if ((starString = nsCRT::strdup(spaceString)) != nsnull) - { - char *star = starString; - while ((star = PL_strchr(star, ' ')) != nsnull) - *star = '*'; - } - } - else - { - int i, count; - - for (i = 0, count = 0; spaceString[i]; ) - { - if (spaceString[i++] == ' ') - { - count++; - while (spaceString[i] && spaceString[i] == ' ') i++; - } - } - - if (transformType == kSurround) - count *= 2; - - if (count > 0) - { - if ((starString = (char *)PR_Malloc(i + count + 1)) != nsnull) - { - int j; - - for (i = 0, j = 0; spaceString[i]; ) - { - if (spaceString[i] == ' ') - { - starString[j++] = '*'; - starString[j++] = ' '; - if (transformType == kSurround) - starString[j++] = '*'; - - i++; - while (spaceString[i] && spaceString[i] == ' ') - i++; - } - else - starString[j++] = spaceString[i++]; - } - starString[j] = 0; - } - } - else - starString = nsCRT::strdup(spaceString); - } + char *starString; + + if (transformType == kOverwrite) + { + if ((starString = nsCRT::strdup(spaceString)) != nsnull) + { + char *star = starString; + while ((star = PL_strchr(star, ' ')) != nsnull) + *star = '*'; + } + } + else + { + int i, count; + + for (i = 0, count = 0; spaceString[i]; ) + { + if (spaceString[i++] == ' ') + { + count++; + while (spaceString[i] && spaceString[i] == ' ') i++; + } + } + + if (transformType == kSurround) + count *= 2; + + if (count > 0) + { + if ((starString = (char *)PR_Malloc(i + count + 1)) != nsnull) + { + int j; + + for (i = 0, j = 0; spaceString[i]; ) + { + if (spaceString[i] == ' ') + { + starString[j++] = '*'; + starString[j++] = ' '; + if (transformType == kSurround) + starString[j++] = '*'; + + i++; + while (spaceString[i] && spaceString[i] == ' ') + i++; + } + else + starString[j++] = spaceString[i++]; + } + starString[j] = 0; + } + } + else + starString = nsCRT::strdup(spaceString); + } - return starString; + return starString; } //----------------------------------------------------------------------------- @@ -883,15 +881,15 @@ nsMsgSearchValidityTable::nsMsgSearchValidityTable () { - // Set everything to be unavailable and disabled - for (int i = 0; i < nsMsgSearchAttrib::kNumMsgSearchAttributes; i++) + // Set everything to be unavailable and disabled + for (int i = 0; i < nsMsgSearchAttrib::kNumMsgSearchAttributes; i++) for (int j = 0; j < nsMsgSearchOp::kNumMsgSearchOperators; j++) - { - SetAvailable (i, j, PR_FALSE); - SetEnabled (i, j, PR_FALSE); - SetValidButNotShown (i,j, PR_FALSE); - } - m_numAvailAttribs = 0; // # of attributes marked with at least one available operator + { + SetAvailable (i, j, PR_FALSE); + SetEnabled (i, j, PR_FALSE); + SetValidButNotShown (i,j, PR_FALSE); + } + m_numAvailAttribs = 0; // # of attributes marked with at least one available operator // assume default is Subject, which it is for mail and news search // it's not for LDAP, so we'll call SetDefaultAttrib() m_defaultAttrib = nsMsgSearchAttrib::Subject; @@ -903,91 +901,89 @@ nsresult nsMsgSearchValidityTable::GetNumAvailAttribs(PRInt32 *aResult) { - m_numAvailAttribs = 0; - for (int i = 0; i < nsMsgSearchAttrib::kNumMsgSearchAttributes; i++) - for (int j = 0; j < nsMsgSearchOp::kNumMsgSearchOperators; j++) { - PRBool available; - GetAvailable(i, j, &available); - if (available) - { - m_numAvailAttribs++; - break; - } - } - *aResult = m_numAvailAttribs; - return NS_OK; + m_numAvailAttribs = 0; + for (int i = 0; i < nsMsgSearchAttrib::kNumMsgSearchAttributes; i++) + for (int j = 0; j < nsMsgSearchOp::kNumMsgSearchOperators; j++) { + PRBool available; + GetAvailable(i, j, &available); + if (available) + { + m_numAvailAttribs++; + break; + } + } + *aResult = m_numAvailAttribs; + return NS_OK; } nsresult nsMsgSearchValidityTable::ValidateTerms (nsISupportsArray *searchTerms) { - nsresult err = NS_OK; + nsresult err = NS_OK; PRUint32 count; NS_ENSURE_ARG(searchTerms); searchTerms->Count(&count); - for (PRUint32 i = 0; i < count; i++) - { - nsCOMPtr pTerm; - searchTerms->QueryElementAt(i, NS_GET_IID(nsIMsgSearchTerm), - (void **)getter_AddRefs(pTerm)); - - nsIMsgSearchTerm *iTerm = pTerm; - nsMsgSearchTerm *term = NS_STATIC_CAST(nsMsgSearchTerm *, iTerm); -// XP_ASSERT(term->IsValid()); - PRBool enabled; - PRBool available; - GetEnabled(term->m_attribute, term->m_operator, &enabled); - GetAvailable(term->m_attribute, term->m_operator, &available); - if (!enabled || !available) - { - PRBool validNotShown; - GetValidButNotShown(term->m_attribute, term->m_operator, - &validNotShown); - if (!validNotShown) - err = NS_MSG_ERROR_INVALID_SEARCH_SCOPE; - } - } + for (PRUint32 i = 0; i < count; i++) + { + nsCOMPtr pTerm(do_QueryElementAt(searchTerms, i)); - return err; + nsIMsgSearchTerm *iTerm = pTerm; + nsMsgSearchTerm *term = NS_STATIC_CAST(nsMsgSearchTerm *, iTerm); +// XP_ASSERT(term->IsValid()); + PRBool enabled; + PRBool available; + GetEnabled(term->m_attribute, term->m_operator, &enabled); + GetAvailable(term->m_attribute, term->m_operator, &available); + if (!enabled || !available) + { + PRBool validNotShown; + GetValidButNotShown(term->m_attribute, term->m_operator, + &validNotShown); + if (!validNotShown) + err = NS_MSG_ERROR_INVALID_SEARCH_SCOPE; + } + } + + return err; } nsresult nsMsgSearchValidityTable::GetAvailableAttributes(PRUint32 *length, nsMsgSearchAttribValue **aResult) { - // count first - PRUint32 totalAttributes=0; - PRInt32 i, j; - for (i = 0; i< nsMsgSearchAttrib::kNumMsgSearchAttributes; i++) { - for (j=0; j< nsMsgSearchOp::kNumMsgSearchOperators; j++) { - if (m_table[i][j].bitAvailable) { - totalAttributes++; - break; - } - } + // count first + PRUint32 totalAttributes=0; + PRInt32 i, j; + for (i = 0; i< nsMsgSearchAttrib::kNumMsgSearchAttributes; i++) { + for (j=0; j< nsMsgSearchOp::kNumMsgSearchOperators; j++) { + if (m_table[i][j].bitAvailable) { + totalAttributes++; + break; + } } + } - nsMsgSearchAttribValue *array = (nsMsgSearchAttribValue*) - nsMemory::Alloc(sizeof(nsMsgSearchAttribValue) * totalAttributes); - NS_ENSURE_TRUE(array, NS_ERROR_OUT_OF_MEMORY); + nsMsgSearchAttribValue *array = (nsMsgSearchAttribValue*) + nsMemory::Alloc(sizeof(nsMsgSearchAttribValue) * totalAttributes); + NS_ENSURE_TRUE(array, NS_ERROR_OUT_OF_MEMORY); - PRUint32 numStored=0; - for (i = 0; i< nsMsgSearchAttrib::kNumMsgSearchAttributes; i++) { - for (j=0; j< nsMsgSearchOp::kNumMsgSearchOperators; j++) { - if (m_table[i][j].bitAvailable) { - array[numStored++] = i; - break; - } - } + PRUint32 numStored=0; + for (i = 0; i< nsMsgSearchAttrib::kNumMsgSearchAttributes; i++) { + for (j=0; j< nsMsgSearchOp::kNumMsgSearchOperators; j++) { + if (m_table[i][j].bitAvailable) { + array[numStored++] = i; + break; + } } + } - NS_ASSERTION(totalAttributes == numStored, "Search Attributes not lining up"); - *length = totalAttributes; - *aResult = array; + NS_ASSERTION(totalAttributes == numStored, "Search Attributes not lining up"); + *length = totalAttributes; + *aResult = array; - return NS_OK; + return NS_OK; } nsresult @@ -995,33 +991,33 @@ PRUint32 *aLength, nsMsgSearchOpValue **aResult) { - nsMsgSearchAttribValue attr; - if (aAttribute == nsMsgSearchAttrib::Default) - attr = m_defaultAttrib; - else - attr = PR_MIN(aAttribute, nsMsgSearchAttrib::OtherHeader); + nsMsgSearchAttribValue attr; + if (aAttribute == nsMsgSearchAttrib::Default) + attr = m_defaultAttrib; + else + attr = PR_MIN(aAttribute, nsMsgSearchAttrib::OtherHeader); - PRUint32 totalOperators=0; - PRInt32 i; - for (i=0; iSetAvailable (aSearchAttrib, nsMsgSearchOp::Contains, 1); - table->SetEnabled (aSearchAttrib, nsMsgSearchOp::Contains, 1); - table->SetAvailable (aSearchAttrib, nsMsgSearchOp::DoesntContain, 1); - table->SetEnabled (aSearchAttrib, nsMsgSearchOp::DoesntContain, 1); - table->SetAvailable (aSearchAttrib, nsMsgSearchOp::Is, 1); - table->SetEnabled (aSearchAttrib, nsMsgSearchOp::Is, 1); - table->SetAvailable (aSearchAttrib, nsMsgSearchOp::Isnt, 1); - table->SetEnabled (aSearchAttrib, nsMsgSearchOp::Isnt, 1); - table->SetAvailable (aSearchAttrib, nsMsgSearchOp::BeginsWith, 1); - table->SetEnabled (aSearchAttrib, nsMsgSearchOp::BeginsWith, 1); - table->SetAvailable (aSearchAttrib, nsMsgSearchOp::EndsWith, 1); - table->SetEnabled (aSearchAttrib, nsMsgSearchOp::EndsWith, 1); - table->SetAvailable (aSearchAttrib, nsMsgSearchOp::SoundsLike, 1); - table->SetEnabled (aSearchAttrib, nsMsgSearchOp::SoundsLike, 1); - return NS_OK; + table->SetAvailable (aSearchAttrib, nsMsgSearchOp::Contains, 1); + table->SetEnabled (aSearchAttrib, nsMsgSearchOp::Contains, 1); + table->SetAvailable (aSearchAttrib, nsMsgSearchOp::DoesntContain, 1); + table->SetEnabled (aSearchAttrib, nsMsgSearchOp::DoesntContain, 1); + table->SetAvailable (aSearchAttrib, nsMsgSearchOp::Is, 1); + table->SetEnabled (aSearchAttrib, nsMsgSearchOp::Is, 1); + table->SetAvailable (aSearchAttrib, nsMsgSearchOp::Isnt, 1); + table->SetEnabled (aSearchAttrib, nsMsgSearchOp::Isnt, 1); + table->SetAvailable (aSearchAttrib, nsMsgSearchOp::BeginsWith, 1); + table->SetEnabled (aSearchAttrib, nsMsgSearchOp::BeginsWith, 1); + table->SetAvailable (aSearchAttrib, nsMsgSearchOp::EndsWith, 1); + table->SetEnabled (aSearchAttrib, nsMsgSearchOp::EndsWith, 1); + table->SetAvailable (aSearchAttrib, nsMsgSearchOp::SoundsLike, 1); + table->SetEnabled (aSearchAttrib, nsMsgSearchOp::SoundsLike, 1); + return NS_OK; } nsresult nsMsgSearchValidityManager::InitLdapTable() Index: mozilla/mailnews/base/search/src/nsMsgSearchNews.cpp =================================================================== RCS file: /cvsroot/mozilla/mailnews/base/search/src/nsMsgSearchNews.cpp,v retrieving revision 1.37 diff -u -r1.37 mozilla/mailnews/base/search/src/nsMsgSearchNews.cpp --- mozilla/mailnews/base/search/src/nsMsgSearchNews.cpp +++ mozilla/mailnews/base/search/src/nsMsgSearchNews.cpp @@ -1,4 +1,4 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * @@ -75,113 +75,113 @@ nsresult nsMsgSearchNews::ValidateTerms () { - nsresult err = nsMsgSearchAdapter::ValidateTerms (); - if (NS_OK == err) - { - err = Encode (&m_encoding); - } + nsresult err = nsMsgSearchAdapter::ValidateTerms (); + if (NS_OK == err) + { + err = Encode (&m_encoding); + } - return err; + return err; } nsresult nsMsgSearchNews::Search (PRBool *aDone) { - // the state machine runs in the news: handler - nsresult err = NS_ERROR_NOT_IMPLEMENTED; - return err; + // the state machine runs in the news: handler + nsresult err = NS_ERROR_NOT_IMPLEMENTED; + return err; } PRUnichar *nsMsgSearchNews::EncodeToWildmat (const PRUnichar *value) { - // Here we take advantage of XPAT's use of the wildmat format, which allows - // a case-insensitive match by specifying each case possibility for each character - // So, "FooBar" is encoded as "[Ff][Oo][Bb][Aa][Rr]" + // Here we take advantage of XPAT's use of the wildmat format, which allows + // a case-insensitive match by specifying each case possibility for each character + // So, "FooBar" is encoded as "[Ff][Oo][Bb][Aa][Rr]" PRUnichar *caseInsensitiveValue = (PRUnichar*) nsMemory::Alloc(sizeof(PRUnichar) * ((4 * nsCRT::strlen(value)) + 1)); - if (caseInsensitiveValue) - { - PRUnichar *walkValue = caseInsensitiveValue; - while (*value) - { - if (nsCRT::IsAsciiAlpha(*value)) - { - *walkValue++ = (PRUnichar)'['; - *walkValue++ = ToUpperCase((PRUnichar)*value); - *walkValue++ = ToLowerCase((PRUnichar)*value); - *walkValue++ = (PRUnichar)']'; - } - else - *walkValue++ = *value; - value++; - } - *walkValue = 0; - } - return caseInsensitiveValue; + if (caseInsensitiveValue) + { + PRUnichar *walkValue = caseInsensitiveValue; + while (*value) + { + if (nsCRT::IsAsciiAlpha(*value)) + { + *walkValue++ = (PRUnichar)'['; + *walkValue++ = ToUpperCase((PRUnichar)*value); + *walkValue++ = ToLowerCase((PRUnichar)*value); + *walkValue++ = (PRUnichar)']'; + } + else + *walkValue++ = *value; + value++; + } + *walkValue = 0; + } + return caseInsensitiveValue; } char *nsMsgSearchNews::EncodeTerm (nsIMsgSearchTerm *term) { - // Develop an XPAT-style encoding for the search term + // Develop an XPAT-style encoding for the search term - NS_ASSERTION(term, "null term"); - if (!term) - return nsnull; + NS_ASSERTION(term, "null term"); + if (!term) + return nsnull; - // Find a string to represent the attribute - const char *attribEncoding = nsnull; + // Find a string to represent the attribute + const char *attribEncoding = nsnull; nsMsgSearchAttribValue attrib; term->GetAttrib(&attrib); - switch (attrib) - { - case nsMsgSearchAttrib::Sender: - attribEncoding = m_kNntpFrom; - break; - case nsMsgSearchAttrib::Subject: - attribEncoding = m_kNntpSubject; - break; - default: - NS_ASSERTION(PR_FALSE,"malformed search"); // malformed search term? - return nsnull; - } - - // Build a string to represent the string pattern - PRBool leadingStar = PR_FALSE; - PRBool trailingStar = PR_FALSE; - int overhead = 1; // null terminator + switch (attrib) + { + case nsMsgSearchAttrib::Sender: + attribEncoding = m_kNntpFrom; + break; + case nsMsgSearchAttrib::Subject: + attribEncoding = m_kNntpSubject; + break; + default: + NS_ASSERTION(PR_FALSE,"malformed search"); // malformed search term? + return nsnull; + } + + // Build a string to represent the string pattern + PRBool leadingStar = PR_FALSE; + PRBool trailingStar = PR_FALSE; + int overhead = 1; // null terminator nsMsgSearchOpValue op; term->GetOp(&op); - switch (op) - { - case nsMsgSearchOp::Contains: - leadingStar = PR_TRUE; - trailingStar = PR_TRUE; - overhead += 2; - break; - case nsMsgSearchOp::Is: - break; - case nsMsgSearchOp::BeginsWith: - trailingStar = PR_TRUE; - overhead++; - break; - case nsMsgSearchOp::EndsWith: - leadingStar = PR_TRUE; - overhead++; - break; - default: - NS_ASSERTION(PR_FALSE,"malformed search"); // malformed search term? - return nsnull; - } - + switch (op) + { + case nsMsgSearchOp::Contains: + leadingStar = PR_TRUE; + trailingStar = PR_TRUE; + overhead += 2; + break; + case nsMsgSearchOp::Is: + break; + case nsMsgSearchOp::BeginsWith: + trailingStar = PR_TRUE; + overhead++; + break; + case nsMsgSearchOp::EndsWith: + leadingStar = PR_TRUE; + overhead++; + break; + default: + NS_ASSERTION(PR_FALSE,"malformed search"); // malformed search term? + return nsnull; + } + // ### i18N problem Get the csid from FE, which is the correct csid for term -// int16 wincsid = INTL_GetCharSetID(INTL_DefaultTextWidgetCsidSel); +// int16 wincsid = INTL_GetCharSetID(INTL_DefaultTextWidgetCsidSel); - // Do INTL_FormatNNTPXPATInRFC1522Format trick for non-ASCII string -// unsigned char *intlNonRFC1522Value = INTL_FormatNNTPXPATInNonRFC1522Format (wincsid, (unsigned char*)term->m_value.u.string); + // Do INTL_FormatNNTPXPATInRFC1522Format trick for non-ASCII string +// unsigned char *intlNonRFC1522Value = INTL_FormatNNTPXPATInNonRFC1522Format (wincsid, (unsigned char*)term->m_value.u.string); nsCOMPtr searchValue; nsresult rv = term->GetValue(getter_AddRefs(searchValue)); @@ -191,58 +191,58 @@ nsXPIDLString intlNonRFC1522Value; rv = searchValue->GetStr(getter_Copies(intlNonRFC1522Value)); - if (NS_FAILED(rv) || !intlNonRFC1522Value) - return nsnull; - - PRUnichar *caseInsensitiveValue = EncodeToWildmat (intlNonRFC1522Value); - if (!caseInsensitiveValue) - return nsnull; - - // TO DO: Do INTL_FormatNNTPXPATInRFC1522Format trick for non-ASCII string - // Unfortunately, we currently do not handle xxx or xxx search in XPAT - // Need to add the INTL_FormatNNTPXPATInRFC1522Format call after we can do that - // so we should search a string in either RFC1522 format and non-RFC1522 format - - PRUnichar *escapedValue = EscapeSearchUrl (caseInsensitiveValue); - nsMemory::Free(caseInsensitiveValue); - if (!escapedValue) - return nsnull; + if (NS_FAILED(rv) || !intlNonRFC1522Value) + return nsnull; + + PRUnichar *caseInsensitiveValue = EncodeToWildmat (intlNonRFC1522Value); + if (!caseInsensitiveValue) + return nsnull; + + // TO DO: Do INTL_FormatNNTPXPATInRFC1522Format trick for non-ASCII string + // Unfortunately, we currently do not handle xxx or xxx search in XPAT + // Need to add the INTL_FormatNNTPXPATInRFC1522Format call after we can do that + // so we should search a string in either RFC1522 format and non-RFC1522 format + + PRUnichar *escapedValue = EscapeSearchUrl (caseInsensitiveValue); + nsMemory::Free(caseInsensitiveValue); + if (!escapedValue) + return nsnull; #if 0 - // We also need to apply NET_Escape to it since we have to pass 8-bits data - // And sometimes % in the 7-bit doulbe byte JIS - // - PRUnichar * urlEncoded = nsEscape(escapedValue, url_Path); - nsCRT::free(escapedValue); - - if (! urlEncoded) - return nsnull; - - char *pattern = new char [nsCRT::strlen(urlEncoded) + overhead]; - if (!pattern) - return nsnull; - else - pattern[0] = '\0'; + // We also need to apply NET_Escape to it since we have to pass 8-bits data + // And sometimes % in the 7-bit doulbe byte JIS + // + PRUnichar * urlEncoded = nsEscape(escapedValue, url_Path); + nsCRT::free(escapedValue); + + if (! urlEncoded) + return nsnull; + + char *pattern = new char [nsCRT::strlen(urlEncoded) + overhead]; + if (!pattern) + return nsnull; + else + pattern[0] = '\0'; #else nsCAutoString pattern; #endif - if (leadingStar) + if (leadingStar) pattern.Append('*'); AppendUTF16toUTF8(escapedValue, pattern); - if (trailingStar) + if (trailingStar) pattern.Append('*'); - // Combine the XPAT command syntax with the attribute and the pattern to - // form the term encoding - const char xpatTemplate[] = "XPAT %s 1- %s"; - int termLength = (sizeof(xpatTemplate) - 1) + strlen(attribEncoding) + pattern.Length() + 1; - char *termEncoding = new char [termLength]; - if (termEncoding) - PR_snprintf (termEncoding, termLength, xpatTemplate, attribEncoding, pattern.get()); + // Combine the XPAT command syntax with the attribute and the pattern to + // form the term encoding + const char xpatTemplate[] = "XPAT %s 1- %s"; + int termLength = (sizeof(xpatTemplate) - 1) + strlen(attribEncoding) + pattern.Length() + 1; + char *termEncoding = new char [termLength]; + if (termEncoding) + PR_snprintf (termEncoding, termLength, xpatTemplate, attribEncoding, pattern.get()); - return termEncoding; + return termEncoding; } nsresult nsMsgSearchNews::GetEncoding(char **result) @@ -254,64 +254,62 @@ nsresult nsMsgSearchNews::Encode (nsCString *outEncoding) { - NS_ASSERTION(outEncoding, "no out encoding"); - if (!outEncoding) - return NS_ERROR_NULL_POINTER; + NS_ASSERTION(outEncoding, "no out encoding"); + if (!outEncoding) + return NS_ERROR_NULL_POINTER; - nsresult err = NS_OK; + nsresult err = NS_OK; PRUint32 numTerms; m_searchTerms->Count(&numTerms); - char **intermediateEncodings = new char * [numTerms]; - if (intermediateEncodings) - { - // Build an XPAT command for each term - int encodingLength = 0; - PRUint32 i; - for (i = 0; i < numTerms; i++) - { - nsCOMPtr pTerm; - m_searchTerms->QueryElementAt(i, NS_GET_IID(nsIMsgSearchTerm), - (void **)getter_AddRefs(pTerm)); - // set boolean OR term if any of the search terms are an OR...this only works if we are using - // homogeneous boolean operators. + char **intermediateEncodings = new char * [numTerms]; + if (intermediateEncodings) + { + // Build an XPAT command for each term + int encodingLength = 0; + PRUint32 i; + for (i = 0; i < numTerms; i++) + { + nsCOMPtr pTerm(do_QueryElementAt(m_searchTerms, i)); + // set boolean OR term if any of the search terms are an OR...this only works if we are using + // homogeneous boolean operators. PRBool isBooleanOpAnd; pTerm->GetBooleanAnd(&isBooleanOpAnd); - m_ORSearch = !isBooleanOpAnd; - - intermediateEncodings[i] = EncodeTerm (pTerm); - if (intermediateEncodings[i]) - encodingLength += strlen(intermediateEncodings[i]) + strlen(m_kTermSeparator); - } - encodingLength += strlen("?search"); - // Combine all the term encodings into one big encoding - char *encoding = new char [encodingLength + 1]; - if (encoding) - { - PL_strcpy (encoding, "?search"); + m_ORSearch = !isBooleanOpAnd; + + intermediateEncodings[i] = EncodeTerm (pTerm); + if (intermediateEncodings[i]) + encodingLength += strlen(intermediateEncodings[i]) + strlen(m_kTermSeparator); + } + encodingLength += strlen("?search"); + // Combine all the term encodings into one big encoding + char *encoding = new char [encodingLength + 1]; + if (encoding) + { + PL_strcpy (encoding, "?search"); m_searchTerms->Count(&numTerms); - for (i = 0; i < numTerms; i++) - { - if (intermediateEncodings[i]) - { - PL_strcat (encoding, m_kTermSeparator); - PL_strcat (encoding, intermediateEncodings[i]); - delete [] intermediateEncodings[i]; - } - } - *outEncoding = encoding; - } - else - err = NS_ERROR_OUT_OF_MEMORY; - } - else - err = NS_ERROR_OUT_OF_MEMORY; - delete [] intermediateEncodings; + for (i = 0; i < numTerms; i++) + { + if (intermediateEncodings[i]) + { + PL_strcat (encoding, m_kTermSeparator); + PL_strcat (encoding, intermediateEncodings[i]); + delete [] intermediateEncodings[i]; + } + } + *outEncoding = encoding; + } + else + err = NS_ERROR_OUT_OF_MEMORY; + } + else + err = NS_ERROR_OUT_OF_MEMORY; + delete [] intermediateEncodings; - return err; + return err; } NS_IMETHODIMP nsMsgSearchNews::AddHit(nsMsgKey key) @@ -323,8 +321,8 @@ /* void CurrentUrlDone (in long exitCode); */ NS_IMETHODIMP nsMsgSearchNews::CurrentUrlDone(PRInt32 exitCode) { - CollateHits(); - ReportHits(); + CollateHits(); + ReportHits(); return NS_OK; } @@ -332,83 +330,83 @@ #if 0 // need to switch this to a notify stop loading handler, I think. void nsMsgSearchNews::PreExitFunction (URL_Struct * /*url*/, int status, MWContext *context) { - MSG_SearchFrame *frame = MSG_SearchFrame::FromContext (context); - nsMsgSearchNews *adapter = (nsMsgSearchNews*) frame->GetRunningAdapter(); - adapter->CollateHits(); - adapter->ReportHits(); - - if (status == MK_INTERRUPTED) - { - adapter->Abort(); - frame->EndCylonMode(); - } - else - { - frame->m_idxRunningScope++; - if (frame->m_idxRunningScope >= frame->m_scopeList.Count()) - frame->EndCylonMode(); - } + MSG_SearchFrame *frame = MSG_SearchFrame::FromContext (context); + nsMsgSearchNews *adapter = (nsMsgSearchNews*) frame->GetRunningAdapter(); + adapter->CollateHits(); + adapter->ReportHits(); + + if (status == MK_INTERRUPTED) + { + adapter->Abort(); + frame->EndCylonMode(); + } + else + { + frame->m_idxRunningScope++; + if (frame->m_idxRunningScope >= frame->m_scopeList.Count()) + frame->EndCylonMode(); + } } #endif // 0 PRBool nsMsgSearchNews::DuplicateHit(PRUint32 artNum) // ASSUMES m_hits is sorted!! { - PRUint32 index; - for (index = 0; index < m_hits.GetSize(); index++) - if (artNum == m_hits.ElementAt(index)) - return PR_TRUE; - return PR_FALSE; + PRUint32 index; + for (index = 0; index < m_hits.GetSize(); index++) + if (artNum == m_hits.ElementAt(index)) + return PR_TRUE; + return PR_FALSE; } void nsMsgSearchNews::CollateHits () { - // Since the XPAT commands are processed one at a time, the result set for the - // entire query is the intersection of results for each XPAT command if an AND Search - // otherwise we want the union of all the search hits (minus the duplicates of course) - - if (m_candidateHits.GetSize() == 0) - return; - - // Sort the article numbers first, so it's easy to tell how many hits - // on a given article we got - m_candidateHits.QuickSort(CompareArticleNumbers); - int size = m_candidateHits.GetSize(); - int index = 0; - PRUint32 candidate = m_candidateHits.ElementAt(index); - - if (m_ORSearch) - { - for (index = 0; index < size; index++) - { - candidate = m_candidateHits.ElementAt(index); - if (!DuplicateHit(candidate)) // if not a dup, add it to the hit list - m_hits.Add (candidate); - } - return; - } - - - // otherwise we have a traditional and search which must be collated - - // In order to get promoted into the hits list, a candidate article number - // must appear in the results of each XPAT command. So if we fire 3 XPAT - // commands (one per search term), the article number must appear 3 times. - // If it appears less than 3 times, it matched some search terms, but not all + // Since the XPAT commands are processed one at a time, the result set for the + // entire query is the intersection of results for each XPAT command if an AND Search + // otherwise we want the union of all the search hits (minus the duplicates of course) + + if (m_candidateHits.GetSize() == 0) + return; + + // Sort the article numbers first, so it's easy to tell how many hits + // on a given article we got + m_candidateHits.QuickSort(CompareArticleNumbers); + int size = m_candidateHits.GetSize(); + int index = 0; + PRUint32 candidate = m_candidateHits.ElementAt(index); - PRUint32 termCount; + if (m_ORSearch) + { + for (index = 0; index < size; index++) + { + candidate = m_candidateHits.ElementAt(index); + if (!DuplicateHit(candidate)) // if not a dup, add it to the hit list + m_hits.Add (candidate); + } + return; + } + + + // otherwise we have a traditional and search which must be collated + + // In order to get promoted into the hits list, a candidate article number + // must appear in the results of each XPAT command. So if we fire 3 XPAT + // commands (one per search term), the article number must appear 3 times. + // If it appears less than 3 times, it matched some search terms, but not all + + PRUint32 termCount; m_searchTerms->Count(&termCount); - PRUint32 candidateCount = 0; - while (index < size) - { - if (candidate == m_candidateHits.ElementAt(index)) - candidateCount++; - else - candidateCount = 1; - if (candidateCount == termCount) - m_hits.Add (m_candidateHits.ElementAt(index)); - candidate = m_candidateHits.ElementAt(index++); - } + PRUint32 candidateCount = 0; + while (index < size) + { + if (candidate == m_candidateHits.ElementAt(index)) + candidateCount++; + else + candidateCount = 1; + if (candidateCount == termCount) + m_hits.Add (m_candidateHits.ElementAt(index)); + candidate = m_candidateHits.ElementAt(index++); + } } void nsMsgSearchNews::ReportHits () @@ -425,41 +423,41 @@ if (db) { - for (PRUint32 i = 0; i < m_hits.GetSize(); i++) - { + for (PRUint32 i = 0; i < m_hits.GetSize(); i++) + { nsCOMPtr header; - db->GetMsgHdrForKey(m_hits.ElementAt(i), getter_AddRefs(header)); - if (header) - ReportHit(header, scopeFolder); - } + db->GetMsgHdrForKey(m_hits.ElementAt(i), getter_AddRefs(header)); + if (header) + ReportHit(header, scopeFolder); + } } } // ### this should take an nsIMsgFolder instead of a string location. void nsMsgSearchNews::ReportHit (nsIMsgDBHdr *pHeaders, nsIMsgFolder *folder) { - // this is totally filched from msg_SearchOfflineMail until I decide whether the - // right thing is to get them from the db or from NNTP + // this is totally filched from msg_SearchOfflineMail until I decide whether the + // right thing is to get them from the db or from NNTP - nsresult err = NS_OK; - nsCOMPtr session; - nsCOMPtr scopeFolder; - err = m_scope->GetFolder(getter_AddRefs(scopeFolder)); - m_scope->GetSearchSession(getter_AddRefs(session)); - if (session) - session->AddSearchHit (pHeaders, scopeFolder); + nsresult err = NS_OK; + nsCOMPtr session; + nsCOMPtr scopeFolder; + err = m_scope->GetFolder(getter_AddRefs(scopeFolder)); + m_scope->GetSearchSession(getter_AddRefs(session)); + if (session) + session->AddSearchHit (pHeaders, scopeFolder); } int PR_CALLBACK nsMsgSearchNews::CompareArticleNumbers (const void *v1, const void *v2, void *data) { - // QuickSort callback to compare article numbers + // QuickSort callback to compare article numbers - uint32 i1 = *(uint32*) v1; - uint32 i2 = *(uint32*) v2; - return i1 - i2; + uint32 i1 = *(uint32*) v1; + uint32 i2 = *(uint32*) v2; + return i1 - i2; } nsresult nsMsgSearchValidityManager::InitNewsTable() Index: mozilla/mailnews/base/search/src/nsMsgSearchSession.cpp =================================================================== RCS file: /cvsroot/mozilla/mailnews/base/search/src/nsMsgSearchSession.cpp,v retrieving revision 1.59 diff -u -r1.59 mozilla/mailnews/base/search/src/nsMsgSearchSession.cpp --- mozilla/mailnews/base/search/src/nsMsgSearchSession.cpp +++ mozilla/mailnews/base/search/src/nsMsgSearchSession.cpp @@ -1,4 +1,4 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * @@ -83,51 +83,51 @@ PRBool BooleanANDp, const char *arbitraryHeader) { - // stupid gcc - nsMsgSearchBooleanOperator boolOp; - if (BooleanANDp) - boolOp = (nsMsgSearchBooleanOperator)nsMsgSearchBooleanOp::BooleanAND; - else - boolOp = (nsMsgSearchBooleanOperator)nsMsgSearchBooleanOp::BooleanOR; - nsMsgSearchTerm *pTerm = new nsMsgSearchTerm (attrib, op, value, - boolOp, arbitraryHeader); - if (nsnull == pTerm) - return NS_ERROR_OUT_OF_MEMORY; - m_termList->AppendElement (pTerm); - // force the expression tree to rebuild whenever we change the terms - delete m_expressionTree; - m_expressionTree = nsnull; - return NS_OK; + // stupid gcc + nsMsgSearchBooleanOperator boolOp; + if (BooleanANDp) + boolOp = (nsMsgSearchBooleanOperator)nsMsgSearchBooleanOp::BooleanAND; + else + boolOp = (nsMsgSearchBooleanOperator)nsMsgSearchBooleanOp::BooleanOR; + nsMsgSearchTerm *pTerm = new nsMsgSearchTerm (attrib, op, value, + boolOp, arbitraryHeader); + if (nsnull == pTerm) + return NS_ERROR_OUT_OF_MEMORY; + m_termList->AppendElement (pTerm); + // force the expression tree to rebuild whenever we change the terms + delete m_expressionTree; + m_expressionTree = nsnull; + return NS_OK; } NS_IMETHODIMP nsMsgSearchSession::AppendTerm(nsIMsgSearchTerm *aTerm) { - NS_ENSURE_ARG_POINTER(aTerm); - NS_ENSURE_TRUE(m_termList, NS_ERROR_NOT_INITIALIZED); - delete m_expressionTree; - m_expressionTree = nsnull; - return m_termList->AppendElement(aTerm); + NS_ENSURE_ARG_POINTER(aTerm); + NS_ENSURE_TRUE(m_termList, NS_ERROR_NOT_INITIALIZED); + delete m_expressionTree; + m_expressionTree = nsnull; + return m_termList->AppendElement(aTerm); } NS_IMETHODIMP nsMsgSearchSession::GetSearchTerms(nsISupportsArray **aResult) { - NS_ENSURE_ARG_POINTER(aResult); - *aResult = m_termList; - NS_ADDREF(*aResult); - return NS_OK; + NS_ENSURE_ARG_POINTER(aResult); + *aResult = m_termList; + NS_ADDREF(*aResult); + return NS_OK; } NS_IMETHODIMP nsMsgSearchSession::CreateTerm(nsIMsgSearchTerm **aResult) { - nsMsgSearchTerm *term = new nsMsgSearchTerm; - NS_ENSURE_TRUE(term, NS_ERROR_OUT_OF_MEMORY); - - *aResult = NS_STATIC_CAST(nsIMsgSearchTerm*,term); - NS_ADDREF(*aResult); - return NS_OK; + nsMsgSearchTerm *term = new nsMsgSearchTerm; + NS_ENSURE_TRUE(term, NS_ERROR_OUT_OF_MEMORY); + + *aResult = NS_STATIC_CAST(nsIMsgSearchTerm*,term); + NS_ADDREF(*aResult); + return NS_OK; } /* void RegisterListener (in nsIMsgSearchNotify listener); */ @@ -164,7 +164,7 @@ nsMsgSearchOpValue op, nsIMsgSearchValue * value) { - return NS_ERROR_NOT_IMPLEMENTED; + return NS_ERROR_NOT_IMPLEMENTED; } /* long CountSearchScopes (); */ @@ -182,10 +182,11 @@ nsIMsgFolder **folder) { // argh, does this do an addref? - nsMsgSearchScopeTerm *scopeTerm = (nsMsgSearchScopeTerm *) m_scopeList.SafeElementAt(which); - if (!scopeTerm) return NS_ERROR_INVALID_ARG; - *scopeId = scopeTerm->m_attribute; - *folder = scopeTerm->m_folder; + nsMsgSearchScopeTerm *scopeTerm = (nsMsgSearchScopeTerm *) m_scopeList.SafeElementAt(which); + if (!scopeTerm) + return NS_ERROR_INVALID_ARG; + *scopeId = scopeTerm->m_attribute; + *folder = scopeTerm->m_folder; NS_IF_ADDREF(*folder); return NS_OK; } @@ -213,7 +214,7 @@ NS_IMETHODIMP nsMsgSearchSession::AddDirectoryScopeTerm(nsMsgSearchScopeValue scope) { - nsMsgSearchScopeTerm *pScopeTerm = new nsMsgSearchScopeTerm(this, scope, nsnull); + nsMsgSearchScopeTerm *pScopeTerm = new nsMsgSearchScopeTerm(this, scope, nsnull); if (!pScopeTerm) return NS_ERROR_OUT_OF_MEMORY; @@ -223,8 +224,8 @@ NS_IMETHODIMP nsMsgSearchSession::ClearScopes() { - DestroyScopeList(); - return NS_OK; + DestroyScopeList(); + return NS_OK; } /* [noscript] boolean ScopeUsesCustomHeaders (in nsMsgSearchScope scope, in voidStar selection, in boolean forFilters); */ @@ -234,7 +235,7 @@ PRBool forFilters, PRBool *_retval) { - return NS_ERROR_NOT_IMPLEMENTED; + return NS_ERROR_NOT_IMPLEMENTED; } /* boolean IsStringAttribute (in nsMsgSearchAttribute attrib); */ @@ -243,7 +244,7 @@ PRBool *_retval) { NS_ENSURE_ARG(_retval); - return NS_ERROR_NOT_IMPLEMENTED; + return NS_ERROR_NOT_IMPLEMENTED; } /* void AddAllScopes (in nsMsgSearchScope attrib); */ @@ -251,25 +252,23 @@ nsMsgSearchSession::AddAllScopes(nsMsgSearchScopeValue attrib) { // don't think this is needed. - return NS_ERROR_NOT_IMPLEMENTED; + return NS_ERROR_NOT_IMPLEMENTED; } /* void Search (); */ NS_IMETHODIMP nsMsgSearchSession::Search(nsIMsgWindow *aWindow) { - nsresult err = Initialize (); - NS_ENSURE_SUCCESS(err,err); - if (m_listenerList) { - PRUint32 count; - m_listenerList->Count(&count); - for (PRUint32 i=0; i listener; - m_listenerList->QueryElementAt(i, NS_GET_IID(nsIMsgSearchNotify), - (void **)getter_AddRefs(listener)); - if (listener) - listener->OnNewSearch(); - } + nsresult err = Initialize (); + NS_ENSURE_SUCCESS(err,err); + if (m_listenerList) { + PRUint32 count; + m_listenerList->Count(&count); + for (PRUint32 i=0; i listener(do_QueryElementAt(m_listenerList, i)); + if (listener) + listener->OnNewSearch(); } + } m_window = aWindow; if (NS_SUCCEEDED(err)) err = BeginSearching (); @@ -283,7 +282,7 @@ { EnableFolderNotifications(PR_TRUE); if (m_idxRunningScope < m_scopeList.Count()) - m_window->StopUrls(); + m_window->StopUrls(); while (m_idxRunningScope < m_scopeList.Count()) { @@ -328,25 +327,25 @@ /* [noscript] readonly attribute voidStar searchParam; */ NS_IMETHODIMP nsMsgSearchSession::GetSearchParam(void * *aSearchParam) { - return NS_ERROR_NOT_IMPLEMENTED; + return NS_ERROR_NOT_IMPLEMENTED; } /* readonly attribute nsMsgSearchType searchType; */ NS_IMETHODIMP nsMsgSearchSession::GetSearchType(nsMsgSearchType * *aSearchType) { - return NS_ERROR_NOT_IMPLEMENTED; + return NS_ERROR_NOT_IMPLEMENTED; } /* [noscript] nsMsgSearchType SetSearchParam (in nsMsgSearchType type, in voidStar param); */ NS_IMETHODIMP nsMsgSearchSession::SetSearchParam(nsMsgSearchType *type, void * param, nsMsgSearchType **_retval) { - return NS_ERROR_NOT_IMPLEMENTED; + return NS_ERROR_NOT_IMPLEMENTED; } /* readonly attribute long numResults; */ NS_IMETHODIMP nsMsgSearchSession::GetNumResults(PRInt32 *aNumResults) { - return NS_ERROR_NOT_IMPLEMENTED; + return NS_ERROR_NOT_IMPLEMENTED; } NS_IMETHODIMP nsMsgSearchSession::SetWindow(nsIMsgWindow *aWindow) @@ -366,7 +365,7 @@ /* void OnStartRunningUrl (in nsIURI url); */ NS_IMETHODIMP nsMsgSearchSession::OnStartRunningUrl(nsIURI *url) { - return NS_OK; + return NS_OK; } /* void OnStopRunningUrl (in nsIURI url, in nsresult aExitCode); */ @@ -580,15 +579,13 @@ m_listenerList->Count(&count); for (PRUint32 i = 0; i < count; i++) { - nsCOMPtr pListener; - m_listenerList->QueryElementAt(i, NS_GET_IID(nsIMsgSearchNotify), - (void **)getter_AddRefs(pListener)); + nsCOMPtr pListener(do_QueryElementAt(m_listenerList, i)); if (pListener) pListener->OnSearchHit(header, folder); } } - return NS_OK; + return NS_OK; } nsresult nsMsgSearchSession::NotifyListenersDone(nsresult status) @@ -599,9 +596,7 @@ m_listenerList->Count(&count); for (PRUint32 i = 0; i < count; i++) { - nsCOMPtr pListener; - m_listenerList->QueryElementAt(i, NS_GET_IID(nsIMsgSearchNotify), - (void **)getter_AddRefs(pListener)); + nsCOMPtr pListener(do_QueryElementAt(m_listenerList, i)); if (pListener) pListener->OnSearchDone(status); @@ -627,7 +622,7 @@ for (int i = 0; i < m_resultList.Count(); i++) { result = m_resultList.ElementAt(i); - // NS_ASSERTION (result->IsValid(), "invalid search result"); + // NS_ASSERTION (result->IsValid(), "invalid search result"); delete result; } m_resultList.Clear(); @@ -642,7 +637,7 @@ for (PRInt32 i = count-1; i >= 0; i--) { scope = m_scopeList.ElementAt(i); - // NS_ASSERTION (scope->IsValid(), "invalid search scope"); + // NS_ASSERTION (scope->IsValid(), "invalid search scope"); delete scope; } m_scopeList.Clear(); @@ -651,12 +646,12 @@ void nsMsgSearchSession::DestroyTermList () { - m_termList->Clear(); + m_termList->Clear(); } nsMsgSearchScopeTerm *nsMsgSearchSession::GetRunningScope() { - return (nsMsgSearchScopeTerm *) m_scopeList.SafeElementAt(m_idxRunningScope); + return (nsMsgSearchScopeTerm *) m_scopeList.SafeElementAt(m_idxRunningScope); } nsresult nsMsgSearchSession::TimeSlice (PRBool *aDone) Index: mozilla/mailnews/base/search/src/nsMsgSearchTerm.cpp =================================================================== RCS file: /cvsroot/mozilla/mailnews/base/search/src/nsMsgSearchTerm.cpp,v retrieving revision 1.131 diff -u -r1.131 mozilla/mailnews/base/search/src/nsMsgSearchTerm.cpp --- mozilla/mailnews/base/search/src/nsMsgSearchTerm.cpp +++ mozilla/mailnews/base/search/src/nsMsgSearchTerm.cpp @@ -1731,9 +1731,8 @@ m_valueList->Count(&count); for (PRUint32 i = 0; i < count && err != NS_OK; i++) { - m_valueList->QueryElementAt(i, NS_GET_IID(nsIMsgSearchValue), - (void **)getter_AddRefs(value)); - + value = do_QueryElementAt(m_valueList, i); + nsMsgSearchAttribValue valueAttribute; value->GetAttrib(&valueAttribute); if (attrib == valueAttribute) Index: mozilla/mailnews/base/src/nsMessenger.cpp =================================================================== RCS file: /cvsroot/mozilla/mailnews/base/src/nsMessenger.cpp,v retrieving revision 1.346 diff -u -r1.346 mozilla/mailnews/base/src/nsMessenger.cpp --- mozilla/mailnews/base/src/nsMessenger.cpp +++ mozilla/mailnews/base/src/nsMessenger.cpp @@ -760,9 +760,7 @@ messageUri = fullMessageUri.get(); } - nsCOMPtr convertedListener; - saveListener->QueryInterface(NS_GET_IID(nsIStreamListener), - getter_AddRefs(convertedListener)); + nsCOMPtr convertedListener(do_QueryInterface(saveListener)); #ifndef XP_MACOSX // if the content type is bin hex we are going to do a hokey hack and make sure we decode the bin hex @@ -1156,7 +1154,7 @@ } NS_ADDREF(saveListener); - rv = saveListener->QueryInterface(NS_GET_IID(nsIUrlListener), getter_AddRefs(urlListener)); + urlListener = do_QueryInterface(saveListener, &rv); if (NS_FAILED(rv)) goto done; @@ -1251,9 +1249,7 @@ PL_strcasestr(saveListener->m_templateUri, "imap://") != nsnull; - rv = saveListener->QueryInterface( - NS_GET_IID(nsIUrlListener), - getter_AddRefs(urlListener)); + urlListener = do_QueryInterface(saveListener, &rv); if (NS_FAILED(rv)) goto done; @@ -2754,8 +2750,8 @@ // copy the file back into the folder. Note: if we set msgToReplace then // CopyFileMessage() fails, do the delete ourselves - nsCOMPtr listenerCopyService; - rv = this->QueryInterface( NS_GET_IID(nsIMsgCopyServiceListener), getter_AddRefs(listenerCopyService) ); + nsCOMPtr listenerCopyService + = do_QueryInterface(NS_ISUPPORTS_CAST(nsIStreamListener*, this), &rv); NS_ENSURE_SUCCESS(rv,rv); mMsgFileStream->Close(); @@ -2807,9 +2803,9 @@ NS_ENSURE_SUCCESS(rv,rv); rv = messageArray->AppendElement(mOriginalMessage); NS_ENSURE_SUCCESS(rv,rv); - nsCOMPtr listenerCopyService; - QueryInterface( NS_GET_IID(nsIMsgCopyServiceListener), getter_AddRefs(listenerCopyService) ); + nsCOMPtr listenerCopyService + = do_QueryInterface(NS_ISUPPORTS_CAST(nsIStreamListener*, this), &rv); mOriginalMessage = nsnull; return mMessageFolder->DeleteMessages( @@ -2951,7 +2947,7 @@ nsDelAttachListener::StartProcessing(nsMessenger * aMessenger, nsIMsgWindow * aMsgWindow, nsAttachmentState * aAttach, PRBool detaching) { - aMessenger->QueryInterface(NS_GET_IID(nsIMessenger), getter_AddRefs(mMessenger)); + mMessenger = do_QueryInterface(NS_ISUPPORTS_CAST(nsIMessenger*, this)); mMsgWindow = aMsgWindow; mAttach = aAttach; mDetaching = detaching; @@ -3020,8 +3016,8 @@ sHeader.Append(detachToHeader); // stream this message to our listener converting it via the attachment mime // converter. The listener will just write the converted message straight to disk. - nsCOMPtr listenerSupports; - rv = this->QueryInterface(NS_GET_IID(nsISupports), getter_AddRefs(listenerSupports)); + nsCOMPtr listenerSupports + = do_QueryInterface(NS_ISUPPORTS_CAST(nsIStreamListener*, this), &rv); NS_ENSURE_SUCCESS(rv,rv); nsCOMPtr listenerUrlListener = do_QueryInterface(listenerSupports, &rv); NS_ENSURE_SUCCESS(rv,rv); @@ -3134,8 +3130,9 @@ nsDelAttachListener * listener = new nsDelAttachListener; if (!listener) return NS_ERROR_OUT_OF_MEMORY; - nsCOMPtr listenerSupports; // auto-delete of the listener with error - listener->QueryInterface(NS_GET_IID(nsISupports), getter_AddRefs(listenerSupports)); + // auto-delete of the listener with error + nsCOMPtr listenerSupports + = do_QueryInterface(NS_ISUPPORTS_CAST(nsIStreamListener*, listener)); if (saveFileUris) listener->mDetachedFileUris = *saveFileUris; Index: mozilla/mailnews/base/src/nsMsgAccount.cpp =================================================================== RCS file: /cvsroot/mozilla/mailnews/base/src/nsMsgAccount.cpp,v retrieving revision 1.73 diff -u -r1.73 mozilla/mailnews/base/src/nsMsgAccount.cpp --- mozilla/mailnews/base/src/nsMsgAccount.cpp +++ mozilla/mailnews/base/src/nsMsgAccount.cpp @@ -280,9 +280,8 @@ if (NS_FAILED(rv)) return rv; if (idsupports) { - rv = idsupports->QueryInterface(NS_GET_IID(nsIMsgIdentity), - (void **)aDefaultIdentity); - NS_RELEASE(idsupports); + rv = CallQueryInterface(idsupports, aDefaultIdentity); + NS_RELEASE(idsupports); } return rv; } Index: mozilla/mailnews/base/src/nsMsgAccountManager.cpp =================================================================== RCS file: /cvsroot/mozilla/mailnews/base/src/nsMsgAccountManager.cpp,v retrieving revision 1.314 diff -u -r1.314 mozilla/mailnews/base/src/nsMsgAccountManager.cpp --- mozilla/mailnews/base/src/nsMsgAccountManager.cpp +++ mozilla/mailnews/base/src/nsMsgAccountManager.cpp @@ -700,13 +700,12 @@ PRUint32 i; for (i=0; i identity; - rv = identityArray->QueryElementAt(i, NS_GET_IID(nsIMsgIdentity), - (void **)getter_AddRefs(identity)); - if (NS_SUCCEEDED(rv)) + nsCOMPtr identity(do_QueryElementAt(identityArray, i, &rv)); + if (NS_SUCCEEDED(rv)) { // clear out all identity information. // watch out! could be scary identity->ClearAllValues(); + } } } @@ -789,13 +788,11 @@ PRUint32 index; PRBool foundValidDefaultAccount = PR_FALSE; for (index = 0; index < count; index++) { - nsCOMPtr aAccount; - rv = m_accounts->QueryElementAt(index, NS_GET_IID(nsIMsgAccount), - (void **)getter_AddRefs(aAccount)); + nsCOMPtr account(do_QueryElementAt(m_accounts, index, &rv)); if (NS_SUCCEEDED(rv)) { // get incoming server nsCOMPtr server; - rv = aAccount->GetIncomingServer(getter_AddRefs(server)); + rv = account->GetIncomingServer(getter_AddRefs(server)); NS_ENSURE_SUCCESS(rv,rv); PRBool canBeDefaultServer = PR_FALSE; @@ -805,7 +802,7 @@ // if this can serve as default server, set it as default and // break outof the loop. if (canBeDefaultServer) { - SetDefaultAccount(aAccount); + SetDefaultAccount(account); foundValidDefaultAccount = PR_TRUE; break; } @@ -816,9 +813,7 @@ // get the first account and use it. // we need to fix this scenario. NS_WARNING("No valid default account found, just using first (FIXME)"); - nsCOMPtr firstAccount; - m_accounts->QueryElementAt(0, NS_GET_IID(nsIMsgAccount), - (void **)getter_AddRefs(firstAccount)); + nsCOMPtr firstAccount(do_QueryElementAt(m_accounts, 0)); SetDefaultAccount(firstAccount); } @@ -2170,9 +2165,7 @@ if (numIdentities > 0) { - nsCOMPtr identity; - rv = identities->QueryElementAt(0, NS_GET_IID(nsIMsgIdentity), - (void **)getter_AddRefs(identity)); + nsCOMPtr identity(do_QueryElementAt(identities, 0, &rv)); NS_ENSURE_SUCCESS(rv, rv); NS_IF_ADDREF(*aIdentity = identity); } Index: mozilla/mailnews/base/src/nsMsgContentPolicy.cpp =================================================================== RCS file: /cvsroot/mozilla/mailnews/base/src/nsMsgContentPolicy.cpp,v retrieving revision 1.38 diff -u -r1.38 mozilla/mailnews/base/src/nsMsgContentPolicy.cpp --- mozilla/mailnews/base/src/nsMsgContentPolicy.cpp +++ mozilla/mailnews/base/src/nsMsgContentPolicy.cpp @@ -506,7 +506,7 @@ rv = docshellTreeItem->GetRootTreeItem(getter_AddRefs(rootItem)); NS_ENSURE_SUCCESS(rv, rv); - return rootItem->QueryInterface(NS_GET_IID(nsIDocShell), (void**) aDocShell); + return CallQueryInterface(rootItem, aDocShell); } /** Index: mozilla/mailnews/base/src/nsMsgFolderCache.cpp =================================================================== RCS file: /cvsroot/mozilla/mailnews/base/src/nsMsgFolderCache.cpp,v retrieving revision 1.48 diff -u -r1.48 mozilla/mailnews/base/src/nsMsgFolderCache.cpp --- mozilla/mailnews/base/src/nsMsgFolderCache.cpp +++ mozilla/mailnews/base/src/nsMsgFolderCache.cpp @@ -1,4 +1,4 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * @@ -48,15 +48,15 @@ #include "nsXPIDLString.h" #include "nsMsgBaseCID.h" -const char *kFoldersScope = "ns:msg:db:row:scope:folders:all"; // scope for all folders table +const char *kFoldersScope = "ns:msg:db:row:scope:folders:all"; // scope for all folders table const char *kFoldersTableKind = "ns:msg:db:table:kind:folders"; nsMsgFolderCache::nsMsgFolderCache() { m_cacheElements = nsnull; - m_mdbEnv = nsnull; - m_mdbStore = nsnull; - m_mdbAllFoldersTable = nsnull; + m_mdbEnv = nsnull; + m_mdbStore = nsnull; + m_mdbAllFoldersTable = nsnull; } // should this, could this be an nsCOMPtr ? @@ -64,272 +64,251 @@ nsMsgFolderCache::~nsMsgFolderCache() { - delete m_cacheElements; - if (m_mdbAllFoldersTable) - m_mdbAllFoldersTable->Release(); - if (m_mdbStore) - m_mdbStore->Release(); - if (gMDBFactory) - { - NS_RELEASE(gMDBFactory); - } - gMDBFactory = nsnull; - if (m_mdbEnv) - { - m_mdbEnv->Release(); - } + delete m_cacheElements; + if (m_mdbAllFoldersTable) + m_mdbAllFoldersTable->Release(); + if (m_mdbStore) + m_mdbStore->Release(); + if (gMDBFactory) + { + NS_RELEASE(gMDBFactory); + } + gMDBFactory = nsnull; + if (m_mdbEnv) + { + m_mdbEnv->Release(); + } } -NS_IMPL_ADDREF(nsMsgFolderCache) -NS_IMPL_RELEASE(nsMsgFolderCache) +NS_IMPL_ISUPPORTS1(nsMsgFolderCache, nsIMsgFolderCache)) -nsresult -nsMsgFolderCache::QueryInterface(const nsIID& iid, void **result) -{ - nsresult rv = NS_NOINTERFACE; - if (! result) - return NS_ERROR_NULL_POINTER; - - void *res = nsnull; - if (iid.Equals(NS_GET_IID(nsIMsgFolderCache)) || - iid.Equals(NS_GET_IID(nsISupports))) - res = NS_STATIC_CAST(nsIMsgFolderCache*, this); - if (res) - { - NS_ADDREF(this); - *result = res; - rv = NS_OK; - } - return rv; -} - /* static */ nsIMdbFactory *nsMsgFolderCache::GetMDBFactory() { - if (!gMDBFactory) - { - nsresult rv; - nsCOMPtr factoryfactory = do_CreateInstance(NS_MORK_CONTRACTID, &rv); - if (NS_SUCCEEDED(rv) && factoryfactory) - rv = factoryfactory->GetMdbFactory(&gMDBFactory); - } - return gMDBFactory; + if (!gMDBFactory) + { + nsresult rv; + nsCOMPtr factoryfactory = do_CreateInstance(NS_MORK_CONTRACTID, &rv); + if (NS_SUCCEEDED(rv) && factoryfactory) + rv = factoryfactory->GetMdbFactory(&gMDBFactory); + } + return gMDBFactory; } // initialize the various tokens and tables in our db's env nsresult nsMsgFolderCache::InitMDBInfo() { - nsresult err = NS_OK; + nsresult err = NS_OK; - if (GetStore()) - { - err = GetStore()->StringToToken(GetEnv(), kFoldersScope, &m_folderRowScopeToken); - if (err == NS_OK) - { - err = GetStore()->StringToToken(GetEnv(), kFoldersTableKind, &m_folderTableKindToken); - if (err == NS_OK) - { - // The table of all message hdrs will have table id 1. - m_allFoldersTableOID.mOid_Scope = m_folderRowScopeToken; - m_allFoldersTableOID.mOid_Id = 1; - } - } - } - return err; + if (GetStore()) + { + err = GetStore()->StringToToken(GetEnv(), kFoldersScope, &m_folderRowScopeToken); + if (err == NS_OK) + { + err = GetStore()->StringToToken(GetEnv(), kFoldersTableKind, &m_folderTableKindToken); + if (err == NS_OK) + { + // The table of all message hdrs will have table id 1. + m_allFoldersTableOID.mOid_Scope = m_folderRowScopeToken; + m_allFoldersTableOID.mOid_Id = 1; + } + } + } + return err; } // set up empty tables, dbFolderInfo, etc. nsresult nsMsgFolderCache::InitNewDB() { - nsresult err = NS_OK; + nsresult err = NS_OK; - err = InitMDBInfo(); - if (err == NS_OK) - { - nsIMdbStore *store = GetStore(); - // create the unique table for the dbFolderInfo. - mdb_err mdberr; + err = InitMDBInfo(); + if (err == NS_OK) + { + nsIMdbStore *store = GetStore(); + // create the unique table for the dbFolderInfo. + mdb_err mdberr; - mdberr = (nsresult) store->NewTable(GetEnv(), m_folderRowScopeToken, - m_folderTableKindToken, PR_FALSE, nsnull, &m_mdbAllFoldersTable); + mdberr = (nsresult) store->NewTable(GetEnv(), m_folderRowScopeToken, + m_folderTableKindToken, PR_FALSE, nsnull, &m_mdbAllFoldersTable); - } - return err; + } + return err; } nsresult nsMsgFolderCache::InitExistingDB() { - nsresult err = NS_OK; + nsresult err = NS_OK; - err = InitMDBInfo(); - if (err == NS_OK) - { - err = GetStore()->GetTable(GetEnv(), &m_allFoldersTableOID, &m_mdbAllFoldersTable); - if (NS_SUCCEEDED(err) && m_mdbAllFoldersTable) - { - nsIMdbTableRowCursor* rowCursor = nsnull; - err = m_mdbAllFoldersTable->GetTableRowCursor(GetEnv(), -1, &rowCursor); - if (NS_SUCCEEDED(err) && rowCursor) - { - // iterate over the table rows and create nsMsgFolderCacheElements for each. - while (PR_TRUE) - { - nsresult rv; - nsIMdbRow* hdrRow; - mdb_pos rowPos; - - rv = rowCursor->NextRow(GetEnv(), &hdrRow, &rowPos); - if (NS_FAILED(rv) || !hdrRow) - break; + err = InitMDBInfo(); + if (err == NS_OK) + { + err = GetStore()->GetTable(GetEnv(), &m_allFoldersTableOID, &m_mdbAllFoldersTable); + if (NS_SUCCEEDED(err) && m_mdbAllFoldersTable) + { + nsIMdbTableRowCursor* rowCursor = nsnull; + err = m_mdbAllFoldersTable->GetTableRowCursor(GetEnv(), -1, &rowCursor); + if (NS_SUCCEEDED(err) && rowCursor) + { + // iterate over the table rows and create nsMsgFolderCacheElements for each. + while (PR_TRUE) + { + nsresult rv; + nsIMdbRow* hdrRow; + mdb_pos rowPos; + + rv = rowCursor->NextRow(GetEnv(), &hdrRow, &rowPos); + if (NS_FAILED(rv) || !hdrRow) + break; - rv = AddCacheElement(nsnull, hdrRow, nsnull); + rv = AddCacheElement(nsnull, hdrRow, nsnull); hdrRow->Release(); - if (NS_FAILED(rv)) - return rv; - } - rowCursor->Release(); - } - } + if (NS_FAILED(rv)) + return rv; + } + rowCursor->Release(); + } + } else err = NS_ERROR_FAILURE; - } - return err; + } + return err; } nsresult nsMsgFolderCache::OpenMDB(const char *dbName, PRBool exists) { - nsresult ret=NS_OK; - nsIMdbFactory *myMDBFactory = GetMDBFactory(); - if (myMDBFactory) - { - ret = myMDBFactory->MakeEnv(nsnull, &m_mdbEnv); - if (NS_SUCCEEDED(ret)) - { - nsIMdbThumb *thumb = nsnull; - char *nativeFileName = nsCRT::strdup(dbName); - nsIMdbHeap* dbHeap = 0; - mdb_bool dbFrozen = mdbBool_kFalse; // not readonly, we want modifiable - - if (!nativeFileName) - return NS_ERROR_OUT_OF_MEMORY; - - if (m_mdbEnv) - m_mdbEnv->SetAutoClear(PR_TRUE); - if (exists) - { - mdbOpenPolicy inOpenPolicy; - mdb_bool canOpen; - mdbYarn outFormatVersion; - - nsIMdbFile* oldFile = 0; - ret = myMDBFactory->OpenOldFile(m_mdbEnv, dbHeap, nativeFileName, - dbFrozen, &oldFile); - if ( oldFile ) - { - if ( ret == NS_OK ) - { - ret = myMDBFactory->CanOpenFilePort(m_mdbEnv, oldFile, // file to investigate - &canOpen, &outFormatVersion); - if (ret == 0 && canOpen) - { - inOpenPolicy.mOpenPolicy_ScopePlan.mScopeStringSet_Count = 0; - inOpenPolicy.mOpenPolicy_MinMemory = 0; - inOpenPolicy.mOpenPolicy_MaxLazy = 0; - - ret = myMDBFactory->OpenFileStore(m_mdbEnv, NULL, oldFile, &inOpenPolicy, - &thumb); - } - else - ret = NS_MSG_ERROR_FOLDER_SUMMARY_OUT_OF_DATE; - } - NS_RELEASE(oldFile); // always release our file ref, store has own - } - } - if (NS_SUCCEEDED(ret) && thumb) - { - mdb_count outTotal; // total somethings to do in operation - mdb_count outCurrent; // subportion of total completed so far - mdb_bool outDone = PR_FALSE; // is operation finished? - mdb_bool outBroken; // is operation irreparably dead and broken? - do - { - ret = thumb->DoMore(m_mdbEnv, &outTotal, &outCurrent, &outDone, &outBroken); - if (ret != 0) - {// mork isn't really doing NS errors yet. - outDone = PR_TRUE; - break; - } - } - while (NS_SUCCEEDED(ret) && !outBroken && !outDone); -// m_mdbEnv->ClearErrors(); // ### temporary... - if (NS_SUCCEEDED(ret) && outDone) - { - ret = myMDBFactory->ThumbToOpenStore(m_mdbEnv, thumb, &m_mdbStore); - if (ret == NS_OK && m_mdbStore) - ret = InitExistingDB(); - } + nsresult ret=NS_OK; + nsIMdbFactory *myMDBFactory = GetMDBFactory(); + if (myMDBFactory) + { + ret = myMDBFactory->MakeEnv(nsnull, &m_mdbEnv); + if (NS_SUCCEEDED(ret)) + { + nsIMdbThumb *thumb = nsnull; + char *nativeFileName = nsCRT::strdup(dbName); + nsIMdbHeap* dbHeap = 0; + mdb_bool dbFrozen = mdbBool_kFalse; // not readonly, we want modifiable + + if (!nativeFileName) + return NS_ERROR_OUT_OF_MEMORY; + + if (m_mdbEnv) + m_mdbEnv->SetAutoClear(PR_TRUE); + if (exists) + { + mdbOpenPolicy inOpenPolicy; + mdb_bool canOpen; + mdbYarn outFormatVersion; + + nsIMdbFile* oldFile = 0; + ret = myMDBFactory->OpenOldFile(m_mdbEnv, dbHeap, nativeFileName, + dbFrozen, &oldFile); + if ( oldFile ) + { + if ( ret == NS_OK ) + { + ret = myMDBFactory->CanOpenFilePort(m_mdbEnv, oldFile, // file to investigate + &canOpen, &outFormatVersion); + if (ret == 0 && canOpen) + { + inOpenPolicy.mOpenPolicy_ScopePlan.mScopeStringSet_Count = 0; + inOpenPolicy.mOpenPolicy_MinMemory = 0; + inOpenPolicy.mOpenPolicy_MaxLazy = 0; + + ret = myMDBFactory->OpenFileStore(m_mdbEnv, NULL, oldFile, &inOpenPolicy, + &thumb); + } + else + ret = NS_MSG_ERROR_FOLDER_SUMMARY_OUT_OF_DATE; + } + NS_RELEASE(oldFile); // always release our file ref, store has own + } + } + if (NS_SUCCEEDED(ret) && thumb) + { + mdb_count outTotal; // total somethings to do in operation + mdb_count outCurrent; // subportion of total completed so far + mdb_bool outDone = PR_FALSE; // is operation finished? + mdb_bool outBroken; // is operation irreparably dead and broken? + do + { + ret = thumb->DoMore(m_mdbEnv, &outTotal, &outCurrent, &outDone, &outBroken); + if (ret != 0) + {// mork isn't really doing NS errors yet. + outDone = PR_TRUE; + break; + } + } + while (NS_SUCCEEDED(ret) && !outBroken && !outDone); +// m_mdbEnv->ClearErrors(); // ### temporary... + if (NS_SUCCEEDED(ret) && outDone) + { + ret = myMDBFactory->ThumbToOpenStore(m_mdbEnv, thumb, &m_mdbStore); + if (ret == NS_OK && m_mdbStore) + ret = InitExistingDB(); + } #ifdef DEBUG_bienvenu1 - DumpContents(); + DumpContents(); #endif - } - else // ### need error code saying why open file store failed - { - nsIMdbFile* newFile = 0; - ret = myMDBFactory->CreateNewFile(m_mdbEnv, dbHeap, dbName, &newFile); - if ( newFile ) - { - if (ret == NS_OK) - { - mdbOpenPolicy inOpenPolicy; - - inOpenPolicy.mOpenPolicy_ScopePlan.mScopeStringSet_Count = 0; - inOpenPolicy.mOpenPolicy_MinMemory = 0; - inOpenPolicy.mOpenPolicy_MaxLazy = 0; - - ret = myMDBFactory->CreateNewFileStore(m_mdbEnv, dbHeap, - newFile, &inOpenPolicy, &m_mdbStore); - if (ret == NS_OK) - ret = InitNewDB(); - } - NS_RELEASE(newFile); // always release our file ref, store has own - } - - } - NS_IF_RELEASE(thumb); - nsCRT::free(nativeFileName); - } - } - return ret; + } + else // ### need error code saying why open file store failed + { + nsIMdbFile* newFile = 0; + ret = myMDBFactory->CreateNewFile(m_mdbEnv, dbHeap, dbName, &newFile); + if ( newFile ) + { + if (ret == NS_OK) + { + mdbOpenPolicy inOpenPolicy; + + inOpenPolicy.mOpenPolicy_ScopePlan.mScopeStringSet_Count = 0; + inOpenPolicy.mOpenPolicy_MinMemory = 0; + inOpenPolicy.mOpenPolicy_MaxLazy = 0; + + ret = myMDBFactory->CreateNewFileStore(m_mdbEnv, dbHeap, + newFile, &inOpenPolicy, &m_mdbStore); + if (ret == NS_OK) + ret = InitNewDB(); + } + NS_RELEASE(newFile); // always release our file ref, store has own + } + + } + NS_IF_RELEASE(thumb); + nsCRT::free(nativeFileName); + } + } + return ret; } NS_IMETHODIMP nsMsgFolderCache::Init(nsIFileSpec *dbFileSpec) { - if (!dbFileSpec) - return NS_ERROR_NULL_POINTER; + if (!dbFileSpec) + return NS_ERROR_NULL_POINTER; - nsresult rv = NS_ERROR_OUT_OF_MEMORY; + nsresult rv = NS_ERROR_OUT_OF_MEMORY; - m_cacheElements = new nsSupportsHashtable; + m_cacheElements = new nsSupportsHashtable; - if (m_cacheElements) - { - rv = dbFileSpec->GetFileSpec(&m_dbFileSpec); - - if (NS_SUCCEEDED(rv)) - { - PRBool exists = m_dbFileSpec.Exists(); - // ### evil cast until MDB supports file streams. - rv = OpenMDB((const char *) m_dbFileSpec, exists); + if (m_cacheElements) + { + rv = dbFileSpec->GetFileSpec(&m_dbFileSpec); + + if (NS_SUCCEEDED(rv)) + { + PRBool exists = m_dbFileSpec.Exists(); + // ### evil cast until MDB supports file streams. + rv = OpenMDB((const char *) m_dbFileSpec, exists); // if this fails and panacea.dat exists, try blowing away the db and recreating it if (NS_FAILED(rv) && exists) { - if (m_mdbStore) - m_mdbStore->Release(); + if (m_mdbStore) + m_mdbStore->Release(); m_dbFileSpec.Delete(PR_FALSE); - rv = OpenMDB((const char *) m_dbFileSpec, PR_FALSE); + rv = OpenMDB((const char *) m_dbFileSpec, PR_FALSE); } - } - } - return rv; + } + } + return rv; } NS_IMETHODIMP nsMsgFolderCache::GetCacheElement(const char *pathKey, PRBool createIfMissing, @@ -338,7 +317,7 @@ if (!result || !pathKey || !m_cacheElements) return NS_ERROR_NULL_POINTER; - + if (!*pathKey) return NS_ERROR_FAILURE; @@ -406,94 +385,94 @@ NS_IMETHODIMP nsMsgFolderCache::Commit(PRBool compress) { - nsresult ret = NS_OK; + nsresult ret = NS_OK; - nsIMdbThumb *commitThumb = nsnull; - if (m_mdbStore) + nsIMdbThumb *commitThumb = nsnull; + if (m_mdbStore) if (compress) - ret = m_mdbStore->CompressCommit(GetEnv(), &commitThumb); + ret = m_mdbStore->CompressCommit(GetEnv(), &commitThumb); else ret = m_mdbStore->LargeCommit(GetEnv(), &commitThumb); - if (commitThumb) - { - mdb_count outTotal = 0; // total somethings to do in operation - mdb_count outCurrent = 0; // subportion of total completed so far - mdb_bool outDone = PR_FALSE; // is operation finished? - mdb_bool outBroken = PR_FALSE; // is operation irreparably dead and broken? - while (!outDone && !outBroken && ret == NS_OK) - { - ret = commitThumb->DoMore(GetEnv(), &outTotal, &outCurrent, &outDone, &outBroken); - } - NS_IF_RELEASE(commitThumb); - } - // ### do something with error, but clear it now because mork errors out on commits. - if (GetEnv()) - GetEnv()->ClearErrors(); - return ret; + if (commitThumb) + { + mdb_count outTotal = 0; // total somethings to do in operation + mdb_count outCurrent = 0; // subportion of total completed so far + mdb_bool outDone = PR_FALSE; // is operation finished? + mdb_bool outBroken = PR_FALSE; // is operation irreparably dead and broken? + while (!outDone && !outBroken && ret == NS_OK) + { + ret = commitThumb->DoMore(GetEnv(), &outTotal, &outCurrent, &outDone, &outBroken); + } + NS_IF_RELEASE(commitThumb); + } + // ### do something with error, but clear it now because mork errors out on commits. + if (GetEnv()) + GetEnv()->ClearErrors(); + return ret; } nsresult nsMsgFolderCache::AddCacheElement(const char *key, nsIMdbRow *row, nsIMsgFolderCacheElement **result) { - nsMsgFolderCacheElement *cacheElement = new nsMsgFolderCacheElement; + nsMsgFolderCacheElement *cacheElement = new nsMsgFolderCacheElement; - if (cacheElement) - { - cacheElement->SetMDBRow(row); - cacheElement->SetOwningCache(this); - nsCAutoString hashStrKey(key); - // if caller didn't pass in key, try to get it from row. - if (!key) - { - char *existingKey = nsnull; - cacheElement->GetStringProperty("key", &existingKey); - cacheElement->SetKey(existingKey); - hashStrKey = existingKey; - PR_Free(existingKey); - } - else - cacheElement->SetKey((char *) key); - nsCOMPtr supports(do_QueryInterface(cacheElement)); - if(supports) - { - nsCStringKey hashKey(hashStrKey); - m_cacheElements->Put(&hashKey, supports); - } - if (result) - { - *result = cacheElement; - NS_ADDREF(*result); - } - return NS_OK; - } - else - return NS_ERROR_OUT_OF_MEMORY; + if (cacheElement) + { + cacheElement->SetMDBRow(row); + cacheElement->SetOwningCache(this); + nsCAutoString hashStrKey(key); + // if caller didn't pass in key, try to get it from row. + if (!key) + { + char *existingKey = nsnull; + cacheElement->GetStringProperty("key", &existingKey); + cacheElement->SetKey(existingKey); + hashStrKey = existingKey; + PR_Free(existingKey); + } + else + cacheElement->SetKey((char *) key); + nsCOMPtr supports(do_QueryInterface(cacheElement)); + if(supports) + { + nsCStringKey hashKey(hashStrKey); + m_cacheElements->Put(&hashKey, supports); + } + if (result) + { + *result = cacheElement; + NS_ADDREF(*result); + } + return NS_OK; + } + else + return NS_ERROR_OUT_OF_MEMORY; } nsresult nsMsgFolderCache::RowCellColumnToCharPtr(nsIMdbRow *hdrRow, mdb_token columnToken, char **resultPtr) { - nsresult err = NS_OK; - nsIMdbCell *hdrCell; + nsresult err = NS_OK; + nsIMdbCell *hdrCell; + + if (hdrRow) // ### probably should be an error if hdrRow is NULL... + { + err = hdrRow->GetCell(GetEnv(), columnToken, &hdrCell); + if (err == NS_OK && hdrCell) + { + struct mdbYarn yarn; + hdrCell->AliasYarn(GetEnv(), &yarn); + char *result = (char *) PR_Malloc(yarn.mYarn_Fill + 1); + if (result) + { + memcpy(result, yarn.mYarn_Buf, yarn.mYarn_Fill); + result[yarn.mYarn_Fill] = '\0'; + } + else + err = NS_ERROR_OUT_OF_MEMORY; - if (hdrRow) // ### probably should be an error if hdrRow is NULL... - { - err = hdrRow->GetCell(GetEnv(), columnToken, &hdrCell); - if (err == NS_OK && hdrCell) - { - struct mdbYarn yarn; - hdrCell->AliasYarn(GetEnv(), &yarn); - char *result = (char *) PR_Malloc(yarn.mYarn_Fill + 1); - if (result) - { - memcpy(result, yarn.mYarn_Buf, yarn.mYarn_Fill); - result[yarn.mYarn_Fill] = '\0'; - } - else - err = NS_ERROR_OUT_OF_MEMORY; - - *resultPtr = result; - hdrCell->Release(); // always release ref - } - } - return err; + *resultPtr = result; + hdrCell->Release(); // always release ref + } + } + return err; } Index: mozilla/mailnews/base/src/nsMsgFolderDataSource.cpp =================================================================== RCS file: /cvsroot/mozilla/mailnews/base/src/nsMsgFolderDataSource.cpp,v retrieving revision 1.208 diff -u -r1.208 mozilla/mailnews/base/src/nsMsgFolderDataSource.cpp --- mozilla/mailnews/base/src/nsMsgFolderDataSource.cpp +++ mozilla/mailnews/base/src/nsMsgFolderDataSource.cpp @@ -384,25 +384,7 @@ return rv; } -NS_IMPL_ADDREF_INHERITED(nsMsgFolderDataSource, nsMsgRDFDataSource) -NS_IMPL_RELEASE_INHERITED(nsMsgFolderDataSource, nsMsgRDFDataSource) - -NS_IMETHODIMP -nsMsgFolderDataSource::QueryInterface(REFNSIID iid, void** result) -{ - if (! result) - return NS_ERROR_NULL_POINTER; - - *result = nsnull; - if(iid.Equals(NS_GET_IID(nsIFolderListener))) - { - *result = NS_STATIC_CAST(nsIFolderListener*, this); - NS_ADDREF(this); - return NS_OK; - } - else - return nsMsgRDFDataSource::QueryInterface(iid, result); -} +NS_IMPL_ISUPPORTS_INHERITED1(nsMsgFolderDataSource, nsIFolderListener, nsMsgRDFDataSource) // nsIRDFDataSource methods NS_IMETHODIMP nsMsgFolderDataSource::GetURI(char* *uri) @@ -1980,7 +1962,7 @@ nsCOMPtr firstFolder; rv = subFolders->CurrentItem(getter_AddRefs(firstFolder)); if (NS_SUCCEEDED(rv)) - firstFolder->QueryInterface(NS_GET_IID(nsIRDFResource), (void**)target); + rv = CallQueryInterface(firstFolder, target); } return NS_FAILED(rv) ? NS_RDF_NO_VALUE : rv; } @@ -2322,7 +2304,7 @@ nsCOMPtr allServers; rv = accountManager->GetAllServers(getter_AddRefs(allServers)); - nsCOMPtr allFolders = do_CreateInstance(NS_SUPPORTSARRAY_CONTRACTID, &rv);; + nsCOMPtr allFolders = do_CreateInstance(NS_SUPPORTSARRAY_CONTRACTID, &rv); if (NS_SUCCEEDED(rv) && allServers) { PRUint32 count = 0; @@ -2530,7 +2512,7 @@ nsCOMPtr allServers; rv = accountManager->GetAllServers(getter_AddRefs(allServers)); - nsCOMPtr allFolders = do_CreateInstance(NS_SUPPORTSARRAY_CONTRACTID, &rv);; + nsCOMPtr allFolders = do_CreateInstance(NS_SUPPORTSARRAY_CONTRACTID, &rv); if (NS_SUCCEEDED(rv) && allServers) { PRUint32 count = 0; Index: mozilla/mailnews/base/src/nsMsgGroupView.cpp =================================================================== RCS file: /cvsroot/mozilla/mailnews/base/src/nsMsgGroupView.cpp,v retrieving revision 1.36 diff -u -r1.36 mozilla/mailnews/base/src/nsMsgGroupView.cpp --- mozilla/mailnews/base/src/nsMsgGroupView.cpp +++ mozilla/mailnews/base/src/nsMsgGroupView.cpp @@ -773,7 +773,7 @@ nsMsgGroupThread *groupThread = (nsMsgGroupThread *) m_groupsTable.Get(hashKey); if (groupThread) - groupThread->QueryInterface(NS_GET_IID(nsIMsgThread), (void **) pThread); + CallQueryInterface(groupThread, pThread); delete hashKey; } else Index: mozilla/mailnews/base/src/nsSoundDatasource.cpp =================================================================== RCS file: /cvsroot/mozilla/mailnews/base/src/nsSoundDatasource.cpp,v retrieving revision 1.14 diff -u -r1.14 mozilla/mailnews/base/src/nsSoundDatasource.cpp --- mozilla/mailnews/base/src/nsSoundDatasource.cpp +++ mozilla/mailnews/base/src/nsSoundDatasource.cpp @@ -161,8 +161,8 @@ if (!name) return NS_RDF_NO_VALUE; - else - return name->QueryInterface(NS_GET_IID(nsIRDFNode), (void**) target); + + return CallQueryInterface(name, target); } else if (property == kNC_SoundURL.get()) { nsCOMPtr name; @@ -171,20 +171,18 @@ if (!name) return NS_RDF_NO_VALUE; - else - return name->QueryInterface(NS_GET_IID(nsIRDFNode), (void**) target); + + return CallQueryInterface(name, target); } else if (property == kNC_Child.get()) { - if (strcmp(value.get(),SOUND_ROOT) == 0) { - nsCOMPtr childResource; - rv = mRDFService->GetResource(NS_LITERAL_CSTRING(DEFAULT_SOUND_URL), - getter_AddRefs(childResource)); - NS_ENSURE_SUCCESS(rv,rv); - return childResource->QueryInterface(NS_GET_IID(nsIRDFNode), (void**) target); - } - else { + if (strcmp(value.get(),SOUND_ROOT) != 0) { return NS_RDF_NO_VALUE; - } + + nsCOMPtr childResource; + rv = mRDFService->GetResource(NS_LITERAL_CSTRING(DEFAULT_SOUND_URL), + getter_AddRefs(childResource)); + NS_ENSURE_SUCCESS(rv,rv); + return CallQueryInterface(childResource, target); } else { // do nothing Index: mozilla/mailnews/base/src/nsSubscribeDataSource.cpp =================================================================== RCS file: /cvsroot/mozilla/mailnews/base/src/nsSubscribeDataSource.cpp,v retrieving revision 1.22 diff -u -r1.22 mozilla/mailnews/base/src/nsSubscribeDataSource.cpp --- mozilla/mailnews/base/src/nsSubscribeDataSource.cpp +++ mozilla/mailnews/base/src/nsSubscribeDataSource.cpp @@ -184,7 +184,7 @@ if (!name) rv = NS_RDF_NO_VALUE; if (rv == NS_RDF_NO_VALUE) return(rv); - return name->QueryInterface(NS_GET_IID(nsIRDFNode), (void**) target); + return CallQueryInterface(name, target); } else if (property == kNC_Child.get()) { nsXPIDLCString childUri; @@ -195,8 +195,8 @@ nsCOMPtr childResource; rv = mRDFService->GetResource(childUri, getter_AddRefs(childResource)); NS_ENSURE_SUCCESS(rv,rv); - - return childResource->QueryInterface(NS_GET_IID(nsIRDFNode), (void**) target); + + return CallQueryInterface(childResource, target); } else if (property == kNC_Subscribed.get()) { PRBool isSubscribed; @@ -226,7 +226,7 @@ if (!serverType) rv = NS_RDF_NO_VALUE; if (rv == NS_RDF_NO_VALUE) return(rv); - return serverType->QueryInterface(NS_GET_IID(nsIRDFNode), (void**) target); + return CallQueryInterface(serverType, target); } else if (property == kNC_LeafName.get()) { nsXPIDLString leafNameStr; @@ -239,7 +239,7 @@ if (!leafName) rv = NS_RDF_NO_VALUE; if (rv == NS_RDF_NO_VALUE) return(rv); - return leafName->QueryInterface(NS_GET_IID(nsIRDFNode), (void**) target); + return CallQueryInterface(leafName, target); } else { // do nothing @@ -439,7 +439,7 @@ NS_ENSURE_SUCCESS(rv,rv); if (!incomingServer) return NS_ERROR_FAILURE; - rv = incomingServer->QueryInterface(NS_GET_IID(nsISubscribableServer), (void**)server); + rv = CallQueryInterface(incomingServer, server); NS_ENSURE_SUCCESS(rv,rv); if (!*server) return NS_ERROR_FAILURE; Index: mozilla/mailnews/base/util/nsMsgDBFolder.cpp =================================================================== RCS file: /cvsroot/mozilla/mailnews/base/util/nsMsgDBFolder.cpp,v retrieving revision 1.285 diff -u -r1.285 mozilla/mailnews/base/util/nsMsgDBFolder.cpp --- mozilla/mailnews/base/util/nsMsgDBFolder.cpp +++ mozilla/mailnews/base/util/nsMsgDBFolder.cpp @@ -713,7 +713,7 @@ mPath->GetFileSpec(&fileSpec); rv = NS_NewIOFileStream(getter_AddRefs(supports), fileSpec, PR_WRONLY | PR_CREATE_FILE, 00700); NS_ENSURE_SUCCESS(rv, rv); - supports->QueryInterface(NS_GET_IID(nsIOutputStream), (void **) outputStream); + CallQueryInterface(supports, outputStream); nsCOMPtr seekable = do_QueryInterface(supports); if (seekable) @@ -3857,8 +3857,7 @@ { if ((flag & mFlags) == flag) { - nsCOMPtr supports; - QueryInterface(NS_GET_IID(nsISupports), getter_AddRefs(supports)); + nsCOMPtr supports(do_QueryInterface(NS_ISUPPORTS_CAST(nsIMsgFolder*, this))); array->AppendElement(supports); } Index: mozilla/mailnews/base/util/nsMsgMailNewsUrl.cpp =================================================================== RCS file: /cvsroot/mozilla/mailnews/base/util/nsMsgMailNewsUrl.cpp,v retrieving revision 1.110 diff -u -r1.110 mozilla/mailnews/base/util/nsMsgMailNewsUrl.cpp --- mozilla/mailnews/base/util/nsMsgMailNewsUrl.cpp +++ mozilla/mailnews/base/util/nsMsgMailNewsUrl.cpp @@ -531,7 +531,7 @@ NS_IMETHODIMP nsMsgMailNewsUrl::GetBaseURI(nsIURI **aBaseURI) { NS_ENSURE_ARG_POINTER(aBaseURI); - return m_baseURL->QueryInterface(NS_GET_IID(nsIURI), (void**) aBaseURI); + return CallQueryInterface(m_baseURL, aBaseURI); } NS_IMETHODIMP nsMsgMailNewsUrl::Equals(nsIURI *other, PRBool *_retval) @@ -1000,7 +1000,7 @@ { NS_ENSURE_ARG_POINTER(aSaveListener); nsMsgSaveAsListener *saveAsListener = new nsMsgSaveAsListener(aFileSpec, addDummyEnvelope); - return saveAsListener->QueryInterface(NS_GET_IID(nsIStreamListener), (void **) aSaveListener); + return CallQueryInterface(saveAsListener, aSaveListener); } Index: mozilla/mailnews/base/util/nsMsgUtils.cpp =================================================================== RCS file: /cvsroot/mozilla/mailnews/base/util/nsMsgUtils.cpp,v retrieving revision 1.120 diff -u -r1.120 mozilla/mailnews/base/util/nsMsgUtils.cpp --- mozilla/mailnews/base/util/nsMsgUtils.cpp +++ mozilla/mailnews/base/util/nsMsgUtils.cpp @@ -150,22 +150,19 @@ nsCOMPtr imapUrl = do_CreateInstance(kImapUrlCID, &rv); if (NS_SUCCEEDED(rv) && imapUrl) - rv = imapUrl->QueryInterface(NS_GET_IID(nsIURI), - (void**) aUrl); + rv = CallQueryInterface(imapUrl, aUrl); } else if (PL_strncasecmp(uri, "mailbox", 7) == 0) { nsCOMPtr mailboxUrl = do_CreateInstance(kCMailboxUrl, &rv); if (NS_SUCCEEDED(rv) && mailboxUrl) - rv = mailboxUrl->QueryInterface(NS_GET_IID(nsIURI), - (void**) aUrl); + rv = CallQueryInterface(mailboxUrl, aUrl); } else if (PL_strncasecmp(uri, "news", 4) == 0) { nsCOMPtr nntpUrl = do_CreateInstance(kCNntpUrlCID, &rv); if (NS_SUCCEEDED(rv) && nntpUrl) - rv = nntpUrl->QueryInterface(NS_GET_IID(nsIURI), - (void**) aUrl); + rv = CallQueryInterface(nntpUrl, aUrl); } if (*aUrl) (*aUrl)->SetSpec(nsDependentCString(uri)); Index: mozilla/mailnews/compose/src/nsMsgAttachmentHandler.cpp =================================================================== RCS file: /cvsroot/mozilla/mailnews/compose/src/nsMsgAttachmentHandler.cpp,v retrieving revision 1.120 diff -u -r1.120 mozilla/mailnews/compose/src/nsMsgAttachmentHandler.cpp --- mozilla/mailnews/compose/src/nsMsgAttachmentHandler.cpp +++ mozilla/mailnews/compose/src/nsMsgAttachmentHandler.cpp @@ -583,8 +583,7 @@ nsCAutoString uri(m_uri); uri += (uri.FindChar('?') == kNotFound) ? "?" : "&"; uri.Append("fetchCompleteMessage=true"); - nsCOMPtr strListener; - fetcher->QueryInterface(NS_GET_IID(nsIStreamListener), getter_AddRefs(strListener)); + nsCOMPtr strListener(do_QueryInterface(fetcher)); // initialize a new stream converter, that uses the strListener as its input // obtain the input stream listener from the new converter, Index: mozilla/mailnews/compose/src/nsMsgCompFields.cpp =================================================================== RCS file: /cvsroot/mozilla/mailnews/compose/src/nsMsgCompFields.cpp,v retrieving revision 1.83 diff -u -r1.83 mozilla/mailnews/compose/src/nsMsgCompFields.cpp --- mozilla/mailnews/compose/src/nsMsgCompFields.cpp +++ mozilla/mailnews/compose/src/nsMsgCompFields.cpp @@ -515,7 +515,7 @@ PRBool sameUrl; for (i = 0; i < attachmentCount; i ++) { - m_attachments->QueryElementAt(i, NS_GET_IID(nsIMsgAttachment), getter_AddRefs(element)); + element = do_QueryElementAt(m_attachments, i); if (element) { element->EqualsUrl(attachment, &sameUrl); @@ -538,7 +538,7 @@ PRBool sameUrl; for (i = 0; i < attachmentCount; i ++) { - m_attachments->QueryElementAt(i, NS_GET_IID(nsIMsgAttachment), getter_AddRefs(element)); + element = do_QueryElementAt(m_attachments, i); if (element) { element->EqualsUrl(attachment, &sameUrl); @@ -582,7 +582,7 @@ if (! pAddrArray) return NS_ERROR_OUT_OF_MEMORY; - rv = pAddrArray->QueryInterface(NS_GET_IID(nsIMsgRecipientArray), (void **)_retval); + rv = CallQueryInterface(pAddrArray, _retval); if (NS_SUCCEEDED(rv)) { nsCOMPtr parser = do_GetService(NS_MAILNEWS_MIME_HEADER_PARSER_CONTRACTID); @@ -654,7 +654,7 @@ pAddrsArray = new nsMsgRecipientArray; if (! pAddrsArray) return NS_ERROR_OUT_OF_MEMORY; - rv = pAddrsArray->QueryInterface(NS_GET_IID(nsIMsgRecipientArray), (void **)fullAddrsArray); + rv = CallQueryInterface(pAddrsArray, fullAddrsArray); if (NS_FAILED(rv)) return rv; } @@ -666,7 +666,7 @@ pEmailsArray = new nsMsgRecipientArray; if (! pEmailsArray) return NS_ERROR_OUT_OF_MEMORY; - rv = pEmailsArray->QueryInterface(NS_GET_IID(nsIMsgRecipientArray), (void **)emailsArray); + rv = CallQueryInterface(pEmailsArray, emailsArray); if (NS_FAILED(rv)) return rv; } Index: mozilla/mailnews/compose/src/nsMsgComposeService.cpp =================================================================== RCS file: /cvsroot/mozilla/mailnews/compose/src/nsMsgComposeService.cpp,v retrieving revision 1.124 diff -u -r1.124 mozilla/mailnews/compose/src/nsMsgComposeService.cpp --- mozilla/mailnews/compose/src/nsMsgComposeService.cpp +++ mozilla/mailnews/compose/src/nsMsgComposeService.cpp @@ -523,8 +523,7 @@ nsresult rv = NS_OK; if (aURI) { - nsCOMPtr aMailtoUrl; - rv = aURI->QueryInterface(NS_GET_IID(nsIMailtoUrl), getter_AddRefs(aMailtoUrl)); + nsCOMPtr aMailtoUrl(do_QueryInterface(aURI, &rv)); if (NS_SUCCEEDED(rv)) { MSG_ComposeFormat requestedComposeFormat = nsIMsgCompFormat::Default; @@ -1111,8 +1110,7 @@ rv = GetMessageServiceFromURI(templateMsgHdrUri, getter_AddRefs(msgService)); NS_ENSURE_SUCCESS(rv, rv); - nsCOMPtr listenerSupports; - helper->QueryInterface(NS_GET_IID(nsISupports), getter_AddRefs(listenerSupports)); + nsCOMPtr listenerSupports(do_QueryInterface(helper)); return msgService->StreamMessage(templateMsgHdrUri, listenerSupports, aMsgWindow, helper, PR_FALSE /* convert data */, @@ -1486,7 +1484,7 @@ // Now, just plug the two together and get the hell out of the way! nsCOMPtr streamListener = do_QueryInterface(mimeConverter); - return messageService->DisplayMessage(nsPromiseFlatCString(aMsgURI).get(), streamListener, aMsgWindow, nsnull, mailCharset, nsnull);; + return messageService->DisplayMessage(nsPromiseFlatCString(aMsgURI).get(), streamListener, aMsgWindow, nsnull, mailCharset, nsnull); } #ifdef MOZ_XUL_APP Index: mozilla/mailnews/compose/src/nsMsgQuote.cpp =================================================================== RCS file: /cvsroot/mozilla/mailnews/compose/src/nsMsgQuote.cpp,v retrieving revision 1.73 diff -u -r1.73 mozilla/mailnews/compose/src/nsMsgQuote.cpp --- mozilla/mailnews/compose/src/nsMsgQuote.cpp +++ mozilla/mailnews/compose/src/nsMsgQuote.cpp @@ -202,11 +202,7 @@ if (NS_FAILED(rv)) return rv; mQuoteListener->SetMsgQuote(this); - // funky magic go get the isupports for this class which inherits from multiple interfaces. - nsISupports * supports; - QueryInterface(NS_GET_IID(nsISupports), (void **) &supports); - nsCOMPtr quoteSupport = supports; - NS_IF_RELEASE(supports); + nsCOMPtr quoteSupport(NS_ISUPPORTS_CAST(nsIMsgQuote*, this)); // now we want to create a necko channel for this url and we want to open it mQuoteChannel = nsnull; Index: mozilla/mailnews/compose/src/nsMsgSend.cpp =================================================================== RCS file: /cvsroot/mozilla/mailnews/compose/src/nsMsgSend.cpp,v retrieving revision 1.386 diff -u -r1.386 mozilla/mailnews/compose/src/nsMsgSend.cpp --- mozilla/mailnews/compose/src/nsMsgSend.cpp +++ mozilla/mailnews/compose/src/nsMsgSend.cpp @@ -1473,7 +1473,7 @@ if (ownerDocument) { nsIDocument *doc = nsnull; - if (NS_FAILED(ownerDocument->QueryInterface(NS_GET_IID(nsIDocument),(void**)&doc)) || !doc) + if (NS_FAILED(CallQueryInterface(ownerDocument, &doc)) || !doc) return NS_ERROR_OUT_OF_MEMORY; nsCAutoString spec; @@ -1653,7 +1653,7 @@ // now we need to get the element in the array and do the magic // to process this element. // - mEmbeddedObjectList->QueryElementAt(i, NS_GET_IID(nsIDOMNode), getter_AddRefs(node)); + node = do_QueryElementAt(mEmbeddedObjectList, i); if (!node) continue; @@ -1975,7 +1975,7 @@ // to process this element. // - mEmbeddedObjectList->QueryElementAt(locCount, NS_GET_IID(nsIDOMNode), getter_AddRefs(node)); + node = do_QueryElementAt(mEmbeddedObjectList, locCount); if (!node) return NS_ERROR_MIME_MPART_ATTACHMENT_ERROR; @@ -2199,7 +2199,7 @@ nsXPIDLCString url; for (i = 0; i < attachmentCount; i ++) { - attachmentsArray->QueryElementAt(i, NS_GET_IID(nsIMsgAttachment), getter_AddRefs(element)); + element = do_QueryElementAt(attachmentsArray, i); if (element) { element->GetUrl(getter_Copies(url)); @@ -2254,7 +2254,7 @@ nsXPIDLCString url; for (i = 0; i < attachmentCount; i ++) { - attachmentsArray->QueryElementAt(i, NS_GET_IID(nsIMsgAttachment), getter_AddRefs(element)); + element = do_QueryElementAt(attachmentsArray, i); if (element) { element->GetUrl(getter_Copies(url)); @@ -2426,7 +2426,7 @@ nsXPIDLCString url; for (i = 0; i < attachmentCount; i ++) { - attachmentsArray->QueryElementAt(i, NS_GET_IID(nsIMsgAttachment), getter_AddRefs(element)); + element = do_QueryElementAt(attachmentsArray, i); if (element) { element->GetUrl(getter_Copies(url)); @@ -3048,7 +3048,7 @@ nsCOMPtr element; for (i = 0; i < attachmentCount; i ++) { - srcAttachmentArray->QueryElementAt(i, NS_GET_IID(nsIMsgAttachment), getter_AddRefs(element)); + element = do_QueryElementAt(srcAttachmentsArray, i); if (element) mCompFields->AddAttachment(element); } Index: mozilla/mailnews/compose/src/nsSmtpService.cpp =================================================================== RCS file: /cvsroot/mozilla/mailnews/compose/src/nsSmtpService.cpp,v retrieving revision 1.138 diff -u -r1.138 mozilla/mailnews/compose/src/nsSmtpService.cpp --- mozilla/mailnews/compose/src/nsSmtpService.cpp +++ mozilla/mailnews/compose/src/nsSmtpService.cpp @@ -246,7 +246,7 @@ if (aStatusFeedback) url->SetStatusFeedback(aStatusFeedback); } - rv = smtpUrl->QueryInterface(NS_GET_IID(nsIURI), (void **) aUrl); + rv = CallQueryInterface(smtpUrl, aUrl); } return rv; @@ -273,7 +273,7 @@ NS_ADDREF(smtpProtocol); rv = smtpProtocol->LoadUrl(aUrl, aConsumer); // protocol will get destroyed when url is completed... - smtpProtocol->QueryInterface(NS_GET_IID(nsIRequest), (void **) aRequest); + CallQueryInterface(smtpProtocol, aRequest); NS_RELEASE(smtpProtocol); } @@ -338,7 +338,7 @@ mailtoUrl->SetSpec(utf8Spec); else mailtoUrl->SetSpec(aSpec); - rv = mailtoUrl->QueryInterface(NS_GET_IID(nsIURI), (void **) _retval); + rv = CallQueryInterface(mailtoUrl, aRetval); } return rv; } @@ -620,10 +620,8 @@ // (which will add it to the array & prefs anyway) if (count == 0) return nsnull;//if there are no smtp servers then don't create one for the default. - else - rv = mSmtpServers->QueryElementAt(0, NS_GET_IID(nsISmtpServer), - (void **)getter_AddRefs(mDefaultSmtpServer)); + mDefaultSmtpServer = do_QueryElementAt(mSmtpServers, 0, &rv); if (NS_FAILED(rv)) return rv; NS_ENSURE_TRUE(mDefaultSmtpServer, NS_ERROR_UNEXPECTED); Index: mozilla/mailnews/compose/src/nsURLFetcher.cpp =================================================================== RCS file: /cvsroot/mozilla/mailnews/compose/src/nsURLFetcher.cpp,v retrieving revision 1.73 diff -u -r1.73 mozilla/mailnews/compose/src/nsURLFetcher.cpp --- mozilla/mailnews/compose/src/nsURLFetcher.cpp +++ mozilla/mailnews/compose/src/nsURLFetcher.cpp @@ -142,16 +142,16 @@ NS_IMETHODIMP nsURLFetcher::DoContent(const char * aContentType, - PRBool aIsContentPreferred, - nsIRequest *request, - nsIStreamListener ** aContentHandler, - PRBool * aAbortProcess) + PRBool aIsContentPreferred, + nsIRequest *request, + nsIStreamListener ** aContentHandler, + PRBool * aAbortProcess) { nsresult rv = NS_OK; if (aAbortProcess) *aAbortProcess = PR_FALSE; - QueryInterface(NS_GET_IID(nsIStreamListener), (void **) aContentHandler); + CallQueryInterface(NS_ISUPPORTS_CAST(nsIStreamListener*, this), aContentHandler); /* Check the content-type to see if we need to insert a converter Index: mozilla/mailnews/extensions/bayesian-spam-filter/src/nsBayesianFilter.cpp =================================================================== RCS file: /cvsroot/mozilla/mailnews/extensions/bayesian-spam-filter/src/nsBayesianFilter.cpp,v retrieving revision 1.59 diff -u -r1.59 mozilla/mailnews/extensions/bayesian-spam-filter/src/nsBayesianFilter.cpp --- mozilla/mailnews/extensions/bayesian-spam-filter/src/nsBayesianFilter.cpp +++ mozilla/mailnews/extensions/bayesian-spam-filter/src/nsBayesianFilter.cpp @@ -1457,7 +1457,7 @@ rv = profileDir->Append(NS_LITERAL_STRING("training.dat")); NS_ENSURE_SUCCESS(rv, rv); - return profileDir->QueryInterface(NS_GET_IID(nsILocalFile), (void **) aTrainingFile); + return CallQueryInterface(profileDir, aTrainingFile); } static const char kMagicCookie[] = { '\xFE', '\xED', '\xFA', '\xCE' }; Index: mozilla/mailnews/extensions/palmsync/src/nsPalmSyncSupport.cpp =================================================================== RCS file: /cvsroot/mozilla/mailnews/extensions/palmsync/src/nsPalmSyncSupport.cpp,v retrieving revision 1.9 diff -u -r1.9 mozilla/mailnews/extensions/palmsync/src/nsPalmSyncSupport.cpp --- mozilla/mailnews/extensions/palmsync/src/nsPalmSyncSupport.cpp +++ mozilla/mailnews/extensions/palmsync/src/nsPalmSyncSupport.cpp @@ -191,7 +191,7 @@ rv = installLocation->GetItemFile(NS_LITERAL_STRING(EXTENSION_ID), NS_LITERAL_STRING(EXECUTABLE_FILENAME), getter_AddRefs(palmSyncInstallExe)); NS_ENSURE_SUCCESS(rv, rv); - palmSyncInstallExe->QueryInterface(NS_GET_IID(nsILocalFile), (void **) aLocalFile); + CallQueryInterface(palmSyncInstallExe, aLocalFile); return rv; } Index: mozilla/mailnews/imap/src/nsImapIncomingServer.cpp =================================================================== RCS file: /cvsroot/mozilla/mailnews/imap/src/nsImapIncomingServer.cpp,v retrieving revision 1.358 diff -u -r1.358 mozilla/mailnews/imap/src/nsImapIncomingServer.cpp --- mozilla/mailnews/imap/src/nsImapIncomingServer.cpp +++ mozilla/mailnews/imap/src/nsImapIncomingServer.cpp @@ -2475,8 +2475,8 @@ m_logonRedirector = do_GetService(contractID.get(), &rv); if (m_logonRedirector && NS_SUCCEEDED(rv)) { - nsCOMPtr logonRedirectorRequester; - rv = QueryInterface(NS_GET_IID(nsIMsgLogonRedirectionRequester), getter_AddRefs(logonRedirectorRequester)); + nsCOMPtr logonRedirectorRequester = + do_QueryInterface(NS_ISUPPORTS_CAST(nsIMsgLogonRedirectionRequester*, this)); if (NS_SUCCEEDED(rv)) { nsXPIDLCString password; Index: mozilla/mailnews/imap/src/nsImapMailFolder.cpp =================================================================== RCS file: /cvsroot/mozilla/mailnews/imap/src/nsImapMailFolder.cpp,v retrieving revision 1.738 diff -u -r1.738 mozilla/mailnews/imap/src/nsImapMailFolder.cpp --- mozilla/mailnews/imap/src/nsImapMailFolder.cpp +++ mozilla/mailnews/imap/src/nsImapMailFolder.cpp @@ -2316,8 +2316,7 @@ PRUint32 count = 0; rv = messages->Count(&count); - rv = QueryInterface(NS_GET_IID(nsIMsgFolder), - getter_AddRefs(srcFolder)); + srcFolder = QueryInterface(NS_ISUPPORTS_CAST(nsIMsgFolder*, this), &rv); nsCOMPtr copyService = do_GetService(NS_MSGCOPYSERVICE_CONTRACTID, &rv); NS_ENSURE_SUCCESS(rv, rv); @@ -3248,8 +3247,7 @@ do_GetService(NS_IMAPSERVICE_CONTRACTID, &rv); NS_ENSURE_SUCCESS(rv,rv); - rv = QueryInterface(NS_GET_IID(nsIUrlListener), - getter_AddRefs(urlListener)); + urlListener = QueryInterface(NS_ISUPPORTS_CAST(nsIUrlListener*, this), &rv); nsCOMPtr copySupport; if (m_copyState) copySupport = do_QueryInterface(m_copyState); @@ -3323,8 +3321,7 @@ for (PRUint32 actionIndex = 0; actionIndex < numActions; actionIndex++) { - nsCOMPtr filterAction; - filterActionList->QueryElementAt(actionIndex, NS_GET_IID(nsIMsgRuleAction), getter_AddRefs(filterAction)); + nsCOMPtr filterAction(do_QueryElementAt(filterActionList, actionIndex)); if (!filterAction) continue; if (NS_SUCCEEDED(filterAction->GetType(&actionType))) @@ -4856,7 +4853,7 @@ nsMsgKeyArray srcKeyArray; if (m_copyState->m_allowUndo) { - rv = m_copyState->m_undoMsgTxn->QueryInterface(NS_GET_IID(nsImapMoveCopyMsgTxn), getter_AddRefs(msgTxn)); + msgTxn = do_QueryInterface(m_copyState->m_undoMsgTxn, &rv); if (msgTxn) msgTxn->GetSrcKeyArray(srcKeyArray); } @@ -5177,7 +5174,7 @@ do_QueryInterface(copyState, &rv); if (NS_FAILED(rv)) return rv; if (mailCopyState->m_undoMsgTxn) - rv = mailCopyState->m_undoMsgTxn->QueryInterface(NS_GET_IID(nsImapMoveCopyMsgTxn), getter_AddRefs(msgTxn)); + msgTxn = do_QueryInterface(mailCopyState->m_undoMsgTxn, &rv); } if (msgTxn) msgTxn->SetCopyResponseUid(msgIdString); @@ -5296,8 +5293,8 @@ if (mailCopyState->m_undoMsgTxn) // CopyMessages() { - nsRefPtr msgTxn; - rv = mailCopyState->m_undoMsgTxn->QueryInterface(NS_GET_IID(nsImapMoveCopyMsgTxn), getter_AddRefs(msgTxn)); + nsRefPtr msgTxn(do_QueryInterface(mailCopyState->m_undoMsgTxn, &rv)); + if (NS_SUCCEEDED(rv)) msgTxn->AddDstKey(aKey); } @@ -6351,9 +6348,8 @@ { nsCAutoString messageIds; nsMsgKeyArray srcKeyArray; - nsCOMPtr urlListener; + nsCOMPtr urlListener(do_QueryInterface(NS_ISUPPORTS_CAST(nsIUrlListener*, this))); - rv = QueryInterface(NS_GET_IID(nsIUrlListener), getter_AddRefs(urlListener)); rv = BuildIdsAndKeyArray(messages, messageIds, srcKeyArray); nsImapMoveCopyMsgTxn* undoMsgTxn = new nsImapMoveCopyMsgTxn; @@ -6376,9 +6372,7 @@ undoMsgTxn->SetTransactionType(nsIMessenger::eCopyMsg); } - rv = undoMsgTxn->QueryInterface( - NS_GET_IID(nsImapMoveCopyMsgTxn), - getter_AddRefs(m_copyState->m_undoMsgTxn) ); + m_copyState->m_undoMsgTxn = do_QueryInterface(undoMsgTxn); } nsCOMPtr aMessage; aMessage = do_QueryElementAt(messages, 0, &rv); @@ -6664,7 +6658,7 @@ sourceOp->GetOperation(&opType); srcKeyArray.Add(originalKey); - rv = QueryInterface(NS_GET_IID(nsIUrlListener), getter_AddRefs(urlListener)); + urlListener = do_QueryInterface(NS_ISUPPORTS_CAST(nsIUrlListener*, this)); nsImapOfflineTxn *undoMsgTxn = new nsImapOfflineTxn(srcFolder, &srcKeyArray, this, isMove, opType, message, m_thread, urlListener); @@ -6733,9 +6727,7 @@ destOp->SetSourceFolderURI(originalSrcFolderURI); destOp->SetMessageKey(originalKey); { - nsCOMPtr urlListener; - - QueryInterface(NS_GET_IID(nsIUrlListener), getter_AddRefs(urlListener)); + nsCOMPtr urlListener(do_QueryInterface(NS_ISUPPORTS_CAST(nsIUrlListener*, this))); nsMsgKeyArray keyArray; keyArray.Add(fakeBase + sourceKeyIndex); nsImapOfflineTxn *undoMsgTxn = new @@ -6763,7 +6755,7 @@ nsCOMPtr urlListener; srcKeyArray.Add(msgKey); - rv = QueryInterface(NS_GET_IID(nsIUrlListener), getter_AddRefs(urlListener)); + urlListener = do_QueryInterface(NS_ISUPPORTS_CAST(nsIUrlListener*, this)); nsOfflineImapOperationType opType = nsIMsgOfflineImapOperation::kDeletedMsg; if (!deleteToTrash) @@ -6922,7 +6914,7 @@ rv = BuildIdsAndKeyArray(messages, messageIds, srcKeyArray); if(NS_FAILED(rv)) goto done; - rv = QueryInterface(NS_GET_IID(nsIUrlListener), getter_AddRefs(urlListener)); + urlListener = do_QueryInterface(NS_ISUPPORTS_CAST(nsIUrlListener*, this)); rv = InitCopyState(srcSupport, messages, isMove, PR_TRUE, PR_FALSE, /* newMsgFlags, not used */0, listener, msgWindow, allowUndo); @@ -6962,9 +6954,7 @@ { undoMsgTxn->SetTransactionType(nsIMessenger::eCopyMsg); } - rv = undoMsgTxn->QueryInterface( - NS_GET_IID(nsImapMoveCopyMsgTxn), - getter_AddRefs(m_copyState->m_undoMsgTxn) ); + m_copyState->m_undoMsgTxn = do_QueryInterface(undoMsgTxn, &rv); } else NS_ASSERTION(PR_FALSE, "online copy failed"); @@ -7367,7 +7357,7 @@ if (NS_FAILED(rv)) return OnCopyCompleted(srcSupport, rv); - rv = QueryInterface(NS_GET_IID(nsIUrlListener), getter_AddRefs(urlListener)); + urlListener = do_QueryInterface(NS_ISUPPORTS_CAST(nsIUrlListener*, this)); if (msgToReplace) { @@ -7801,7 +7791,7 @@ if (onlineName.Equals(targetOnlineName)) { - return QueryInterface(NS_GET_IID(nsIMsgImapMailFolder), (void **) aResultFolder); + return CallQueryInterface(NS_ISUPPORTS_CAST(nsIMsgImapMailFolder*, this), aResultFolder); } nsCOMPtr aEnumerator; GetSubFolders(getter_AddRefs(aEnumerator)); @@ -8646,7 +8636,7 @@ identity->GetEmail(getter_Copies(identityEmail)); if (identityEmail.Equals(otherUsersEmailAddress)) { - retIdentity = identity;; + retIdentity = identity; break; } } Index: mozilla/mailnews/imap/src/nsImapProtocol.cpp =================================================================== RCS file: /cvsroot/mozilla/mailnews/imap/src/nsImapProtocol.cpp,v retrieving revision 1.639 diff -u -r1.639 mozilla/mailnews/imap/src/nsImapProtocol.cpp --- mozilla/mailnews/imap/src/nsImapProtocol.cpp +++ mozilla/mailnews/imap/src/nsImapProtocol.cpp @@ -1,4 +1,4 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * @@ -144,10 +144,10 @@ NS_IMETHODIMP nsMsgImapHdrXferInfo::GetHeader(PRInt32 hdrIndex, nsIImapHeaderInfo **aResult) { - if (m_hdrInfos) - return m_hdrInfos->QueryElementAt(hdrIndex, NS_GET_IID(nsIImapHeaderInfo), (void **) aResult); - else + if (!m_hdrInfos) return NS_ERROR_OUT_OF_MEMORY; + + return m_hdrInfos->QueryElementAt(hdrIndex, NS_GET_IID(nsIImapHeaderInfo), (void **) aResult); } static const PRInt32 kInitLineHdrCacheSize = 512; // should be about right @@ -206,24 +206,24 @@ // **** helper class for downloading line **** nsMsgImapLineDownloadCache::nsMsgImapLineDownloadCache() { - fLineInfo = (msg_line_info *) PR_CALLOC(sizeof( msg_line_info)); - fLineInfo->uidOfMessage = nsMsgKey_None; - m_msgSize = 0; + fLineInfo = (msg_line_info *) PR_CALLOC(sizeof( msg_line_info)); + fLineInfo->uidOfMessage = nsMsgKey_None; + m_msgSize = 0; } nsMsgImapLineDownloadCache::~nsMsgImapLineDownloadCache() { - PR_Free( fLineInfo); + PR_Free( fLineInfo); } PRUint32 nsMsgImapLineDownloadCache::CurrentUID() { - return fLineInfo->uidOfMessage; + return fLineInfo->uidOfMessage; } PRUint32 nsMsgImapLineDownloadCache::SpaceAvailable() { - return kDownLoadCacheSize - m_bufferPos; + return kDownLoadCacheSize - m_bufferPos; } msg_line_info *nsMsgImapLineDownloadCache::GetCurrentLineInfo() @@ -235,58 +235,58 @@ NS_IMETHODIMP nsMsgImapLineDownloadCache::ResetCache() { - ResetWritePos(); - return NS_OK; + ResetWritePos(); + return NS_OK; } PRBool nsMsgImapLineDownloadCache::CacheEmpty() { - return m_bufferPos == 0; + return m_bufferPos == 0; } NS_IMETHODIMP nsMsgImapLineDownloadCache::CacheLine(const char *line, PRUint32 uid) { - NS_ASSERTION((PL_strlen(line) + 1) <= SpaceAvailable(), - "Oops... line length greater than space available"); + NS_ASSERTION((PL_strlen(line) + 1) <= SpaceAvailable(), + "Oops... line length greater than space available"); - fLineInfo->uidOfMessage = uid; + fLineInfo->uidOfMessage = uid; - AppendString(line); - return NS_OK; + AppendString(line); + return NS_OK; } /* attribute nsMsgKey msgUid; */ NS_IMETHODIMP nsMsgImapLineDownloadCache::GetMsgUid(nsMsgKey *aMsgUid) { - *aMsgUid = fLineInfo->uidOfMessage; - return NS_OK; + *aMsgUid = fLineInfo->uidOfMessage; + return NS_OK; } NS_IMETHODIMP nsMsgImapLineDownloadCache::SetMsgUid(nsMsgKey aMsgUid) { - fLineInfo->uidOfMessage = aMsgUid; - return NS_OK; + fLineInfo->uidOfMessage = aMsgUid; + return NS_OK; } /* attribute long msgSize; */ NS_IMETHODIMP nsMsgImapLineDownloadCache::GetMsgSize(PRInt32 *aMsgSize) { - *aMsgSize = m_msgSize; - return NS_OK; + *aMsgSize = m_msgSize; + return NS_OK; } NS_IMETHODIMP nsMsgImapLineDownloadCache::SetMsgSize(PRInt32 aMsgSize) { - m_msgSize = aMsgSize; - return NS_OK; + m_msgSize = aMsgSize; + return NS_OK; } /* attribute string msgHdrs; */ NS_IMETHODIMP nsMsgImapLineDownloadCache::GetMsgHdrs(const char **aMsgHdrs) { // this doesn't copy the string - AppendBuffer("", 1); // null terminate the buffer - *aMsgHdrs = GetBuffer(); - return NS_OK; + AppendBuffer("", 1); // null terminate the buffer + *aMsgHdrs = GetBuffer(); + return NS_OK; } /* the following macros actually implement addref, release and query interface for our component. */ @@ -321,36 +321,36 @@ nsresult nsImapProtocol::GlobalInitialization() { - gInitialized = PR_TRUE; - nsresult rv; - nsCOMPtr prefBranch(do_GetService(NS_PREFSERVICE_CONTRACTID, &rv)); - NS_ENSURE_SUCCESS(rv, rv); - - prefBranch->GetIntPref("mail.imap.chunk_fast", &gTooFastTime); // secs we read too little too fast - prefBranch->GetIntPref("mail.imap.chunk_ideal", &gIdealTime); // secs we read enough in good time - prefBranch->GetIntPref("mail.imap.chunk_add", &gChunkAddSize); // buffer size to add when wasting time - prefBranch->GetIntPref("mail.imap.chunk_size", &gChunkSize); - prefBranch->GetIntPref("mail.imap.min_chunk_size_threshold", &gChunkThreshold); - prefBranch->GetIntPref("mail.imap.max_chunk_size", &gMaxChunkSize); - prefBranch->GetBoolPref("mail.imap.hide_other_users", - &gHideOtherUsersFromList); - prefBranch->GetBoolPref("mail.imap.hide_unused_namespaces", - &gHideUnusedNamespaces); - prefBranch->GetIntPref("mail.imap.noop_check_count", &gPromoteNoopToCheckCount); - prefBranch->GetBoolPref("mail.imap.use_envelope_cmd", - &gUseEnvelopeCmd); - prefBranch->GetBoolPref("mail.imap.use_literal_plus", &gUseLiteralPlus); - prefBranch->GetBoolPref("mail.imap.expunge_after_delete", &gExpungeAfterDelete); - prefBranch->GetBoolPref("mail.imap.check_deleted_before_expunge", &gCheckDeletedBeforeExpunge); - prefBranch->GetIntPref("mailnews.tcptimeout", &gResponseTimeout); - nsXPIDLCString customDBHeaders; - prefBranch->GetCharPref("mailnews.customDBHeaders", getter_Copies(customDBHeaders)); - gCustomDBHeaders.ParseString(customDBHeaders, ", "); - return NS_OK; + gInitialized = PR_TRUE; + nsresult rv; + nsCOMPtr prefBranch(do_GetService(NS_PREFSERVICE_CONTRACTID, &rv)); + NS_ENSURE_SUCCESS(rv, rv); + + prefBranch->GetIntPref("mail.imap.chunk_fast", &gTooFastTime); // secs we read too little too fast + prefBranch->GetIntPref("mail.imap.chunk_ideal", &gIdealTime); // secs we read enough in good time + prefBranch->GetIntPref("mail.imap.chunk_add", &gChunkAddSize); // buffer size to add when wasting time + prefBranch->GetIntPref("mail.imap.chunk_size", &gChunkSize); + prefBranch->GetIntPref("mail.imap.min_chunk_size_threshold", &gChunkThreshold); + prefBranch->GetIntPref("mail.imap.max_chunk_size", &gMaxChunkSize); + prefBranch->GetBoolPref("mail.imap.hide_other_users", + &gHideOtherUsersFromList); + prefBranch->GetBoolPref("mail.imap.hide_unused_namespaces", + &gHideUnusedNamespaces); + prefBranch->GetIntPref("mail.imap.noop_check_count", &gPromoteNoopToCheckCount); + prefBranch->GetBoolPref("mail.imap.use_envelope_cmd", + &gUseEnvelopeCmd); + prefBranch->GetBoolPref("mail.imap.use_literal_plus", &gUseLiteralPlus); + prefBranch->GetBoolPref("mail.imap.expunge_after_delete", &gExpungeAfterDelete); + prefBranch->GetBoolPref("mail.imap.check_deleted_before_expunge", &gCheckDeletedBeforeExpunge); + prefBranch->GetIntPref("mailnews.tcptimeout", &gResponseTimeout); + nsXPIDLCString customDBHeaders; + prefBranch->GetCharPref("mailnews.customDBHeaders", getter_Copies(customDBHeaders)); + gCustomDBHeaders.ParseString(customDBHeaders, ", "); + return NS_OK; } nsImapProtocol::nsImapProtocol() : nsMsgProtocol(nsnull), - m_parser(*this) + m_parser(*this) { m_urlInProgress = PR_FALSE; m_idle = PR_FALSE; @@ -379,7 +379,7 @@ prefString->ToString(getter_Copies(mAcceptLanguages)); } - // ***** Thread support ***** + // ***** Thread support ***** m_thread = nsnull; m_dataAvailableMonitor = nsnull; m_urlReadyToRunMonitor = nsnull; @@ -477,24 +477,24 @@ nsIEventTarget * aSinkEventTarget) { NS_PRECONDITION(aSinkEventTarget && aHostSessionList, - "oops...trying to initialize with a null sink event target!"); + "oops...trying to initialize with a null sink event target!"); if (!aSinkEventTarget || !aHostSessionList || !aServer) - return NS_ERROR_NULL_POINTER; + return NS_ERROR_NULL_POINTER; + + nsresult rv = m_downloadLineCache.GrowBuffer(kDownLoadCacheSize); + NS_ENSURE_SUCCESS(rv, rv); + + m_flagState = new nsImapFlagAndUidState(kImapFlagAndUidStateSize, PR_FALSE); + if (!m_flagState) + return NS_ERROR_OUT_OF_MEMORY; - nsresult rv = m_downloadLineCache.GrowBuffer(kDownLoadCacheSize); - NS_ENSURE_SUCCESS(rv, rv); + aServer->GetUseIdle(&m_useIdle); + NS_ADDREF(m_flagState); - m_flagState = new nsImapFlagAndUidState(kImapFlagAndUidStateSize, PR_FALSE); - if (!m_flagState) - return NS_ERROR_OUT_OF_MEMORY; - - aServer->GetUseIdle(&m_useIdle); - NS_ADDREF(m_flagState); - - m_sinkEventTarget = aSinkEventTarget; - m_hostSessionList = aHostSessionList; // no ref count...host session list has life time > connection - m_parser.SetHostSessionList(aHostSessionList); - m_parser.SetFlagState(m_flagState); + m_sinkEventTarget = aSinkEventTarget; + m_hostSessionList = aHostSessionList; // no ref count...host session list has life time > connection + m_parser.SetHostSessionList(aHostSessionList); + m_parser.SetFlagState(m_flagState); // Now initialize the thread for the connection and create appropriate monitors if (m_thread == nsnull) @@ -685,15 +685,15 @@ NS_PRECONDITION(aURL, "null URL passed into Imap Protocol"); if (aURL) { - rv = aURL->QueryInterface(NS_GET_IID(nsIImapUrl), getter_AddRefs(m_runningUrl)); + m_runningUrl = do_QueryInterface(aURL, &rv); if (NS_FAILED(rv)) return rv; nsCOMPtr server = do_QueryReferent(m_server); if (!server) { - nsCOMPtr mailnewsUrl = do_QueryInterface(m_runningUrl); - rv = mailnewsUrl->GetServer(getter_AddRefs(server)); - m_server = do_GetWeakReference(server); + nsCOMPtr mailnewsUrl = do_QueryInterface(m_runningUrl); + rv = mailnewsUrl->GetServer(getter_AddRefs(server)); + m_server = do_GetWeakReference(server); } nsCOMPtr imapServer = do_QueryInterface(server); @@ -954,11 +954,11 @@ PR_CEnterMonitor(this); NS_ASSERTION(me->m_imapThreadIsRunning == PR_FALSE, "Oh. oh. thread is already running. What's wrong here?"); - if (me->m_imapThreadIsRunning) - { - PR_CExitMonitor(me); - return NS_OK; - } + if (me->m_imapThreadIsRunning) + { + PR_CExitMonitor(me); + return NS_OK; + } me->m_imapThreadIsRunning = PR_TRUE; PR_CExitMonitor(me); @@ -1466,23 +1466,23 @@ if (m_retryUrlOnError) return RetryUrl(); - // The URL has now been processed + // The URL has now been processed if ((!logonFailed && GetConnectionStatus() < 0) || DeathSignalReceived()) - HandleCurrentUrlError(); + HandleCurrentUrlError(); } else if (!logonFailed) - HandleCurrentUrlError(); + HandleCurrentUrlError(); if (mailnewsurl && m_imapMailFolderSink) { - rv = GetServerStateParser().LastCommandSuccessful() - ? NS_OK : NS_ERROR_FAILURE; - // we are done with this url. - m_imapMailFolderSink->SetUrlState(this, mailnewsurl, PR_FALSE, rv); - // doom the cache entry - if (NS_FAILED(rv) && DeathSignalReceived() && m_mockChannel) - m_mockChannel->Cancel(rv); + rv = GetServerStateParser().LastCommandSuccessful() + ? NS_OK : NS_ERROR_FAILURE; + // we are done with this url. + m_imapMailFolderSink->SetUrlState(this, mailnewsurl, PR_FALSE, rv); + // doom the cache entry + if (NS_FAILED(rv) && DeathSignalReceived() && m_mockChannel) + m_mockChannel->Cancel(rv); } else NS_ASSERTION(PR_FALSE, "missing url or sink"); @@ -1491,18 +1491,18 @@ if (m_transport) m_transport->SetTimeout(nsISocketTransport::TIMEOUT_READ_WRITE, PR_UINT32_MAX); -// if we are set up as a channel, we should notify our channel listener that we are stopping... -// so pass in ourself as the channel and not the underlying socket or file channel the protocol -// happens to be using + // if we are set up as a channel, we should notify our channel listener that we are stopping... + // so pass in ourself as the channel and not the underlying socket or file channel the protocol + // happens to be using if (m_channelListener) { - nsCOMPtr request = do_QueryInterface(m_mockChannel); - NS_ASSERTION(request, "no request"); - if (request) { - nsresult status; - request->GetStatus(&status); - rv = m_channelListener->OnStopRequest(request, m_channelContext, status); - } + nsCOMPtr request = do_QueryInterface(m_mockChannel); + NS_ASSERTION(request, "no request"); + if (request) { + nsresult status; + request->GetStatus(&status); + rv = m_channelListener->OnStopRequest(request, m_channelContext, status); + } } SetFlag(IMAP_CLEAN_UP_URL_STATE); @@ -1539,7 +1539,7 @@ if (GetConnectionStatus() >= 0) rv = m_imapServerSink->LoadNextQueuedUrl(this, &anotherUrlRun); else // if we don't do this, they'll just sit and spin until - // we run some other url on this server. + // we run some other url on this server. { Log("ProcessCurrentURL", nsnull, "aborting queued urls"); rv = m_imapServerSink->AbortQueuedUrls(); @@ -1549,7 +1549,7 @@ // if we didn't run another url, release the server sink to // cut circular refs. if (!anotherUrlRun) - m_imapServerSink = nsnull; + m_imapServerSink = nsnull; nsCOMPtr imapServer = do_QueryReferent(m_server, &rv); if (GetConnectionStatus() < 0 || !GetServerStateParser().Connected() @@ -1560,7 +1560,7 @@ if (!DeathSignalReceived()) { - TellThreadToDie(PR_FALSE); + TellThreadToDie(PR_FALSE); } } else @@ -1596,11 +1596,11 @@ // from the server..in other words the command is "exploratory" and we don't really care if it succeeds or fails. void nsImapProtocol::ParseIMAPandCheckForNewMail(const char* commandString, PRBool aIgnoreBadAndNOResponses) { - if (commandString) - GetServerStateParser().ParseIMAPServerResponse(commandString, aIgnoreBadAndNOResponses); - else - GetServerStateParser().ParseIMAPServerResponse(m_currentCommand.get(), aIgnoreBadAndNOResponses); - // **** fix me for new mail biff state ***** + if (commandString) + GetServerStateParser().ParseIMAPServerResponse(commandString, aIgnoreBadAndNOResponses); + else + GetServerStateParser().ParseIMAPServerResponse(m_currentCommand.get(), aIgnoreBadAndNOResponses); + // **** fix me for new mail biff state ***** } ///////////////////////////////////////////////////////////////////////////////////////////// @@ -1608,23 +1608,21 @@ ////////////////////////////////////////////////////////////////////////////////////////////// NS_IMETHODIMP -nsImapProtocol::GetRunningUrl(nsIURI **result) +nsImapProtocol::GetRunningUrl(nsIURI **aRunningUrl) { - if (result && m_runningUrl) - return m_runningUrl->QueryInterface(NS_GET_IID(nsIURI), (void**) - result); - else - return NS_ERROR_NULL_POINTER; + if (!aRunningUrl || !m_runningUrl) + return NS_ERROR_NULL_POINTER; + + return CallQueryInterface(m_runningUrl, aRunningUrl); } NS_IMETHODIMP nsImapProtocol::GetRunningImapURL(nsIImapUrl **aImapUrl) { - if (aImapUrl && m_runningUrl) - return m_runningUrl->QueryInterface(NS_GET_IID(nsIImapUrl), (void**) aImapUrl); - else + if (!aImapUrl || !m_runningUrl) return NS_ERROR_NULL_POINTER; + return CallQueryInterface(m_runningUrl, aImapUrl); } /* Index: mozilla/mailnews/imap/src/nsImapServerResponseParser.cpp =================================================================== RCS file: /cvsroot/mozilla/mailnews/imap/src/nsImapServerResponseParser.cpp,v retrieving revision 1.141 diff -u -r1.141 mozilla/mailnews/imap/src/nsImapServerResponseParser.cpp --- mozilla/mailnews/imap/src/nsImapServerResponseParser.cpp +++ mozilla/mailnews/imap/src/nsImapServerResponseParser.cpp @@ -955,12 +955,14 @@ else { NS_ASSERTION(boxSpec->connection, "box spec has null connection"); - NS_ASSERTION(boxSpec->connection->GetCurrentUrl(), "box spec has connection with null url"); + /* what protects this from changing? */ + nsIImapUrl* currentConnectionUrl = boxSpec->connection->GetCurrentUrl(); + NS_ASSERTION(currentConnectionUrl, "box spec has connection with null url"); //boxSpec->hostName = nsnull; - //if (boxSpec->connection && boxSpec->connection->GetCurrentUrl()) - boxSpec->connection->GetCurrentUrl()->AllocateCanonicalPath(boxname, boxSpec->hierarchySeparator, &boxSpec->allocatedPathName); + //if (boxSpec->connection && currentConnectionUrl) + currentConnectionUrl->AllocateCanonicalPath(boxname, boxSpec->hierarchySeparator, &boxSpec->allocatedPathName); nsIURI * aURL = nsnull; - boxSpec->connection->GetCurrentUrl()->QueryInterface(NS_GET_IID(nsIURI), (void **) &aURL); + CallQueryInterface(currentConnectionUrl, &aURL); if (aURL) { nsCAutoString host; aURL->GetHost(host); @@ -3117,8 +3119,7 @@ if (returnSpec->connection) { nsIURI * aUrl = nsnull; - nsresult rv = NS_OK; - returnSpec->connection->GetCurrentUrl()->QueryInterface(NS_GET_IID(nsIURI), (void **) &aUrl); + nsresult rv = CallQueryInterface(returnSpec->connection->GetCurrentUrl(), &aUrl); if (NS_SUCCEEDED(rv) && aUrl) { nsCAutoString host; Index: mozilla/mailnews/imap/src/nsImapService.cpp =================================================================== RCS file: /cvsroot/mozilla/mailnews/imap/src/nsImapService.cpp,v retrieving revision 1.317 diff -u -r1.317 mozilla/mailnews/imap/src/nsImapService.cpp --- mozilla/mailnews/imap/src/nsImapService.cpp +++ mozilla/mailnews/imap/src/nsImapService.cpp @@ -309,7 +309,7 @@ urlSpec.Append(">"); urlSpec.Append(msgKey); rv = url->SetSpec(urlSpec); - imapUrl->QueryInterface(NS_GET_IID(nsIURI), (void **) aURL); + CallQueryInterface(imapUrl, aURL); } return rv; @@ -874,7 +874,7 @@ rv = rdf->GetResource(folderURI, getter_AddRefs(res)); NS_ENSURE_SUCCESS(rv,rv); - rv = res->QueryInterface(NS_GET_IID(nsIMsgFolder), (void **) aFolder); + rv = CallQueryInterface(res, aFolder); NS_ENSURE_SUCCESS(rv,rv); return NS_OK; @@ -1669,15 +1669,13 @@ aImapUrl->SetImapServerSink(imapServerSink); } - rv = aMsgFolder->QueryInterface(NS_GET_IID(nsIImapMailFolderSink), - (void**)&aInst); + rv = CallQueryInterface(aMsgFolder, &aInst); if (NS_SUCCEEDED(rv) && aInst) aImapUrl->SetImapMailFolderSink((nsIImapMailFolderSink*) aInst); NS_IF_RELEASE (aInst); aInst = nsnull; - rv = aMsgFolder->QueryInterface(NS_GET_IID(nsIImapMessageSink), - (void**)&aInst); + rv = CallQueryInterface(aMsgFolder, &aInst); if (NS_SUCCEEDED(rv) && aInst) aImapUrl->SetImapMessageSink((nsIImapMessageSink*) aInst); NS_IF_RELEASE (aInst); @@ -2559,7 +2557,7 @@ aImapUrl->SetFetchPartsOnDemand(PR_TRUE); // we got an imap url, so be sure to return it... - aImapUrl->QueryInterface(NS_GET_IID(nsIURI), (void **) _retval); + CallQueryInterface(aImapUrl, _retval); } return rv; @@ -2814,6 +2812,9 @@ nsImapService::GetServerIID(nsIID* *aServerIID) { *aServerIID = new nsIID(NS_GET_IID(nsIImapIncomingServer)); + if (!*aServerIID) + return NS_ERROR_OUT_OF_MEMORY; + return NS_OK; } @@ -3263,10 +3264,13 @@ nsImapOfflineSync *goOnline = new nsImapOfflineSync(aMsgWindow, aListener, nsnull); if (goOnline) { - rv = goOnline->QueryInterface(NS_GET_IID(nsISupports), (void **) aResult); + rv = CallQueryInterface(goOnline, aResult); NS_ENSURE_SUCCESS(rv, rv); - if (NS_SUCCEEDED(rv) && *aResult) + if (*aResult) return goOnline->ProcessNextOperation(); + + /* can this actually happen? */ + delete goOnline; } return NS_ERROR_OUT_OF_MEMORY; } Index: mozilla/mailnews/import/eudora/src/nsEudoraMac.cpp =================================================================== RCS file: /cvsroot/mozilla/mailnews/import/eudora/src/nsEudoraMac.cpp,v retrieving revision 1.39 diff -u -r1.39 mozilla/mailnews/import/eudora/src/nsEudoraMac.cpp --- mozilla/mailnews/import/eudora/src/nsEudoraMac.cpp +++ mozilla/mailnews/import/eudora/src/nsEudoraMac.cpp @@ -1,4 +1,4 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- +/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 @@ -85,33 +85,33 @@ #include "MoreFilesExtras.h" #endif -static NS_DEFINE_IID(kISupportsIID, NS_ISUPPORTS_IID); +static NS_DEFINE_IID(kISupportsIID, NS_ISUPPORTS_IID); -static const char * kWhitespace = "\b\t\r\n "; +static const char * kWhitespace = "\b\t\r\n "; nsEudoraMac::nsEudoraMac() { - m_mailImportLocation = nsnull; + m_mailImportLocation = nsnull; } nsEudoraMac::~nsEudoraMac() { - NS_IF_RELEASE( m_mailImportLocation); + NS_IF_RELEASE( m_mailImportLocation); } PRBool nsEudoraMac::FindMailFolder( nsIFileSpec *pFolder) { - return( FindEudoraLocation( pFolder)); + return( FindEudoraLocation( pFolder)); } PRBool nsEudoraMac::FindEudoraLocation( nsIFileSpec *pFolder, PRBool findIni, nsIFileSpec *pLookIn) { - PRBool result = PR_FALSE; - - // The "default" eudora folder is in the system folder named - // "Eudora Folder" (not sure if this is true for intl versions of Eudora) - - if (!pLookIn) { + PRBool result = PR_FALSE; + + // The "default" eudora folder is in the system folder named + // "Eudora Folder" (not sure if this is true for intl versions of Eudora) + + if (!pLookIn) { nsCOMPtr sysDir; nsresult rv = NS_GetSpecialDirectory(NS_OS_SYSTEM_DIR, getter_AddRefs(sysDir)); if (NS_FAILED(rv)) @@ -122,49 +122,49 @@ if (NS_FAILED(rv)) return (PR_FALSE); - pFolder->FromFileSpec(sysDirSpec); - pFolder->AppendRelativeUnixPath( "Eudora Folder"); - PRBool link = PR_FALSE; - rv = pFolder->IsSymlink( &link); - if (NS_SUCCEEDED( rv) && link) { - rv = pFolder->ResolveSymlink(); - if (NS_FAILED( rv)) - return( PR_FALSE); - } - } - else - pFolder->FromFileSpec( pLookIn); - - PRBool exists = PR_FALSE; - nsresult rv = pFolder->Exists( &exists); - PRBool isFolder = PR_FALSE; - if (NS_SUCCEEDED( rv) && exists) - rv = pFolder->IsDirectory( &isFolder); - if (!exists || !isFolder) - return( PR_FALSE); - - - nsFileSpec pref; - PRBool foundPref = PR_FALSE; - - nsCOMPtr dir; - rv = NS_NewDirectoryIterator( getter_AddRefs( dir)); - if (NS_SUCCEEDED( rv) && dir) { - exists = PR_FALSE; - rv = dir->Init( pFolder, PR_TRUE); - if (NS_SUCCEEDED( rv)) { - rv = dir->Exists( &exists); - nsCOMPtr entry; - int count = 0; - OSType type, creator; - while (exists && NS_SUCCEEDED( rv) && (count < 2)) { - rv = dir->GetCurrentSpec( getter_AddRefs( entry)); - if (NS_SUCCEEDED( rv)) { - nsFileSpec spec; - rv = entry->GetFileSpec( &spec); - if (NS_SUCCEEDED( rv)) { - // find a file with TEXT, CSOm that isn't the nicknames file - // or just cheat and look for more than 1 file? + pFolder->FromFileSpec(sysDirSpec); + pFolder->AppendRelativeUnixPath( "Eudora Folder"); + PRBool link = PR_FALSE; + rv = pFolder->IsSymlink( &link); + if (NS_SUCCEEDED( rv) && link) { + rv = pFolder->ResolveSymlink(); + if (NS_FAILED( rv)) + return( PR_FALSE); + } + } + else + pFolder->FromFileSpec( pLookIn); + + PRBool exists = PR_FALSE; + nsresult rv = pFolder->Exists( &exists); + PRBool isFolder = PR_FALSE; + if (NS_SUCCEEDED( rv) && exists) + rv = pFolder->IsDirectory( &isFolder); + if (!exists || !isFolder) + return( PR_FALSE); + + + nsFileSpec pref; + PRBool foundPref = PR_FALSE; + + nsCOMPtr dir; + rv = NS_NewDirectoryIterator( getter_AddRefs( dir)); + if (NS_SUCCEEDED( rv) && dir) { + exists = PR_FALSE; + rv = dir->Init( pFolder, PR_TRUE); + if (NS_SUCCEEDED( rv)) { + rv = dir->Exists( &exists); + nsCOMPtr entry; + int count = 0; + OSType type, creator; + while (exists && NS_SUCCEEDED( rv) && (count < 2)) { + rv = dir->GetCurrentSpec( getter_AddRefs( entry)); + if (NS_SUCCEEDED( rv)) { + nsFileSpec spec; + rv = entry->GetFileSpec( &spec); + if (NS_SUCCEEDED( rv)) { + // find a file with TEXT, CSOm that isn't the nicknames file + // or just cheat and look for more than 1 file? #ifdef XP_MACOSX { nsCOMPtr macFile; @@ -176,167 +176,167 @@ } } #else - rv = spec.GetFileTypeAndCreator( &type, &creator); + rv = spec.GetFileTypeAndCreator( &type, &creator); #endif - if (NS_SUCCEEDED( rv)) { - if ((type == 'TEXT') && (creator == 'CSOm')) - count++; - else if ((type == 'PREF') && (creator == 'CSOm')) { - if (!foundPref) { - pref = spec; - foundPref = PR_TRUE; - } - else { - // does one of them end in ".bkup"? - char *pLeafName = spec.GetLeafName(); - PRBool isBk = PR_FALSE; - PRInt32 len; - if (pLeafName) { - len = strlen( pLeafName); - if (len > 5) - isBk = (nsCRT::strcasecmp( pLeafName + len - 5, ".bkup") == 0); - nsCRT::free( pLeafName); - } - if (!isBk) { - pLeafName = pref.GetLeafName(); - if (pLeafName) { - len = strlen( pLeafName); - if (len > 5) - isBk = (nsCRT::strcasecmp( pLeafName + len - 5, ".bkup") == 0); - nsCRT::free( pLeafName); - } - if (isBk) { - pref = spec; - } - else { - // Neither of the pref files was named .bkup - // Pick the newest one? - nsFileSpec::TimeStamp modDate1, modDate2; - - spec.GetModDate( modDate2); - pref.GetModDate( modDate1); - if (modDate2 > modDate1) - pref = spec; - } - } - } - } - } - } - } - rv = dir->Next(); - if (NS_SUCCEEDED( rv)) - rv = dir->Exists( &exists); - } - if (count >= 2) - result = PR_TRUE; - } - } - - if (!findIni) - return( result); - - if (!foundPref) - return( PR_FALSE); - - pFolder->SetFromFileSpec( pref); - - return( PR_TRUE); + if (NS_SUCCEEDED( rv)) { + if ((type == 'TEXT') && (creator == 'CSOm')) + count++; + else if ((type == 'PREF') && (creator == 'CSOm')) { + if (!foundPref) { + pref = spec; + foundPref = PR_TRUE; + } + else { + // does one of them end in ".bkup"? + char *pLeafName = spec.GetLeafName(); + PRBool isBk = PR_FALSE; + PRInt32 len; + if (pLeafName) { + len = strlen( pLeafName); + if (len > 5) + isBk = (nsCRT::strcasecmp( pLeafName + len - 5, ".bkup") == 0); + nsCRT::free( pLeafName); + } + if (!isBk) { + pLeafName = pref.GetLeafName(); + if (pLeafName) { + len = strlen( pLeafName); + if (len > 5) + isBk = (nsCRT::strcasecmp( pLeafName + len - 5, ".bkup") == 0); + nsCRT::free( pLeafName); + } + if (isBk) { + pref = spec; + } + else { + // Neither of the pref files was named .bkup + // Pick the newest one? + nsFileSpec::TimeStamp modDate1, modDate2; + + spec.GetModDate( modDate2); + pref.GetModDate( modDate1); + if (modDate2 > modDate1) + pref = spec; + } + } + } + } + } + } + } + rv = dir->Next(); + if (NS_SUCCEEDED( rv)) + rv = dir->Exists( &exists); + } + if (count >= 2) + result = PR_TRUE; + } + } + + if (!findIni) + return( result); + + if (!foundPref) + return( PR_FALSE); + + pFolder->SetFromFileSpec( pref); + + return( PR_TRUE); } nsresult nsEudoraMac::FindMailboxes( nsIFileSpec *pRoot, nsISupportsArray **ppArray) { - nsresult rv = NS_NewISupportsArray( ppArray); - if (NS_FAILED( rv)) { - IMPORT_LOG0( "FAILED to allocate the nsISupportsArray\n"); - return( rv); - } - - nsCOMPtr impSvc(do_GetService(NS_IMPORTSERVICE_CONTRACTID, &rv)); - if (NS_FAILED( rv)) - return( rv); - - m_depth = 0; - NS_IF_RELEASE( m_mailImportLocation); - m_mailImportLocation = pRoot; - NS_IF_ADDREF( m_mailImportLocation); + nsresult rv = NS_NewISupportsArray( ppArray); + if (NS_FAILED( rv)) { + IMPORT_LOG0( "FAILED to allocate the nsISupportsArray\n"); + return( rv); + } + + nsCOMPtr impSvc(do_GetService(NS_IMPORTSERVICE_CONTRACTID, &rv)); + if (NS_FAILED( rv)) + return( rv); + + m_depth = 0; + NS_IF_RELEASE( m_mailImportLocation); + m_mailImportLocation = pRoot; + NS_IF_ADDREF( m_mailImportLocation); - return( ScanMailDir( pRoot, *ppArray, impSvc)); + return( ScanMailDir( pRoot, *ppArray, impSvc)); } nsresult nsEudoraMac::ScanMailDir( nsIFileSpec *pFolder, nsISupportsArray *pArray, nsIImportService *pImport) { - // On Windows, we look for a descmap file but on Mac we just iterate - // the directory - - m_depth++; - - nsresult rv = IterateMailDir( pFolder, pArray, pImport); - - m_depth--; + // On Windows, we look for a descmap file but on Mac we just iterate + // the directory + + m_depth++; + + nsresult rv = IterateMailDir( pFolder, pArray, pImport); + + m_depth--; - return( rv); + return( rv); } nsresult nsEudoraMac::IterateMailDir( nsIFileSpec *pFolder, nsISupportsArray *pArray, nsIImportService *pImport) { - nsCOMPtr dir; - nsresult rv = NS_NewDirectoryIterator( getter_AddRefs( dir)); - if (NS_FAILED( rv)) - return( rv); - - PRBool exists = PR_FALSE; - rv = dir->Init( pFolder, PR_TRUE); - if (NS_FAILED( rv)) - return( rv); - - rv = dir->Exists( &exists); - if (NS_FAILED( rv)) - return( rv); - - PRBool isFolder; - PRBool isFile; - nsCOMPtr entry; - char * pName; - nsCString fName; - nsCString ext; - nsCString name; - nsFileSpec spec; - OSType type; - OSType creator; - - while (exists && NS_SUCCEEDED( rv)) { - rv = dir->GetCurrentSpec( getter_AddRefs( entry)); - if (NS_SUCCEEDED( rv)) { - isFolder = PR_FALSE; - isFile = PR_FALSE; - pName = nsnull; - rv = entry->IsDirectory( &isFolder); - rv = entry->IsFile( &isFile); - rv = entry->GetLeafName( &pName); - if (NS_SUCCEEDED( rv) && pName) { - fName = pName; - nsCRT::free( pName); - if (isFolder) { - if (IsValidMailFolderName( fName)) { - rv = FoundMailFolder( entry, fName.get(), pArray, pImport); - if (NS_SUCCEEDED( rv)) { - rv = ScanMailDir( entry, pArray, pImport); - if (NS_FAILED( rv)) { - IMPORT_LOG0( "*** Error scanning mail directory\n"); - } - } - } - } - else if (isFile) { - rv = entry->GetFileSpec( &spec); - if (NS_SUCCEEDED( rv)) { - type = 0; - creator = 0; + nsCOMPtr dir; + nsresult rv = NS_NewDirectoryIterator( getter_AddRefs( dir)); + if (NS_FAILED( rv)) + return( rv); + + PRBool exists = PR_FALSE; + rv = dir->Init( pFolder, PR_TRUE); + if (NS_FAILED( rv)) + return( rv); + + rv = dir->Exists( &exists); + if (NS_FAILED( rv)) + return( rv); + + PRBool isFolder; + PRBool isFile; + nsCOMPtr entry; + char * pName; + nsCString fName; + nsCString ext; + nsCString name; + nsFileSpec spec; + OSType type; + OSType creator; + + while (exists && NS_SUCCEEDED( rv)) { + rv = dir->GetCurrentSpec( getter_AddRefs( entry)); + if (NS_SUCCEEDED( rv)) { + isFolder = PR_FALSE; + isFile = PR_FALSE; + pName = nsnull; + rv = entry->IsDirectory( &isFolder); + rv = entry->IsFile( &isFile); + rv = entry->GetLeafName( &pName); + if (NS_SUCCEEDED( rv) && pName) { + fName = pName; + nsCRT::free( pName); + if (isFolder) { + if (IsValidMailFolderName( fName)) { + rv = FoundMailFolder( entry, fName.get(), pArray, pImport); + if (NS_SUCCEEDED( rv)) { + rv = ScanMailDir( entry, pArray, pImport); + if (NS_FAILED( rv)) { + IMPORT_LOG0( "*** Error scanning mail directory\n"); + } + } + } + } + else if (isFile) { + rv = entry->GetFileSpec( &spec); + if (NS_SUCCEEDED( rv)) { + type = 0; + creator = 0; #ifdef XP_MACOSX { nsCOMPtr macFile; @@ -350,114 +350,114 @@ #else spec.GetFileTypeAndCreator( &type, &creator); #endif - if ((type == 'TEXT') && IsValidMailboxName( fName) && IsValidMailboxFile( entry)) { - rv = FoundMailbox( entry, fName.get(), pArray, pImport); - } - } - } - } - } - - rv = dir->Next(); - if (NS_SUCCEEDED( rv)) - rv = dir->Exists( &exists); - } + if ((type == 'TEXT') && IsValidMailboxName( fName) && IsValidMailboxFile( entry)) { + rv = FoundMailbox( entry, fName.get(), pArray, pImport); + } + } + } + } + } + + rv = dir->Next(); + if (NS_SUCCEEDED( rv)) + rv = dir->Exists( &exists); + } - return( rv); + return( rv); } nsresult nsEudoraMac::FoundMailbox( nsIFileSpec *mailFile, const char *pName, nsISupportsArray *pArray, nsIImportService *pImport) { - nsAutoString displayName; - nsCOMPtr desc; - nsISupports * pInterface; + nsAutoString displayName; + nsCOMPtr desc; + nsISupports * pInterface; - NS_CopyNativeToUnicode(nsDependentCString(pName), displayName); + NS_CopyNativeToUnicode(nsDependentCString(pName), displayName); #ifdef IMPORT_DEBUG - char *pPath = nsnull; - mailFile->GetNativePath( &pPath); - if (pPath) { - IMPORT_LOG2( "Found eudora mailbox, %s: %s\n", pPath, pName); - nsCRT::free( pPath); - } - else { - IMPORT_LOG1( "Found eudora mailbox, %s\n", pName); - } - IMPORT_LOG1( "\tm_depth = %d\n", (int)m_depth); + char *pPath = nsnull; + mailFile->GetNativePath( &pPath); + if (pPath) { + IMPORT_LOG2( "Found eudora mailbox, %s: %s\n", pPath, pName); + nsCRT::free( pPath); + } + else { + IMPORT_LOG1( "Found eudora mailbox, %s\n", pName); + } + IMPORT_LOG1( "\tm_depth = %d\n", (int)m_depth); #endif - nsresult rv = pImport->CreateNewMailboxDescriptor( getter_AddRefs( desc)); - if (NS_SUCCEEDED( rv)) { - PRUint32 sz = 0; - mailFile->GetFileSize( &sz); - desc->SetDisplayName( displayName.get()); - desc->SetDepth( m_depth); - desc->SetSize( sz); - nsIFileSpec *pSpec = nsnull; - desc->GetFileSpec( &pSpec); - if (pSpec) { - pSpec->FromFileSpec( mailFile); - NS_RELEASE( pSpec); - } - rv = desc->QueryInterface( kISupportsIID, (void **) &pInterface); - pArray->AppendElement( pInterface); - pInterface->Release(); - } + nsresult rv = pImport->CreateNewMailboxDescriptor( getter_AddRefs( desc)); + if (NS_SUCCEEDED( rv)) { + PRUint32 sz = 0; + mailFile->GetFileSize( &sz); + desc->SetDisplayName( displayName.get()); + desc->SetDepth( m_depth); + desc->SetSize( sz); + nsIFileSpec *pSpec = nsnull; + desc->GetFileSpec( &pSpec); + if (pSpec) { + pSpec->FromFileSpec( mailFile); + NS_RELEASE( pSpec); + } + rv = desc->QueryInterface( kISupportsIID, (void **) &pInterface); + pArray->AppendElement( pInterface); + pInterface->Release(); + } - return( NS_OK); + return( NS_OK); } nsresult nsEudoraMac::FoundMailFolder( nsIFileSpec *mailFolder, const char *pName, nsISupportsArray *pArray, nsIImportService *pImport) { - nsAutoString displayName; - nsCOMPtr desc; - nsISupports * pInterface; + nsAutoString displayName; + nsCOMPtr desc; + nsISupports * pInterface; - NS_CopyNativeToUnicode(nsDependentCString(pName), displayName); + NS_CopyNativeToUnicode(nsDependentCString(pName), displayName); #ifdef IMPORT_DEBUG - char *pPath = nsnull; - mailFolder->GetNativePath( &pPath); - if (pPath) { - IMPORT_LOG2( "Found eudora folder, %s: %s\n", pPath, pName); - nsCRT::free( pPath); - } - else { - IMPORT_LOG1( "Found eudora folder, %s\n", pName); - } - IMPORT_LOG1( "\tm_depth = %d\n", (int)m_depth); + char *pPath = nsnull; + mailFolder->GetNativePath( &pPath); + if (pPath) { + IMPORT_LOG2( "Found eudora folder, %s: %s\n", pPath, pName); + nsCRT::free( pPath); + } + else { + IMPORT_LOG1( "Found eudora folder, %s\n", pName); + } + IMPORT_LOG1( "\tm_depth = %d\n", (int)m_depth); #endif - nsresult rv = pImport->CreateNewMailboxDescriptor( getter_AddRefs( desc)); - if (NS_SUCCEEDED( rv)) { - PRUint32 sz = 0; - desc->SetDisplayName( displayName.get()); - desc->SetDepth( m_depth); - desc->SetSize( sz); - nsIFileSpec *pSpec = nsnull; - desc->GetFileSpec( &pSpec); - if (pSpec) { - pSpec->FromFileSpec( mailFolder); - NS_RELEASE( pSpec); - } - rv = desc->QueryInterface( kISupportsIID, (void **) &pInterface); - pArray->AppendElement( pInterface); - pInterface->Release(); - } + nsresult rv = pImport->CreateNewMailboxDescriptor( getter_AddRefs( desc)); + if (NS_SUCCEEDED( rv)) { + PRUint32 sz = 0; + desc->SetDisplayName( displayName.get()); + desc->SetDepth( m_depth); + desc->SetSize( sz); + nsIFileSpec *pSpec = nsnull; + desc->GetFileSpec( &pSpec); + if (pSpec) { + pSpec->FromFileSpec( mailFolder); + NS_RELEASE( pSpec); + } + rv = desc->QueryInterface( kISupportsIID, (void **) &pInterface); + pArray->AppendElement( pInterface); + pInterface->Release(); + } - return( NS_OK); + return( NS_OK); } PRBool nsEudoraMac::CreateTocFromResource( nsIFileSpec *pMail, nsIFileSpec *pToc) -{ - nsFileSpec spec; - nsresult rv = pMail->GetFileSpec( &spec); - if (NS_FAILED( rv)) - return( PR_FALSE); +{ + nsFileSpec spec; + nsresult rv = pMail->GetFileSpec( &spec); + if (NS_FAILED( rv)) + return( PR_FALSE); short resFile = -1; #ifdef XP_MACOSX { @@ -468,7 +468,7 @@ FSSpec fsSpec; rv = macFile->GetFSSpec(&fsSpec); - if (NS_FAILED(rv)) + if (NS_FAILED(rv)) return PR_FALSE; resFile = FSpOpenResFile( &fsSpec, fsRdPerm); @@ -476,17 +476,17 @@ #else resFile = FSpOpenResFile( spec.GetFSSpecPtr(), fsRdPerm); #endif - if (resFile == -1) - return( PR_FALSE); - Handle resH = nil; - short max = Count1Resources( 'TOCF'); - if (max) { - resH = Get1IndResource( 'TOCF', 1); - } - PRBool result = PR_FALSE; - if (resH) { - PRInt32 sz = (PRInt32) GetHandleSize( resH); - if (sz) { + if (resFile == -1) + return( PR_FALSE); + Handle resH = nil; + short max = Count1Resources( 'TOCF'); + if (max) { + resH = Get1IndResource( 'TOCF', 1); + } + PRBool result = PR_FALSE; + if (resH) { + PRInt32 sz = (PRInt32) GetHandleSize( resH); + if (sz) { // Create the new TOC file nsCOMPtr tempDir; nsresult rv = NS_GetSpecialDirectory(NS_OS_TEMP_DIR, getter_AddRefs(tempDir)); @@ -498,66 +498,66 @@ if (NS_FAILED(rv)) return (PR_FALSE); - rv = pToc->FromFileSpec( dir); - if (NS_SUCCEEDED( rv)) - rv = pToc->AppendRelativeUnixPath( "temp.toc"); - if (NS_SUCCEEDED( rv)) - rv = pToc->MakeUnique(); - if (NS_SUCCEEDED( rv)) - rv = pToc->OpenStreamForWriting(); - if (NS_SUCCEEDED( rv)) { - HLock( resH); - PRInt32 written = 0; - rv = pToc->Write( *resH, sz, &written); - HUnlock( resH); - pToc->CloseStream(); - if (NS_FAILED( rv) || (written != sz)) { - pToc->GetFileSpec( &spec); - spec.Delete( PR_FALSE); - } - else - result = PR_TRUE; - } - } - ReleaseResource( resH); - } - CloseResFile( resFile); - - return( result); + rv = pToc->FromFileSpec( dir); + if (NS_SUCCEEDED( rv)) + rv = pToc->AppendRelativeUnixPath( "temp.toc"); + if (NS_SUCCEEDED( rv)) + rv = pToc->MakeUnique(); + if (NS_SUCCEEDED( rv)) + rv = pToc->OpenStreamForWriting(); + if (NS_SUCCEEDED( rv)) { + HLock( resH); + PRInt32 written = 0; + rv = pToc->Write( *resH, sz, &written); + HUnlock( resH); + pToc->CloseStream(); + if (NS_FAILED( rv) || (written != sz)) { + pToc->GetFileSpec( &spec); + spec.Delete( PR_FALSE); + } + else + result = PR_TRUE; + } + } + ReleaseResource( resH); + } + CloseResFile( resFile); + + return( result); } nsresult nsEudoraMac::FindTOCFile( nsIFileSpec *pMailFile, nsIFileSpec **ppTOCFile, PRBool *pDeleteToc) { - nsresult rv; - char * pName = nsnull; + nsresult rv; + char * pName = nsnull; - *pDeleteToc = PR_FALSE; - *ppTOCFile = nsnull; - rv = pMailFile->GetLeafName( &pName); - if (NS_FAILED( rv)) - return( rv); - rv = pMailFile->GetParent( ppTOCFile); - if (NS_FAILED( rv)) - return( rv); - - nsCString leaf(pName); - nsCRT::free( pName); - leaf.Append( ".toc"); - - OSType type = 0; - OSType creator = 0; - PRBool exists = PR_FALSE; - PRBool isFile = PR_FALSE; - rv = (*ppTOCFile)->AppendRelativeUnixPath( leaf.get()); - if (NS_SUCCEEDED( rv)) - rv = (*ppTOCFile)->Exists( &exists); - if (NS_SUCCEEDED( rv) && exists) - rv = (*ppTOCFile)->IsFile( &isFile); - if (isFile) { - nsFileSpec spec; - rv = (*ppTOCFile)->GetFileSpec( &spec); - if (NS_SUCCEEDED( rv)) + *pDeleteToc = PR_FALSE; + *ppTOCFile = nsnull; + rv = pMailFile->GetLeafName( &pName); + if (NS_FAILED( rv)) + return( rv); + rv = pMailFile->GetParent( ppTOCFile); + if (NS_FAILED( rv)) + return( rv); + + nsCString leaf(pName); + nsCRT::free( pName); + leaf.Append( ".toc"); + + OSType type = 0; + OSType creator = 0; + PRBool exists = PR_FALSE; + PRBool isFile = PR_FALSE; + rv = (*ppTOCFile)->AppendRelativeUnixPath( leaf.get()); + if (NS_SUCCEEDED( rv)) + rv = (*ppTOCFile)->Exists( &exists); + if (NS_SUCCEEDED( rv) && exists) + rv = (*ppTOCFile)->IsFile( &isFile); + if (isFile) { + nsFileSpec spec; + rv = (*ppTOCFile)->GetFileSpec( &spec); + if (NS_SUCCEEDED( rv)) #ifdef XP_MACOSX { nsCOMPtr macFile; @@ -569,37 +569,37 @@ } } #else - spec.GetFileTypeAndCreator( &type, &creator); + spec.GetFileTypeAndCreator( &type, &creator); #endif - } - + } + - if (exists && isFile && (type == 'TOCF') && (creator == 'CSOm')) - return( NS_OK); - - // try and create the file from a resource. - if (CreateTocFromResource( pMailFile, *ppTOCFile)) { - *pDeleteToc = PR_TRUE; - return( NS_OK); - } - return( NS_ERROR_FAILURE); + if (exists && isFile && (type == 'TOCF') && (creator == 'CSOm')) + return( NS_OK); + + // try and create the file from a resource. + if (CreateTocFromResource( pMailFile, *ppTOCFile)) { + *pDeleteToc = PR_TRUE; + return( NS_OK); + } + return( NS_ERROR_FAILURE); } // Strings returned: -// 1 - smtp server +// 1 - smtp server // 2 - pop account user name -// 3 - the pop server -// 4 - Return address -// 5 - Full name -// 6 - Leave mail on server -#define kNumSettingStrs 6 -#define kSmtpServerStr 0 -#define kPopAccountNameStr 1 -#define kPopServerStr 2 -#define kReturnAddressStr 3 -#define kFullNameStr 4 -#define kLeaveOnServerStr 5 +// 3 - the pop server +// 4 - Return address +// 5 - Full name +// 6 - Leave mail on server +#define kNumSettingStrs 6 +#define kSmtpServerStr 0 +#define kPopAccountNameStr 1 +#define kPopServerStr 2 +#define kReturnAddressStr 3 +#define kFullNameStr 4 +#define kLeaveOnServerStr 5 // resource IDs #define kSmtpServerID 4 @@ -611,437 +611,437 @@ PRBool nsEudoraMac::GetSettingsFromResource( nsIFileSpec *pSettings, short resId, nsCString **pStrs, PRBool *pIMAP) { - *pIMAP = PR_FALSE; - // Get settings from the resources... - nsFileSpec spec; - nsresult rv = pSettings->GetFileSpec( &spec); - if (NS_FAILED( rv)) - return( PR_FALSE); + *pIMAP = PR_FALSE; + // Get settings from the resources... + nsFileSpec spec; + nsresult rv = pSettings->GetFileSpec( &spec); + if (NS_FAILED( rv)) + return( PR_FALSE); short resFile = -1; #ifdef XP_MACOSX { nsCOMPtr macFile; rv = NS_FileSpecToILocalFileMac(&spec, getter_AddRefs(macFile)); - if (NS_FAILED(rv)) + if (NS_FAILED(rv)) return PR_FALSE; FSSpec fsSpec; rv = macFile->GetFSSpec(&fsSpec); - if (NS_FAILED(rv)) + if (NS_FAILED(rv)) return PR_FALSE; resFile = FSpOpenResFile( &fsSpec, fsRdPerm); } #else - resFile = FSpOpenResFile( spec.GetFSSpecPtr(), fsRdPerm); + resFile = FSpOpenResFile( spec.GetFSSpecPtr(), fsRdPerm); #endif - if (resFile == -1) - return( PR_FALSE); - - // smtp server, STR# 1000, 4 - Handle resH = Get1Resource( 'STR#', resId /* 1000 */); - int idx; - if (resH) { - ReleaseResource( resH); - StringPtr pStr[5]; - StringPtr theStr; - short i; - for (i = 0; i < 5; i++) { - pStr[i] = (StringPtr) new PRUint8[256]; - (pStr[i])[0] = 0; - } - GetIndString( pStr[0], resId /* 1000 */, kSmtpServerID); - GetIndString( pStr[1], resId, kEmailAddressID); // user name@pop server - GetIndString( pStr[2], resId, kReturnAddressID); - GetIndString( pStr[3], resId, kFullNameID); - GetIndString( pStr[4], resId, kLeaveMailOnServerID); - CloseResFile( resFile); - - theStr = pStr[0]; - if (*theStr) { - pStrs[0]->Append( (const char *) (theStr + 1), *theStr); - } - theStr = pStr[1]; - if (*theStr) { - idx = 1; - while (idx <= *theStr) { - if (theStr[idx] == '@') - break; - else - idx++; - } - if (idx <= *theStr) { - PRUint8 save = *theStr; - *theStr = idx - 1; - if (*theStr) { - pStrs[1]->Append( (const char *) (theStr + 1), *theStr); - } - *theStr = save; - } - else - idx = 0; - theStr[idx] = theStr[0] - idx; - if (theStr[idx]) { - pStrs[2]->Append( (const char *) (theStr + idx + 1), *(theStr + idx)); - } - } - theStr = pStr[2]; - if ( *theStr) { - pStrs[3]->Append( (const char *) (theStr + 1), *theStr); - } - theStr = pStr[3]; - if ( *theStr) { - pStrs[4]->Append( (const char *) (theStr + 1), *theStr); - } - theStr = pStr[4]; - if ( *theStr) { - if (theStr[1] == 'y') { - *(pStrs[5]) = "Y"; - } - else { - *(pStrs[5]) = "N"; - } - } - for (i = 0; i < 5; i++) { - delete pStr[i]; - } - - return( PR_TRUE); - } - else { - CloseResFile( resFile); - return( PR_FALSE); - } + if (resFile == -1) + return( PR_FALSE); + + // smtp server, STR# 1000, 4 + Handle resH = Get1Resource( 'STR#', resId /* 1000 */); + int idx; + if (resH) { + ReleaseResource( resH); + StringPtr pStr[5]; + StringPtr theStr; + short i; + for (i = 0; i < 5; i++) { + pStr[i] = (StringPtr) new PRUint8[256]; + (pStr[i])[0] = 0; + } + GetIndString( pStr[0], resId /* 1000 */, kSmtpServerID); + GetIndString( pStr[1], resId, kEmailAddressID); // user name@pop server + GetIndString( pStr[2], resId, kReturnAddressID); + GetIndString( pStr[3], resId, kFullNameID); + GetIndString( pStr[4], resId, kLeaveMailOnServerID); + CloseResFile( resFile); + + theStr = pStr[0]; + if (*theStr) { + pStrs[0]->Append( (const char *) (theStr + 1), *theStr); + } + theStr = pStr[1]; + if (*theStr) { + idx = 1; + while (idx <= *theStr) { + if (theStr[idx] == '@') + break; + else + idx++; + } + if (idx <= *theStr) { + PRUint8 save = *theStr; + *theStr = idx - 1; + if (*theStr) { + pStrs[1]->Append( (const char *) (theStr + 1), *theStr); + } + *theStr = save; + } + else + idx = 0; + theStr[idx] = theStr[0] - idx; + if (theStr[idx]) { + pStrs[2]->Append( (const char *) (theStr + idx + 1), *(theStr + idx)); + } + } + theStr = pStr[2]; + if ( *theStr) { + pStrs[3]->Append( (const char *) (theStr + 1), *theStr); + } + theStr = pStr[3]; + if ( *theStr) { + pStrs[4]->Append( (const char *) (theStr + 1), *theStr); + } + theStr = pStr[4]; + if ( *theStr) { + if (theStr[1] == 'y') { + *(pStrs[5]) = "Y"; + } + else { + *(pStrs[5]) = "N"; + } + } + for (i = 0; i < 5; i++) { + delete pStr[i]; + } + + return( PR_TRUE); + } + else { + CloseResFile( resFile); + return( PR_FALSE); + } } PRBool nsEudoraMac::ImportSettings( nsIFileSpec *pIniFile, nsIMsgAccount **localMailAccount) { - nsresult rv; + nsresult rv; - nsCOMPtr accMgr = - do_GetService(NS_MSGACCOUNTMANAGER_CONTRACTID, &rv); + nsCOMPtr accMgr = + do_GetService(NS_MSGACCOUNTMANAGER_CONTRACTID, &rv); if (NS_FAILED(rv)) { - IMPORT_LOG0( "*** Failed to create a account manager!\n"); - return( PR_FALSE); - } - - short baseResId = 1000; - nsCString **pStrs = new nsCString *[kNumSettingStrs]; - int i; - - for (i = 0; i < kNumSettingStrs; i++) { - pStrs[i] = new nsCString; - } - - nsString accName(NS_LITERAL_STRING("Eudora Settings")); - nsEudoraStringBundle::GetStringByID( EUDORAIMPORT_ACCOUNTNAME, accName); - - // This is a little overkill but we're not sure yet how multiple accounts - // are stored in the Mac preferences, hopefully similar to existing prefs - // which means the following is a good start! - PRBool isIMAP = PR_FALSE; - - int popCount = 0; - int accounts = 0; - nsIMsgAccount * pAccount; - - while (baseResId) { - isIMAP = PR_FALSE; - if (GetSettingsFromResource( pIniFile, baseResId, pStrs, &isIMAP)) { - pAccount = nsnull; - if (!isIMAP) { - // This is a POP account - if (BuildPOPAccount( accMgr, pStrs, &pAccount, accName)) { - accounts++; - popCount++; - if (popCount > 1) { - if (localMailAccount && *localMailAccount) { - NS_RELEASE( *localMailAccount); - *localMailAccount = nsnull; - } - } - else { - if (localMailAccount) { - *localMailAccount = pAccount; - NS_IF_ADDREF( pAccount); - } - } - } - } - else { - // This is an IMAP account - if (BuildIMAPAccount( accMgr, pStrs, &pAccount, accName)) { - accounts++; - } - } - if (pAccount && (baseResId == 1000)) { - accMgr->SetDefaultAccount( pAccount); - } - - NS_IF_RELEASE( pAccount); - } - - baseResId = 0; - // Set the next account name??? - - if (baseResId) { - for (i = 0; i < kNumSettingStrs; i++) { - pStrs[i]->Truncate(); - } - } - } - - // Now save the new acct info to pref file. - rv = accMgr->SaveAccountInfo(); - NS_ASSERTION(NS_SUCCEEDED(rv), "Can't save account info to pref file"); - - for (i = 0; i < kNumSettingStrs; i++) { - delete pStrs[i]; - } - delete pStrs; + IMPORT_LOG0( "*** Failed to create a account manager!\n"); + return( PR_FALSE); + } - return( accounts != 0); + short baseResId = 1000; + nsCString **pStrs = new nsCString *[kNumSettingStrs]; + int i; + + for (i = 0; i < kNumSettingStrs; i++) { + pStrs[i] = new nsCString; + } + + nsString accName(NS_LITERAL_STRING("Eudora Settings")); + nsEudoraStringBundle::GetStringByID( EUDORAIMPORT_ACCOUNTNAME, accName); + + // This is a little overkill but we're not sure yet how multiple accounts + // are stored in the Mac preferences, hopefully similar to existing prefs + // which means the following is a good start! + PRBool isIMAP = PR_FALSE; + + int popCount = 0; + int accounts = 0; + nsIMsgAccount * pAccount; + + while (baseResId) { + isIMAP = PR_FALSE; + if (GetSettingsFromResource( pIniFile, baseResId, pStrs, &isIMAP)) { + pAccount = nsnull; + if (!isIMAP) { + // This is a POP account + if (BuildPOPAccount( accMgr, pStrs, &pAccount, accName)) { + accounts++; + popCount++; + if (popCount > 1) { + if (localMailAccount && *localMailAccount) { + NS_RELEASE( *localMailAccount); + *localMailAccount = nsnull; + } + } + else { + if (localMailAccount) { + *localMailAccount = pAccount; + NS_IF_ADDREF( pAccount); + } + } + } + } + else { + // This is an IMAP account + if (BuildIMAPAccount( accMgr, pStrs, &pAccount, accName)) { + accounts++; + } + } + if (pAccount && (baseResId == 1000)) { + accMgr->SetDefaultAccount( pAccount); + } + + NS_IF_RELEASE( pAccount); + } + + baseResId = 0; + // Set the next account name??? + + if (baseResId) { + for (i = 0; i < kNumSettingStrs; i++) { + pStrs[i]->Truncate(); + } + } + } + + // Now save the new acct info to pref file. + rv = accMgr->SaveAccountInfo(); + NS_ASSERTION(NS_SUCCEEDED(rv), "Can't save account info to pref file"); + + for (i = 0; i < kNumSettingStrs; i++) { + delete pStrs[i]; + } + delete pStrs; + + return( accounts != 0); } PRBool nsEudoraMac::BuildPOPAccount( nsIMsgAccountManager *accMgr, nsCString **pStrs, nsIMsgAccount **ppAccount, nsString& accName) { - if (ppAccount) - *ppAccount = nsnull; - - - if (!pStrs[kPopServerStr]->Length() || !pStrs[kPopAccountNameStr]->Length()) - return( PR_FALSE); - - PRBool result = PR_FALSE; - - // I now have a user name/server name pair, find out if it already exists? - nsCOMPtr in; - nsresult rv = accMgr->FindServer( pStrs[kPopAccountNameStr]->get(), pStrs[kPopServerStr]->get(), "pop3", getter_AddRefs( in)); - if (NS_FAILED( rv) || (in == nsnull)) { - // Create the incoming server and an account for it? - rv = accMgr->CreateIncomingServer( pStrs[kPopAccountNameStr]->get(), pStrs[kPopServerStr]->get(), "pop3", getter_AddRefs( in)); - if (NS_SUCCEEDED( rv) && in) { - rv = in->SetType( "pop3"); - // rv = in->SetHostName( pStrs[kPopServerStr]->get()); - // rv = in->SetUsername( pStrs[kPopAccountNameStr]->get()); - - IMPORT_LOG2( "Created POP3 server named: %s, userName: %s\n", pStrs[kPopServerStr]->get(), pStrs[kPopAccountNameStr]->get()); - - PRUnichar *pretty = ToNewUnicode(accName); - IMPORT_LOG1( "\tSet pretty name to: %S\n", pretty); - rv = in->SetPrettyName( pretty); - nsCRT::free( pretty); - - // We have a server, create an account. - nsCOMPtr account; - rv = accMgr->CreateAccount( getter_AddRefs( account)); - if (NS_SUCCEEDED( rv) && account) { - rv = account->SetIncomingServer( in); - - IMPORT_LOG0( "Created a new account and set the incoming server to the POP3 server.\n"); - + if (ppAccount) + *ppAccount = nsnull; + + + if (!pStrs[kPopServerStr]->Length() || !pStrs[kPopAccountNameStr]->Length()) + return( PR_FALSE); + + PRBool result = PR_FALSE; + + // I now have a user name/server name pair, find out if it already exists? + nsCOMPtr in; + nsresult rv = accMgr->FindServer( pStrs[kPopAccountNameStr]->get(), pStrs[kPopServerStr]->get(), "pop3", getter_AddRefs( in)); + if (NS_FAILED( rv) || (in == nsnull)) { + // Create the incoming server and an account for it? + rv = accMgr->CreateIncomingServer( pStrs[kPopAccountNameStr]->get(), pStrs[kPopServerStr]->get(), "pop3", getter_AddRefs( in)); + if (NS_SUCCEEDED( rv) && in) { + rv = in->SetType( "pop3"); + // rv = in->SetHostName( pStrs[kPopServerStr]->get()); + // rv = in->SetUsername( pStrs[kPopAccountNameStr]->get()); + + IMPORT_LOG2( "Created POP3 server named: %s, userName: %s\n", pStrs[kPopServerStr]->get(), pStrs[kPopAccountNameStr]->get()); + + PRUnichar *pretty = ToNewUnicode(accName); + IMPORT_LOG1( "\tSet pretty name to: %S\n", pretty); + rv = in->SetPrettyName( pretty); + nsCRT::free( pretty); + + // We have a server, create an account. + nsCOMPtr account; + rv = accMgr->CreateAccount( getter_AddRefs( account)); + if (NS_SUCCEEDED( rv) && account) { + rv = account->SetIncomingServer( in); + + IMPORT_LOG0( "Created a new account and set the incoming server to the POP3 server.\n"); + nsCOMPtr pop3Server = do_QueryInterface(in, &rv); NS_ENSURE_SUCCESS(rv,rv); pop3Server->SetLeaveMessagesOnServer(pStrs[kLeaveOnServerStr]->First() == 'Y' ? PR_TRUE : PR_FALSE); // Fiddle with the identities - SetIdentities(accMgr, account, pStrs[kPopAccountNameStr]->get(), pStrs[kPopServerStr]->get(), pStrs); - result = PR_TRUE; - if (ppAccount) - account->QueryInterface( NS_GET_IID(nsIMsgAccount), (void **)ppAccount); - } - } - } - else - result = PR_TRUE; - - return( result); + SetIdentities(accMgr, account, pStrs[kPopAccountNameStr]->get(), pStrs[kPopServerStr]->get(), pStrs); + result = PR_TRUE; + if (ppAccount) + CallQueryInterface(account, ppAccount); + } + } + } + else + result = PR_TRUE; + + return( result); } PRBool nsEudoraMac::BuildIMAPAccount( nsIMsgAccountManager *accMgr, nsCString **pStrs, nsIMsgAccount **ppAccount, nsString& accName) -{ +{ + + if (!pStrs[kPopServerStr]->Length() || !pStrs[kPopAccountNameStr]->Length()) + return( PR_FALSE); - if (!pStrs[kPopServerStr]->Length() || !pStrs[kPopAccountNameStr]->Length()) - return( PR_FALSE); + PRBool result = PR_FALSE; - PRBool result = PR_FALSE; + nsCOMPtr in; + nsresult rv = accMgr->FindServer( pStrs[kPopAccountNameStr]->get(), pStrs[kPopServerStr]->get(), "imap", getter_AddRefs( in)); + if (NS_FAILED( rv) || (in == nsnull)) { + // Create the incoming server and an account for it? + rv = accMgr->CreateIncomingServer( pStrs[kPopAccountNameStr]->get(), pStrs[kPopServerStr]->get(), "imap", getter_AddRefs( in)); + if (NS_SUCCEEDED( rv) && in) { + rv = in->SetType( "imap"); + // rv = in->SetHostName( pStrs[kPopServerStr]->get()); + // rv = in->SetUsername( pStrs[kPopAccountNameStr]->get()); + + IMPORT_LOG2( "Created IMAP server named: %s, userName: %s\n", pStrs[kPopServerStr]->get(), pStrs[kPopAccountNameStr]->get()); + + PRUnichar *pretty = ToNewUnicode(accName); + + IMPORT_LOG1( "\tSet pretty name to: %S\n", pretty); + + rv = in->SetPrettyName( pretty); + nsCRT::free( pretty); + + // We have a server, create an account. + nsCOMPtr account; + rv = accMgr->CreateAccount( getter_AddRefs( account)); + if (NS_SUCCEEDED( rv) && account) { + rv = account->SetIncomingServer( in); + + IMPORT_LOG0( "Created an account and set the IMAP server as the incoming server\n"); - nsCOMPtr in; - nsresult rv = accMgr->FindServer( pStrs[kPopAccountNameStr]->get(), pStrs[kPopServerStr]->get(), "imap", getter_AddRefs( in)); - if (NS_FAILED( rv) || (in == nsnull)) { - // Create the incoming server and an account for it? - rv = accMgr->CreateIncomingServer( pStrs[kPopAccountNameStr]->get(), pStrs[kPopServerStr]->get(), "imap", getter_AddRefs( in)); - if (NS_SUCCEEDED( rv) && in) { - rv = in->SetType( "imap"); - // rv = in->SetHostName( pStrs[kPopServerStr]->get()); - // rv = in->SetUsername( pStrs[kPopAccountNameStr]->get()); - - IMPORT_LOG2( "Created IMAP server named: %s, userName: %s\n", pStrs[kPopServerStr]->get(), pStrs[kPopAccountNameStr]->get()); - - PRUnichar *pretty = ToNewUnicode(accName); - - IMPORT_LOG1( "\tSet pretty name to: %S\n", pretty); - - rv = in->SetPrettyName( pretty); - nsCRT::free( pretty); - - // We have a server, create an account. - nsCOMPtr account; - rv = accMgr->CreateAccount( getter_AddRefs( account)); - if (NS_SUCCEEDED( rv) && account) { - rv = account->SetIncomingServer( in); - - IMPORT_LOG0( "Created an account and set the IMAP server as the incoming server\n"); - - // Fiddle with the identities - SetIdentities(accMgr, account, pStrs[kPopAccountNameStr]->get(), pStrs[kPopServerStr]->get(), pStrs); - result = PR_TRUE; - if (ppAccount) - account->QueryInterface( NS_GET_IID(nsIMsgAccount), (void **)ppAccount); - } - } - } - else - result = PR_TRUE; + // Fiddle with the identities + SetIdentities(accMgr, account, pStrs[kPopAccountNameStr]->get(), pStrs[kPopServerStr]->get(), pStrs); + result = PR_TRUE; + if (ppAccount) + CallQueryInterface(account, ppAccount); + } + } + } + else + result = PR_TRUE; - return( result); + return( result); } void nsEudoraMac::SetIdentities(nsIMsgAccountManager *accMgr, nsIMsgAccount *acc, const char *userName, const char *serverName, nsCString **pStrs) { - nsresult rv; - - nsCOMPtr id; - rv = accMgr->CreateIdentity( getter_AddRefs( id)); - if (id) { - nsAutoString fullName; - if (pStrs[kFullNameStr]->Length()) { - fullName.AssignWithConversion(pStrs[kFullNameStr]->get()); - } - id->SetFullName( fullName.get()); - id->SetIdentityName( fullName.get()); - if (pStrs[kReturnAddressStr]->Length()) { - id->SetEmail( pStrs[kReturnAddressStr]->get()); - } - else { - nsCAutoString emailAddress; - emailAddress = userName; - emailAddress += "@"; - emailAddress += serverName; - id->SetEmail(emailAddress.get()); - } - acc->AddIdentity( id); - - IMPORT_LOG0( "Created identity and added to the account\n"); - IMPORT_LOG1( "\tname: %s\n", pStrs[kFullNameStr]->get()); - IMPORT_LOG1( "\temail: %s\n", pStrs[kReturnAddressStr]->get()); - } + nsresult rv; + + nsCOMPtr id; + rv = accMgr->CreateIdentity( getter_AddRefs( id)); + if (id) { + nsAutoString fullName; + if (pStrs[kFullNameStr]->Length()) { + fullName.AssignWithConversion(pStrs[kFullNameStr]->get()); + } + id->SetFullName( fullName.get()); + id->SetIdentityName( fullName.get()); + if (pStrs[kReturnAddressStr]->Length()) { + id->SetEmail( pStrs[kReturnAddressStr]->get()); + } + else { + nsCAutoString emailAddress; + emailAddress = userName; + emailAddress += "@"; + emailAddress += serverName; + id->SetEmail(emailAddress.get()); + } + acc->AddIdentity( id); - SetSmtpServer( accMgr, acc, pStrs[kSmtpServerStr]->get(), userName); - + IMPORT_LOG0( "Created identity and added to the account\n"); + IMPORT_LOG1( "\tname: %s\n", pStrs[kFullNameStr]->get()); + IMPORT_LOG1( "\temail: %s\n", pStrs[kReturnAddressStr]->get()); + } + + SetSmtpServer( accMgr, acc, pStrs[kSmtpServerStr]->get(), userName); + } void nsEudoraMac::SetSmtpServer( nsIMsgAccountManager *pMgr, nsIMsgAccount *pAcc, const char *pServer, const char *pUser) { - nsresult rv; - - nsCOMPtr smtpService(do_GetService(NS_SMTPSERVICE_CONTRACTID, &rv)); - if (NS_SUCCEEDED(rv) && smtpService) { - nsCOMPtr foundServer; - - rv = smtpService->FindServer( pUser, pServer, getter_AddRefs( foundServer)); - if (NS_SUCCEEDED( rv) && foundServer) { - IMPORT_LOG1( "SMTP server already exists: %s\n", pServer); - return; - } - nsCOMPtr smtpServer; - - rv = smtpService->CreateSmtpServer( getter_AddRefs( smtpServer)); - if (NS_SUCCEEDED( rv) && smtpServer) { - smtpServer->SetHostname( pServer); - if (pUser) - smtpServer->SetUsername( pUser); - - IMPORT_LOG1( "Created new SMTP server: %s\n", pServer); - } - } + nsresult rv; + + nsCOMPtr smtpService(do_GetService(NS_SMTPSERVICE_CONTRACTID, &rv)); + if (NS_SUCCEEDED(rv) && smtpService) { + nsCOMPtr foundServer; + + rv = smtpService->FindServer( pUser, pServer, getter_AddRefs( foundServer)); + if (NS_SUCCEEDED( rv) && foundServer) { + IMPORT_LOG1( "SMTP server already exists: %s\n", pServer); + return; + } + nsCOMPtr smtpServer; + + rv = smtpService->CreateSmtpServer( getter_AddRefs( smtpServer)); + if (NS_SUCCEEDED( rv) && smtpServer) { + smtpServer->SetHostname( pServer); + if (pUser) + smtpServer->SetUsername( pUser); + + IMPORT_LOG1( "Created new SMTP server: %s\n", pServer); + } + } } nsresult nsEudoraMac::GetAttachmentInfo( const char *pFileName, nsIFileSpec *pSpec, nsCString& mimeType, nsCString& aAttachment) { - mimeType.Truncate(); + mimeType.Truncate(); - // Sample attachment line - // Internet:sandh.jpg (JPEG/JVWR) (0003C2E8) - - OSType type = '????'; - OSType creator = '????'; - PRUint32 fNum = 0; - int i; - PRUnichar c; - - nsCString str(pFileName); - if (str.Length() > 22) { - // try and extract the mac file info from the attachment line - nsCString fileNum; - nsCString types; - - str.Right( fileNum, 10); - if ((fileNum.CharAt( 0) == '(') && (fileNum.CharAt( 9) == ')')) { - for (i = 1; i < 9; i++) { - fNum *= 16; - c = fileNum.CharAt( i); - if ((c >= '0') && (c <= '9')) - fNum += (c - '0'); - else if ((c >= 'a') && (c <= 'f')) - fNum += (c - 'a' + 10); - else if ((c >= 'A') && (c <= 'F')) - fNum += (c - 'A' + 10); - else - break; - } - if (i == 9) { - str.Left( fileNum, str.Length() - 10); - str = fileNum; - str.Trim( kWhitespace); - str.Right( types, 11); - if ((types.CharAt( 0) == '(') && (types.CharAt( 5) == '/') && (types.CharAt( 10) == ')')) { - type = ((PRUint32)types.CharAt( 1)) << 24; - type |= ((PRUint32)types.CharAt( 2)) << 16; - type |= types.CharAt( 3) << 8; - type |= types.CharAt( 4); - creator = ((PRUint32)types.CharAt( 6)) << 24; - creator |= ((PRUint32)types.CharAt( 7)) << 16; - creator |= types.CharAt( 8) << 8; - creator |= types.CharAt( 9); - str.Left( types, str.Length() - 11); - str = types; - str.Trim( kWhitespace); - } - } - else - fNum = 0; - } - } - + // Sample attachment line + // Internet:sandh.jpg (JPEG/JVWR) (0003C2E8) + + OSType type = '????'; + OSType creator = '????'; + PRUint32 fNum = 0; + int i; + PRUnichar c; + + nsCString str(pFileName); + if (str.Length() > 22) { + // try and extract the mac file info from the attachment line + nsCString fileNum; + nsCString types; + + str.Right( fileNum, 10); + if ((fileNum.CharAt( 0) == '(') && (fileNum.CharAt( 9) == ')')) { + for (i = 1; i < 9; i++) { + fNum *= 16; + c = fileNum.CharAt( i); + if ((c >= '0') && (c <= '9')) + fNum += (c - '0'); + else if ((c >= 'a') && (c <= 'f')) + fNum += (c - 'a' + 10); + else if ((c >= 'A') && (c <= 'F')) + fNum += (c - 'A' + 10); + else + break; + } + if (i == 9) { + str.Left( fileNum, str.Length() - 10); + str = fileNum; + str.Trim( kWhitespace); + str.Right( types, 11); + if ((types.CharAt( 0) == '(') && (types.CharAt( 5) == '/') && (types.CharAt( 10) == ')')) { + type = ((PRUint32)types.CharAt( 1)) << 24; + type |= ((PRUint32)types.CharAt( 2)) << 16; + type |= types.CharAt( 3) << 8; + type |= types.CharAt( 4); + creator = ((PRUint32)types.CharAt( 6)) << 24; + creator |= ((PRUint32)types.CharAt( 7)) << 16; + creator |= types.CharAt( 8) << 8; + creator |= types.CharAt( 9); + str.Left( types, str.Length() - 11); + str = types; + str.Trim( kWhitespace); + } + } + else + fNum = 0; + } + } + #ifdef IMPORT_DEBUG - nsCString typeStr; - nsCString creatStr; - - creatStr.Append( (const char *)&creator, 4); - typeStr.Append( (const char *)&type, 4); - IMPORT_LOG3( "\tAttachment type: %s, creator: %s, fileNum: %ld\n", typeStr.get(), creatStr.get(), fNum); - IMPORT_LOG1( "\tAttachment file name: %s\n", str.get()); + nsCString typeStr; + nsCString creatStr; + + creatStr.Append( (const char *)&creator, 4); + typeStr.Append( (const char *)&type, 4); + IMPORT_LOG3( "\tAttachment type: %s, creator: %s, fileNum: %ld\n", typeStr.get(), creatStr.get(), fNum); + IMPORT_LOG1( "\tAttachment file name: %s\n", str.get()); #endif - FSSpec spec; - memset( &spec, 0, sizeof( spec)); + FSSpec spec; + memset( &spec, 0, sizeof( spec)); #ifdef XP_MACOSX { nsresult rv = pSpec->SetNativePath(str.get()); @@ -1058,7 +1058,7 @@ } char *pLeaf = nsnull; - pSpec->GetLeafName( &pLeaf); + pSpec->GetLeafName( &pLeaf); aAttachment.Adopt(pLeaf); nsCOMPtr macFile; @@ -1075,61 +1075,61 @@ } } #else - // Now we have all of the pertinent info, find out if the file exists? - nsCString fileName; - if ((str.CharAt( 0) == '"') && (str.Last() == '"')) { - str.Mid( fileName, 1, str.Length() - 2); - str = fileName; - } - - PRInt32 idx = str.FindChar( ':'); - if (idx == -1) { - return( NS_ERROR_FAILURE); - } - - nsCString volumeName; - str.Left( volumeName, idx + 1); - str.Right( fileName, str.Length() - idx - 1); - - // Create a FSSpec from the volume name, fileName, and folderNumber - // Assume that we are looking for a file on the volume with macFileId - Str63 str63; - short vRefNum = 0; - if (volumeName.Length() > 63) { - memcpy( &(str63[1]), volumeName.get(), 63); - str63[0] = 63; - } - else { - memcpy( &(str63[1]), volumeName.get(), volumeName.Length()); - str63[0] = volumeName.Length(); - } - - OSErr err = DetermineVRefNum( str63, 0, &vRefNum); - if (err != noErr) { - IMPORT_LOG0( "\t*** Error cannot find volume ref num\n"); - return( NS_ERROR_FAILURE); - } - - err = FSpResolveFileIDRef( nil, vRefNum, (long) fNum, &spec); - if (err != noErr) { - IMPORT_LOG1( "\t*** Error, cannot resolve fileIDRef: %ld\n", (long) err); - return( NS_ERROR_FAILURE); - } - - - FInfo fInfo; - err = FSpGetFInfo( &spec, &fInfo); - if ((err != noErr) || (fInfo.fdType != (OSType) type)) { - IMPORT_LOG0( "\t*** Error, file type does not match\n"); - return( NS_ERROR_FAILURE); - } - - nsFileSpec fSpec( spec); - pSpec->SetFromFileSpec( fSpec); + // Now we have all of the pertinent info, find out if the file exists? + nsCString fileName; + if ((str.CharAt( 0) == '"') && (str.Last() == '"')) { + str.Mid( fileName, 1, str.Length() - 2); + str = fileName; + } + + PRInt32 idx = str.FindChar( ':'); + if (idx == -1) { + return( NS_ERROR_FAILURE); + } + + nsCString volumeName; + str.Left( volumeName, idx + 1); + str.Right( fileName, str.Length() - idx - 1); + + // Create a FSSpec from the volume name, fileName, and folderNumber + // Assume that we are looking for a file on the volume with macFileId + Str63 str63; + short vRefNum = 0; + if (volumeName.Length() > 63) { + memcpy( &(str63[1]), volumeName.get(), 63); + str63[0] = 63; + } + else { + memcpy( &(str63[1]), volumeName.get(), volumeName.Length()); + str63[0] = volumeName.Length(); + } + + OSErr err = DetermineVRefNum( str63, 0, &vRefNum); + if (err != noErr) { + IMPORT_LOG0( "\t*** Error cannot find volume ref num\n"); + return( NS_ERROR_FAILURE); + } + + err = FSpResolveFileIDRef( nil, vRefNum, (long) fNum, &spec); + if (err != noErr) { + IMPORT_LOG1( "\t*** Error, cannot resolve fileIDRef: %ld\n", (long) err); + return( NS_ERROR_FAILURE); + } + + + FInfo fInfo; + err = FSpGetFInfo( &spec, &fInfo); + if ((err != noErr) || (fInfo.fdType != (OSType) type)) { + IMPORT_LOG0( "\t*** Error, file type does not match\n"); + return( NS_ERROR_FAILURE); + } + + nsFileSpec fSpec( spec); + pSpec->SetFromFileSpec( fSpec); #endif - + #ifdef XP_MACOSX - if (HasResourceFork(&spec)) + if (HasResourceFork(&spec)) #else // Need to find the mime type for the attachment? long dataSize = 0; @@ -1143,15 +1143,15 @@ if (rsrcSize) #endif - mimeType = "application/applefile"; - else - mimeType = "application/octet-stream"; - - IMPORT_LOG1( "\tMimeType: %s\n", mimeType.get()); - - return( NS_OK); + mimeType = "application/applefile"; + else + mimeType = "application/octet-stream"; + + IMPORT_LOG1( "\tMimeType: %s\n", mimeType.get()); + + return( NS_OK); } - + PRBool nsEudoraMac::HasResourceFork(FSSpec *fsSpec) { FSRef fsRef; @@ -1165,64 +1165,64 @@ } -#define kNumBadFolderNames 7 +#define kNumBadFolderNames 7 const char *cBadFolderNames[kNumBadFolderNames] = { - "Attachments Folder", - "Eudora Items", - "Nicknames Folder", - "Parts Folder", - "Signature Folder", - "Spool Folder", - "Stationery Folder" + "Attachments Folder", + "Eudora Items", + "Nicknames Folder", + "Parts Folder", + "Signature Folder", + "Spool Folder", + "Stationery Folder" }; PRBool nsEudoraMac::IsValidMailFolderName( nsCString& name) { - if (m_depth > 1) - return( PR_TRUE); - - for (int i = 0; i < kNumBadFolderNames; i++) { - if (name.Equals( cBadFolderNames[i], nsCaseInsensitiveCStringComparator())) - return( PR_FALSE); - } - - return( PR_TRUE); + if (m_depth > 1) + return( PR_TRUE); + + for (int i = 0; i < kNumBadFolderNames; i++) { + if (name.Equals( cBadFolderNames[i], nsCaseInsensitiveCStringComparator())) + return( PR_FALSE); + } + + return( PR_TRUE); } PRBool nsEudoraMac::IsValidMailboxName( nsCString& fName) { - if (m_depth > 1) - return( PR_TRUE); - if (fName.Equals(NS_LITERAL_CSTRING("Eudora Nicknames"), nsCaseInsensitiveCStringComparator())) - return( PR_FALSE); - return( PR_TRUE); + if (m_depth > 1) + return( PR_TRUE); + if (fName.Equals(NS_LITERAL_CSTRING("Eudora Nicknames"), nsCaseInsensitiveCStringComparator())) + return( PR_FALSE); + return( PR_TRUE); } PRBool nsEudoraMac::IsValidMailboxFile( nsIFileSpec *pFile) { - PRUint32 size = 0; - nsresult rv = pFile->GetFileSize( &size); - if (size) { - if (size < 10) - return( PR_FALSE); - rv = pFile->OpenStreamForReading(); - if (NS_FAILED( rv)) - return( PR_FALSE); - PRInt32 read = 0; - char buffer[6]; - char * pBuf = buffer; - rv = pFile->Read( &pBuf, 5, &read); - pFile->CloseStream(); - if (NS_FAILED( rv) || (read != 5)) - return( PR_FALSE); - buffer[5] = 0; - if (nsCRT::strcmp( buffer, "From ")) - return( PR_FALSE); - } - - return( PR_TRUE); + PRUint32 size = 0; + nsresult rv = pFile->GetFileSize( &size); + if (size) { + if (size < 10) + return( PR_FALSE); + rv = pFile->OpenStreamForReading(); + if (NS_FAILED( rv)) + return( PR_FALSE); + PRInt32 read = 0; + char buffer[6]; + char * pBuf = buffer; + rv = pFile->Read( &pBuf, 5, &read); + pFile->CloseStream(); + if (NS_FAILED( rv) || (read != 5)) + return( PR_FALSE); + buffer[5] = 0; + if (nsCRT::strcmp( buffer, "From ")) + return( PR_FALSE); + } + + return( PR_TRUE); } @@ -1230,121 +1230,121 @@ PRBool nsEudoraMac::FindAddressFolder( nsIFileSpec *pFolder) { - return( FindEudoraLocation( pFolder)); + return( FindEudoraLocation( pFolder)); } nsresult nsEudoraMac::FindAddressBooks( nsIFileSpec *pRoot, nsISupportsArray **ppArray) { - // Look for the nicknames file in this folder and then - // additional files in the Nicknames folder - // Try and find the nickNames file - nsCOMPtr spec; - nsresult rv = NS_NewFileSpec( getter_AddRefs( spec)); - if (NS_FAILED( rv)) - return( rv); - rv = spec->FromFileSpec( pRoot); - if (NS_FAILED( rv)) - return( rv); - rv = NS_NewISupportsArray( ppArray); - if (NS_FAILED( rv)) { - IMPORT_LOG0( "FAILED to allocate the nsISupportsArray\n"); - return( rv); - } - - nsCOMPtr impSvc(do_GetService(NS_IMPORTSERVICE_CONTRACTID, &rv)); - if (NS_FAILED( rv)) - return( rv); - - - nsString displayName; - nsEudoraStringBundle::GetStringByID( EUDORAIMPORT_NICKNAMES_NAME, displayName); - PRUint32 sz = 0; - - // First find the Nicknames file itself - rv = spec->AppendRelativeUnixPath( "Eudora Nicknames"); - PRBool exists = PR_FALSE; - PRBool isFile = PR_FALSE; - if (NS_SUCCEEDED( rv)) - rv = spec->Exists( &exists); - if (NS_SUCCEEDED( rv) && exists) - rv = spec->IsFile( &isFile); - - nsCOMPtr desc; - nsISupports * pInterface; - - if (exists && isFile) { - rv = impSvc->CreateNewABDescriptor( getter_AddRefs( desc)); - if (NS_SUCCEEDED( rv)) { - sz = 0; - spec->GetFileSize( &sz); - desc->SetPreferredName( displayName.get()); - desc->SetSize( sz); - nsIFileSpec *pSpec = nsnull; - desc->GetFileSpec( &pSpec); - if (pSpec) { - pSpec->FromFileSpec( spec); - NS_RELEASE( pSpec); - } - rv = desc->QueryInterface( kISupportsIID, (void **) &pInterface); - (*ppArray)->AppendElement( pInterface); - pInterface->Release(); - } - if (NS_FAILED( rv)) { - IMPORT_LOG0( "*** Error creating address book descriptor for eudora nicknames\n"); - return( rv); - } - } - - // Now try the directory of address books! - rv = spec->FromFileSpec( pRoot); - if (NS_SUCCEEDED( rv)) - rv = spec->AppendRelativeUnixPath( "Nicknames Folder"); - exists = PR_FALSE; - PRBool isDir = PR_FALSE; - if (NS_SUCCEEDED( rv)) - rv = spec->Exists( &exists); - if (NS_SUCCEEDED( rv) && exists) - rv = spec->IsDirectory( &isDir); - - if (!isDir) - return( NS_OK); - - // We need to iterate the directory - nsCOMPtr dir; - rv = NS_NewDirectoryIterator( getter_AddRefs( dir)); - if (NS_FAILED( rv)) - return( rv); - - exists = PR_FALSE; - rv = dir->Init( spec, PR_TRUE); - if (NS_FAILED( rv)) - return( rv); - - rv = dir->Exists( &exists); - if (NS_FAILED( rv)) - return( rv); - - char * pName; - nsFileSpec fSpec; - OSType type; - OSType creator; - - while (exists && NS_SUCCEEDED( rv)) { - rv = dir->GetCurrentSpec( getter_AddRefs( spec)); - if (NS_SUCCEEDED( rv)) { - isFile = PR_FALSE; - pName = nsnull; - rv = spec->IsFile( &isFile); - rv = spec->GetLeafName( &pName); - if (pName) { - NS_CopyNativeToUnicode(nsDependentCString(pName), displayName); - nsCRT::free( pName); - } - if (NS_SUCCEEDED( rv) && pName && isFile) { - rv = spec->GetFileSpec( &fSpec); - if (NS_SUCCEEDED( rv)) { - type = 0; - creator = 0; + // Look for the nicknames file in this folder and then + // additional files in the Nicknames folder + // Try and find the nickNames file + nsCOMPtr spec; + nsresult rv = NS_NewFileSpec( getter_AddRefs( spec)); + if (NS_FAILED( rv)) + return( rv); + rv = spec->FromFileSpec( pRoot); + if (NS_FAILED( rv)) + return( rv); + rv = NS_NewISupportsArray( ppArray); + if (NS_FAILED( rv)) { + IMPORT_LOG0( "FAILED to allocate the nsISupportsArray\n"); + return( rv); + } + + nsCOMPtr impSvc(do_GetService(NS_IMPORTSERVICE_CONTRACTID, &rv)); + if (NS_FAILED( rv)) + return( rv); + + + nsString displayName; + nsEudoraStringBundle::GetStringByID( EUDORAIMPORT_NICKNAMES_NAME, displayName); + PRUint32 sz = 0; + + // First find the Nicknames file itself + rv = spec->AppendRelativeUnixPath( "Eudora Nicknames"); + PRBool exists = PR_FALSE; + PRBool isFile = PR_FALSE; + if (NS_SUCCEEDED( rv)) + rv = spec->Exists( &exists); + if (NS_SUCCEEDED( rv) && exists) + rv = spec->IsFile( &isFile); + + nsCOMPtr desc; + nsISupports * pInterface; + + if (exists && isFile) { + rv = impSvc->CreateNewABDescriptor( getter_AddRefs( desc)); + if (NS_SUCCEEDED( rv)) { + sz = 0; + spec->GetFileSize( &sz); + desc->SetPreferredName( displayName.get()); + desc->SetSize( sz); + nsIFileSpec *pSpec = nsnull; + desc->GetFileSpec( &pSpec); + if (pSpec) { + pSpec->FromFileSpec( spec); + NS_RELEASE( pSpec); + } + rv = desc->QueryInterface( kISupportsIID, (void **) &pInterface); + (*ppArray)->AppendElement( pInterface); + pInterface->Release(); + } + if (NS_FAILED( rv)) { + IMPORT_LOG0( "*** Error creating address book descriptor for eudora nicknames\n"); + return( rv); + } + } + + // Now try the directory of address books! + rv = spec->FromFileSpec( pRoot); + if (NS_SUCCEEDED( rv)) + rv = spec->AppendRelativeUnixPath( "Nicknames Folder"); + exists = PR_FALSE; + PRBool isDir = PR_FALSE; + if (NS_SUCCEEDED( rv)) + rv = spec->Exists( &exists); + if (NS_SUCCEEDED( rv) && exists) + rv = spec->IsDirectory( &isDir); + + if (!isDir) + return( NS_OK); + + // We need to iterate the directory + nsCOMPtr dir; + rv = NS_NewDirectoryIterator( getter_AddRefs( dir)); + if (NS_FAILED( rv)) + return( rv); + + exists = PR_FALSE; + rv = dir->Init( spec, PR_TRUE); + if (NS_FAILED( rv)) + return( rv); + + rv = dir->Exists( &exists); + if (NS_FAILED( rv)) + return( rv); + + char * pName; + nsFileSpec fSpec; + OSType type; + OSType creator; + + while (exists && NS_SUCCEEDED( rv)) { + rv = dir->GetCurrentSpec( getter_AddRefs( spec)); + if (NS_SUCCEEDED( rv)) { + isFile = PR_FALSE; + pName = nsnull; + rv = spec->IsFile( &isFile); + rv = spec->GetLeafName( &pName); + if (pName) { + NS_CopyNativeToUnicode(nsDependentCString(pName), displayName); + nsCRT::free( pName); + } + if (NS_SUCCEEDED( rv) && pName && isFile) { + rv = spec->GetFileSpec( &fSpec); + if (NS_SUCCEEDED( rv)) { + type = 0; + creator = 0; #ifdef XP_MACOSX { nsCOMPtr macFile; @@ -1356,40 +1356,40 @@ } } #else - fSpec.GetFileTypeAndCreator( &type, &creator); + fSpec.GetFileTypeAndCreator( &type, &creator); #endif - if (type == 'TEXT') { - rv = impSvc->CreateNewABDescriptor( getter_AddRefs( desc)); - if (NS_SUCCEEDED( rv)) { - sz = 0; - spec->GetFileSize( &sz); - desc->SetPreferredName( displayName.get()); - desc->SetSize( sz); - nsIFileSpec *pSpec = nsnull; - desc->GetFileSpec( &pSpec); - if (pSpec) { - pSpec->FromFileSpec( spec); - NS_RELEASE( pSpec); - } - rv = desc->QueryInterface( kISupportsIID, (void **) &pInterface); - (*ppArray)->AppendElement( pInterface); - pInterface->Release(); - } - if (NS_FAILED( rv)) { - IMPORT_LOG0( "*** Error creating address book descriptor for eudora address book\n"); - return( rv); - } - } - } - } - } - - rv = dir->Next(); - if (NS_SUCCEEDED( rv)) - rv = dir->Exists( &exists); - } + if (type == 'TEXT') { + rv = impSvc->CreateNewABDescriptor( getter_AddRefs( desc)); + if (NS_SUCCEEDED( rv)) { + sz = 0; + spec->GetFileSize( &sz); + desc->SetPreferredName( displayName.get()); + desc->SetSize( sz); + nsIFileSpec *pSpec = nsnull; + desc->GetFileSpec( &pSpec); + if (pSpec) { + pSpec->FromFileSpec( spec); + NS_RELEASE( pSpec); + } + rv = desc->QueryInterface( kISupportsIID, (void **) &pInterface); + (*ppArray)->AppendElement( pInterface); + pInterface->Release(); + } + if (NS_FAILED( rv)) { + IMPORT_LOG0( "*** Error creating address book descriptor for eudora address book\n"); + return( rv); + } + } + } + } + } + + rv = dir->Next(); + if (NS_SUCCEEDED( rv)) + rv = dir->Exists( &exists); + } - - return( rv); + + return( rv); } Index: mozilla/mailnews/import/eudora/src/nsEudoraMailbox.cpp =================================================================== RCS file: /cvsroot/mozilla/mailnews/import/eudora/src/nsEudoraMailbox.cpp,v retrieving revision 1.27 diff -u -r1.27 mozilla/mailnews/import/eudora/src/nsEudoraMailbox.cpp --- mozilla/mailnews/import/eudora/src/nsEudoraMailbox.cpp +++ mozilla/mailnews/import/eudora/src/nsEudoraMailbox.cpp @@ -1,4 +1,4 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- +/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 @@ -47,11 +47,11 @@ #include "EudoraDebugLog.h" -#define kCopyBufferSize 8192 -#define kMailReadBufferSize 16384 +#define kCopyBufferSize 8192 +#define kMailReadBufferSize 16384 #define DATE_STR_LEN 64 // 64 bytes is plenty to hold the date header. -#define kWhitespace " \t\b\r\n" +#define kWhitespace " \t\b\r\n" const char *eudoraFromLine = "From - Mon Jan 1 00:00:00 1965\x0D\x0A"; @@ -60,61 +60,61 @@ void DUMP_FILENAME( nsIFileSpec *pSpec, PRBool endLine) { - char *pPath = nsnull; - if (pSpec) - pSpec->GetNativePath( &pPath); - if (pPath) { - IMPORT_LOG1( "%s", pPath); - nsCRT::free( pPath); - } - else { - IMPORT_LOG0( "Unknown"); - } - if (endLine) { - IMPORT_LOG0( "\n"); - } + char *pPath = nsnull; + if (pSpec) + pSpec->GetNativePath( &pPath); + if (pPath) { + IMPORT_LOG1( "%s", pPath); + nsCRT::free( pPath); + } + else { + IMPORT_LOG0( "Unknown"); + } + if (endLine) { + IMPORT_LOG0( "\n"); + } } -// #define DONT_DELETE_EUDORA_TEMP_FILES 1 +// #define DONT_DELETE_EUDORA_TEMP_FILES 1 #else #define DUMP_FILENAME( x, y) #endif static char *eudoraWeekDays[7] = { - "Mon", - "Tue", - "Wed", - "Thu", - "Fri", - "Sat", - "Sun" + "Mon", + "Tue", + "Wed", + "Thu", + "Fri", + "Sat", + "Sun" }; static char *eudoraMonths[12] = { - "Jan", - "Feb", - "Mar", - "Apr", - "May", - "Jun", - "Jul", - "Aug", - "Sep", - "Oct", - "Nov", - "Dec" + "Jan", + "Feb", + "Mar", + "Apr", + "May", + "Jun", + "Jul", + "Aug", + "Sep", + "Oct", + "Nov", + "Dec" }; nsEudoraMailbox::nsEudoraMailbox() { - m_fromLen = 0; + m_fromLen = 0; } nsEudoraMailbox::~nsEudoraMailbox() { - EmptyAttachments(); + EmptyAttachments(); } nsresult nsEudoraMailbox::CreateTempFile( nsIFileSpec **ppSpec) @@ -135,164 +135,164 @@ nsresult nsEudoraMailbox::DeleteFile( nsIFileSpec *pSpec) { - PRBool result; - nsresult rv = NS_OK; + PRBool result; + nsresult rv = NS_OK; - result = PR_FALSE; - pSpec->IsStreamOpen( &result); - if (result) - pSpec->CloseStream(); - result = PR_FALSE; - pSpec->Exists( &result); - if (result) { - result = PR_FALSE; - pSpec->IsFile( &result); - if (result) { - nsFileSpec spec; - rv = pSpec->GetFileSpec( &spec); + result = PR_FALSE; + pSpec->IsStreamOpen( &result); + if (result) + pSpec->CloseStream(); + result = PR_FALSE; + pSpec->Exists( &result); + if (result) { + result = PR_FALSE; + pSpec->IsFile( &result); + if (result) { + nsFileSpec spec; + rv = pSpec->GetFileSpec( &spec); #ifndef DONT_DELETE_EUDORA_TEMP_FILES - if (NS_SUCCEEDED( rv)) - spec.Delete( PR_FALSE); + if (NS_SUCCEEDED( rv)) + spec.Delete( PR_FALSE); #endif - } - } + } + } - return( rv); + return( rv); } -#define kComposeErrorStr "X-Eudora-Compose-Error: *****" "\x0D\x0A" +#define kComposeErrorStr "X-Eudora-Compose-Error: *****" "\x0D\x0A" #define kHTMLTag "" nsresult nsEudoraMailbox::ImportMailbox( PRUint32 *pBytes, PRBool *pAbort, const PRUnichar *pName, nsIFileSpec *pSrc, nsIFileSpec *pDst, PRInt32 *pMsgCount) { - nsCOMPtr tocFile; - PRBool deleteToc = PR_FALSE; - nsresult rv; - nsCOMPtr mailFile; - PRBool deleteMailFile = PR_FALSE; - PRUint32 div = 1; - PRUint32 mul = 1; - - if (pMsgCount) - *pMsgCount = 0; - - rv = pSrc->GetFileSize( &m_mailSize); - - rv = pSrc->OpenStreamForReading(); - if (NS_FAILED( rv)) - return( rv); - - NS_ADDREF( pSrc); - - // First, get the index file for this mailbox - rv = FindTOCFile( pSrc, getter_AddRefs( tocFile), &deleteToc); - if (NS_SUCCEEDED( rv) && tocFile) { - IMPORT_LOG0( "Reading euroda toc file: "); - DUMP_FILENAME( tocFile, PR_TRUE); - - rv = CreateTempFile( getter_AddRefs( mailFile)); - deleteMailFile = PR_TRUE; - if (NS_SUCCEEDED( rv)) { - // Read the TOC and compact the mailbox file into a temp file - rv = tocFile->OpenStreamForReading(); - if (NS_SUCCEEDED( rv)) { - rv = mailFile->OpenStreamForWriting(); - if (NS_SUCCEEDED( rv)) { - // Read the toc and compact the mailbox into mailFile - rv = CompactMailbox( pBytes, pAbort, pSrc, tocFile, mailFile); - div = 4; - mul = 3; - } - } - } - - pSrc->CloseStream(); - - // clean up - if (deleteToc) { - DeleteFile( tocFile); - } - if (NS_SUCCEEDED( rv)) - rv = mailFile->CloseStream(); - if (NS_FAILED( rv)) { - DeleteFile( mailFile); - mailFile->FromFileSpec( pSrc); - deleteMailFile = PR_FALSE; - IMPORT_LOG0( "*** Error compacting mailbox.\n"); - } - - IMPORT_LOG0( "Compacted mailbox: "); DUMP_FILENAME( mailFile, PR_TRUE); - - rv = mailFile->OpenStreamForReading(); - if (NS_SUCCEEDED( rv)) { - pSrc->Release(); - mailFile->QueryInterface( NS_GET_IID(nsIFileSpec), (void **)&pSrc); - - IMPORT_LOG0( "Compacting mailbox was successful\n"); - } - else { - DeleteFile( mailFile); - deleteMailFile = PR_FALSE; - IMPORT_LOG0( "*** Error accessing compacted mailbox\n"); - } - } - - // So, where we are now, is we have the mail file to import in pSrc - // It may need deleting if deleteMailFile is PR_TRUE. - // pSrc must be Released before returning - - // The source file contains partially constructed mail messages, - // and attachments. We should first investigate if we can use the mailnews msgCompose - // stuff to do the work for us. If not we have to scan the mailboxes and do TONS - // of work to properly reconstruct the message - Eudora is so nice that it strips things - // like MIME headers, character encoding, and attachments - beautiful! - - rv = pSrc->GetFileSize( &m_mailSize); - - nsCOMPtr compositionFile; - SimpleBufferTonyRCopiedOnce readBuffer; - SimpleBufferTonyRCopiedOnce headers; - SimpleBufferTonyRCopiedOnce body; - SimpleBufferTonyRCopiedOnce copy; - PRInt32 written; - nsCString fromLine(eudoraFromLine); - - headers.m_convertCRs = PR_TRUE; - body.m_convertCRs = PR_TRUE; - - copy.Allocate( kCopyBufferSize); - readBuffer.Allocate( kMailReadBufferSize); - ReadFileState state; - state.offset = 0; - state.size = m_mailSize; - state.pFile = pSrc; + nsCOMPtr tocFile; + PRBool deleteToc = PR_FALSE; + nsresult rv; + nsCOMPtr mailFile; + PRBool deleteMailFile = PR_FALSE; + PRUint32 div = 1; + PRUint32 mul = 1; + + if (pMsgCount) + *pMsgCount = 0; + + rv = pSrc->GetFileSize( &m_mailSize); + + rv = pSrc->OpenStreamForReading(); + if (NS_FAILED( rv)) + return( rv); + + NS_ADDREF( pSrc); + + // First, get the index file for this mailbox + rv = FindTOCFile( pSrc, getter_AddRefs( tocFile), &deleteToc); + if (NS_SUCCEEDED( rv) && tocFile) { + IMPORT_LOG0( "Reading euroda toc file: "); + DUMP_FILENAME( tocFile, PR_TRUE); + + rv = CreateTempFile( getter_AddRefs( mailFile)); + deleteMailFile = PR_TRUE; + if (NS_SUCCEEDED( rv)) { + // Read the TOC and compact the mailbox file into a temp file + rv = tocFile->OpenStreamForReading(); + if (NS_SUCCEEDED( rv)) { + rv = mailFile->OpenStreamForWriting(); + if (NS_SUCCEEDED( rv)) { + // Read the toc and compact the mailbox into mailFile + rv = CompactMailbox( pBytes, pAbort, pSrc, tocFile, mailFile); + div = 4; + mul = 3; + } + } + } + + pSrc->CloseStream(); + + // clean up + if (deleteToc) { + DeleteFile( tocFile); + } + if (NS_SUCCEEDED( rv)) + rv = mailFile->CloseStream(); + if (NS_FAILED( rv)) { + DeleteFile( mailFile); + mailFile->FromFileSpec( pSrc); + deleteMailFile = PR_FALSE; + IMPORT_LOG0( "*** Error compacting mailbox.\n"); + } + + IMPORT_LOG0( "Compacted mailbox: "); DUMP_FILENAME( mailFile, PR_TRUE); + + rv = mailFile->OpenStreamForReading(); + if (NS_SUCCEEDED( rv)) { + pSrc->Release(); + CallQueryInterface(mailFile, &pSrc); + + IMPORT_LOG0( "Compacting mailbox was successful\n"); + } + else { + DeleteFile( mailFile); + deleteMailFile = PR_FALSE; + IMPORT_LOG0( "*** Error accessing compacted mailbox\n"); + } + } + + // So, where we are now, is we have the mail file to import in pSrc + // It may need deleting if deleteMailFile is PR_TRUE. + // pSrc must be Released before returning + + // The source file contains partially constructed mail messages, + // and attachments. We should first investigate if we can use the mailnews msgCompose + // stuff to do the work for us. If not we have to scan the mailboxes and do TONS + // of work to properly reconstruct the message - Eudora is so nice that it strips things + // like MIME headers, character encoding, and attachments - beautiful! + + rv = pSrc->GetFileSize( &m_mailSize); + + nsCOMPtr compositionFile; + SimpleBufferTonyRCopiedOnce readBuffer; + SimpleBufferTonyRCopiedOnce headers; + SimpleBufferTonyRCopiedOnce body; + SimpleBufferTonyRCopiedOnce copy; + PRInt32 written; + nsCString fromLine(eudoraFromLine); + + headers.m_convertCRs = PR_TRUE; + body.m_convertCRs = PR_TRUE; + + copy.Allocate( kCopyBufferSize); + readBuffer.Allocate( kMailReadBufferSize); + ReadFileState state; + state.offset = 0; + state.size = m_mailSize; + state.pFile = pSrc; - IMPORT_LOG0( "Reading mailbox\n"); + IMPORT_LOG0( "Reading mailbox\n"); - if (NS_SUCCEEDED( rv = NS_NewFileSpec( getter_AddRefs( compositionFile)))) { - nsEudoraCompose compose; + if (NS_SUCCEEDED( rv = NS_NewFileSpec( getter_AddRefs( compositionFile)))) { + nsEudoraCompose compose; nsCString defaultDate; nsCAutoString bodyType; - - /* - IMPORT_LOG0( "Calling compose.SendMessage\n"); - rv = compose.SendMessage( compositionFile); - if (NS_SUCCEEDED( rv)) { - IMPORT_LOG0( "Composed message in file: "); DUMP_FILENAME( compositionFile, PR_TRUE); - } - else { - IMPORT_LOG0( "*** Error composing message\n"); - } - */ + + /* + IMPORT_LOG0( "Calling compose.SendMessage\n"); + rv = compose.SendMessage( compositionFile); + if (NS_SUCCEEDED( rv)) { + IMPORT_LOG0( "Composed message in file: "); DUMP_FILENAME( compositionFile, PR_TRUE); + } + else { + IMPORT_LOG0( "*** Error composing message\n"); + } + */ - IMPORT_LOG0( "Reading first message\n"); + IMPORT_LOG0( "Reading first message\n"); while (!*pAbort && NS_SUCCEEDED( rv = ReadNextMessage( &state, readBuffer, headers, body, defaultDate, bodyType))) { - - if (pBytes) { - *pBytes += (((body.m_writeOffset - 1 + headers.m_writeOffset - 1) / div) * mul); - } + + if (pBytes) { + *pBytes += (((body.m_writeOffset - 1 + headers.m_writeOffset - 1) / div) * mul); + } // Unfortunately Eudora stores HTML messages in the sent folder // without any content type header at all. If the first line of the message body is @@ -301,152 +301,152 @@ bodyType = "text/html"; // ignore whatever body type we were given...force html compose.SetBody( body.m_pBuffer, body.m_writeOffset - 1, bodyType); - compose.SetHeaders( headers.m_pBuffer, headers.m_writeOffset - 1); - compose.SetAttachments( &m_attachments); + compose.SetHeaders( headers.m_pBuffer, headers.m_writeOffset - 1); + compose.SetAttachments( &m_attachments); compose.SetDefaultDate(defaultDate); - rv = compose.SendTheMessage( compositionFile); - if (NS_SUCCEEDED( rv)) { - /* IMPORT_LOG0( "Composed message in file: "); DUMP_FILENAME( compositionFile, PR_TRUE); */ - // copy the resulting file into the destination file! - rv = compose.CopyComposedMessage( fromLine, compositionFile, pDst, copy); - DeleteFile( compositionFile); - if (NS_FAILED( rv)) { - IMPORT_LOG0( "*** Error copying composed message to destination mailbox\n"); - break; - } - if (pMsgCount) - (*pMsgCount)++; - } - else { - IMPORT_LOG0( "*** Error composing message, writing raw message\n"); - rv = WriteFromSep( pDst); - - rv = pDst->Write( kComposeErrorStr, - strlen( kComposeErrorStr), - &written ); - - if (NS_SUCCEEDED( rv)) - rv = pDst->Write( headers.m_pBuffer, headers.m_writeOffset - 1, &written); - if (NS_SUCCEEDED( rv) && (written == (headers.m_writeOffset - 1))) - rv = pDst->Write( "\x0D\x0A" "\x0D\x0A", 4, &written); - if (NS_SUCCEEDED( rv) && (written == 4)) - rv = pDst->Write( body.m_pBuffer, body.m_writeOffset - 1, &written); - if (NS_SUCCEEDED( rv) && (written == (body.m_writeOffset - 1))) { - rv = pDst->Write( "\x0D\x0A", 2, &written); - if (written != 2) - rv = NS_ERROR_FAILURE; - } - - if (NS_FAILED( rv)) { - IMPORT_LOG0( "*** Error writing to destination mailbox\n"); - break; - } - } - - if (!readBuffer.m_bytesInBuf && (state.offset >= state.size)) - break; - } - - } - else { - IMPORT_LOG0( "*** Error creating file spec for composition\n"); - } - - if (deleteMailFile) - DeleteFile( pSrc); - - pSrc->Release(); + rv = compose.SendTheMessage( compositionFile); + if (NS_SUCCEEDED( rv)) { + /* IMPORT_LOG0( "Composed message in file: "); DUMP_FILENAME( compositionFile, PR_TRUE); */ + // copy the resulting file into the destination file! + rv = compose.CopyComposedMessage( fromLine, compositionFile, pDst, copy); + DeleteFile( compositionFile); + if (NS_FAILED( rv)) { + IMPORT_LOG0( "*** Error copying composed message to destination mailbox\n"); + break; + } + if (pMsgCount) + (*pMsgCount)++; + } + else { + IMPORT_LOG0( "*** Error composing message, writing raw message\n"); + rv = WriteFromSep( pDst); + + rv = pDst->Write( kComposeErrorStr, + strlen( kComposeErrorStr), + &written ); + + if (NS_SUCCEEDED( rv)) + rv = pDst->Write( headers.m_pBuffer, headers.m_writeOffset - 1, &written); + if (NS_SUCCEEDED( rv) && (written == (headers.m_writeOffset - 1))) + rv = pDst->Write( "\x0D\x0A" "\x0D\x0A", 4, &written); + if (NS_SUCCEEDED( rv) && (written == 4)) + rv = pDst->Write( body.m_pBuffer, body.m_writeOffset - 1, &written); + if (NS_SUCCEEDED( rv) && (written == (body.m_writeOffset - 1))) { + rv = pDst->Write( "\x0D\x0A", 2, &written); + if (written != 2) + rv = NS_ERROR_FAILURE; + } + + if (NS_FAILED( rv)) { + IMPORT_LOG0( "*** Error writing to destination mailbox\n"); + break; + } + } + + if (!readBuffer.m_bytesInBuf && (state.offset >= state.size)) + break; + } + + } + else { + IMPORT_LOG0( "*** Error creating file spec for composition\n"); + } + + if (deleteMailFile) + DeleteFile( pSrc); + + pSrc->Release(); - return( rv); + return( rv); } #ifdef XP_MACOSX -#define kMsgHeaderSize 220 -#define kMsgFirstOffset 278 +#define kMsgHeaderSize 220 +#define kMsgFirstOffset 278 #else -#define kMsgHeaderSize 218 -#define kMsgFirstOffset 104 +#define kMsgHeaderSize 218 +#define kMsgFirstOffset 104 #endif nsresult nsEudoraMailbox::CompactMailbox( PRUint32 *pBytes, PRBool *pAbort, nsIFileSpec *pMail, nsIFileSpec *pToc, nsIFileSpec *pDst) { - PRUint32 mailSize = m_mailSize; - PRUint32 tocSize = 0; - PRUint32 msgCount = 0; - nsresult rv; - - rv = pToc->GetFileSize( &tocSize); - - // if the index or the mail file is empty then just - // use the original mail file. - if (!mailSize || !tocSize) - return( NS_ERROR_FAILURE); - - SimpleBufferTonyRCopiedOnce copy; - PRBool done = PR_FALSE; - PRInt32 tocOffset = kMsgFirstOffset; - PRInt32 data[2]; - PRInt32 count; - PRInt32 read; - PRInt32 written; - char * pBuffer; - char lastChar; - - copy.Allocate( kCopyBufferSize); - - IMPORT_LOG0( "Compacting mailbox: "); - - while (!*pAbort && (tocOffset < (PRInt32)tocSize)) { - if (NS_FAILED( rv = pToc->Seek( tocOffset))) return( rv); - pBuffer = (char *)data; - if (NS_FAILED( rv = pToc->Read( &pBuffer, 8, &read)) || (read != 8)) - return( NS_ERROR_FAILURE); - // data[0] is the message offset, data[1] is the message size - if (NS_FAILED( rv = pMail->Seek( data[0]))) return( rv); - count = kCopyBufferSize; - if (count > data[1]) - count = data[1]; - pBuffer = copy.m_pBuffer; - if (NS_FAILED( rv = pMail->Read( &pBuffer, count, &read)) || (read != count)) - return( NS_ERROR_FAILURE); - if (count < 6) - return( NS_ERROR_FAILURE); - if ((copy.m_pBuffer[0] != 'F') || (copy.m_pBuffer[1] != 'r') || - (copy.m_pBuffer[2] != 'o') || (copy.m_pBuffer[3] != 'm') || - (copy.m_pBuffer[4] != ' ')) - return( NS_ERROR_FAILURE); - - if (pBytes) - *pBytes += (data[1] / 4); - // Looks like everything is cool, we have a message that appears to start with a separator - while (data[1]) { - lastChar = copy.m_pBuffer[count - 1]; - if (NS_FAILED( rv = pDst->Write( copy.m_pBuffer, count, &written)) || (written != count)) - return( NS_ERROR_FAILURE); - data[1] -= count; - if (data[1]) { - pBuffer = copy.m_pBuffer; - count = kCopyBufferSize; - if (count > data[1]) - count = data[1]; - if (NS_FAILED( rv = pMail->Read( &pBuffer, count, &read)) || (read != count)) - return( NS_ERROR_FAILURE); - } - } - if ((lastChar != 0x0D) && (lastChar != 0x0A)) { - if (NS_FAILED( rv = pDst->Write( "\x0D\x0A", 2, &written)) || (written != 2)) - return( rv); - } - - IMPORT_LOG1( " Message #%d processed.", ++msgCount); + PRUint32 mailSize = m_mailSize; + PRUint32 tocSize = 0; + PRUint32 msgCount = 0; + nsresult rv; + + rv = pToc->GetFileSize( &tocSize); + + // if the index or the mail file is empty then just + // use the original mail file. + if (!mailSize || !tocSize) + return( NS_ERROR_FAILURE); + + SimpleBufferTonyRCopiedOnce copy; + PRBool done = PR_FALSE; + PRInt32 tocOffset = kMsgFirstOffset; + PRInt32 data[2]; + PRInt32 count; + PRInt32 read; + PRInt32 written; + char * pBuffer; + char lastChar; + + copy.Allocate( kCopyBufferSize); + + IMPORT_LOG0( "Compacting mailbox: "); + + while (!*pAbort && (tocOffset < (PRInt32)tocSize)) { + if (NS_FAILED( rv = pToc->Seek( tocOffset))) return( rv); + pBuffer = (char *)data; + if (NS_FAILED( rv = pToc->Read( &pBuffer, 8, &read)) || (read != 8)) + return( NS_ERROR_FAILURE); + // data[0] is the message offset, data[1] is the message size + if (NS_FAILED( rv = pMail->Seek( data[0]))) return( rv); + count = kCopyBufferSize; + if (count > data[1]) + count = data[1]; + pBuffer = copy.m_pBuffer; + if (NS_FAILED( rv = pMail->Read( &pBuffer, count, &read)) || (read != count)) + return( NS_ERROR_FAILURE); + if (count < 6) + return( NS_ERROR_FAILURE); + if ((copy.m_pBuffer[0] != 'F') || (copy.m_pBuffer[1] != 'r') || + (copy.m_pBuffer[2] != 'o') || (copy.m_pBuffer[3] != 'm') || + (copy.m_pBuffer[4] != ' ')) + return( NS_ERROR_FAILURE); + + if (pBytes) + *pBytes += (data[1] / 4); + // Looks like everything is cool, we have a message that appears to start with a separator + while (data[1]) { + lastChar = copy.m_pBuffer[count - 1]; + if (NS_FAILED( rv = pDst->Write( copy.m_pBuffer, count, &written)) || (written != count)) + return( NS_ERROR_FAILURE); + data[1] -= count; + if (data[1]) { + pBuffer = copy.m_pBuffer; + count = kCopyBufferSize; + if (count > data[1]) + count = data[1]; + if (NS_FAILED( rv = pMail->Read( &pBuffer, count, &read)) || (read != count)) + return( NS_ERROR_FAILURE); + } + } + if ((lastChar != 0x0D) && (lastChar != 0x0A)) { + if (NS_FAILED( rv = pDst->Write( "\x0D\x0A", 2, &written)) || (written != 2)) + return( rv); + } + + IMPORT_LOG1( " Message #%d processed.", ++msgCount); - tocOffset += kMsgHeaderSize; - } + tocOffset += kMsgHeaderSize; + } - IMPORT_LOG0( " finished\n"); + IMPORT_LOG0( " finished\n"); - return( NS_OK); + return( NS_OK); } @@ -454,266 +454,266 @@ nsresult nsEudoraMailbox::ReadNextMessage( ReadFileState *pState, SimpleBufferTonyRCopiedOnce& copy, SimpleBufferTonyRCopiedOnce& header, SimpleBufferTonyRCopiedOnce& body, nsCString& defaultDate, nsCString& bodyType) { - header.m_writeOffset = 0; - body.m_writeOffset = 0; - - nsresult rv; - PRInt32 lineLen; - char endBuffer = 0; - - lineLen = -1; - // Find the from separator - we should actually be positioned at the - // from separator, but for now, we'll verify this. - while (lineLen == -1) { - if (NS_FAILED( rv = FillMailBuffer( pState, copy))) { - IMPORT_LOG0( "*** Error, FillMailBuffer FAILED in ReadNextMessage\n"); - return( rv); - } - lineLen = IsEudoraFromSeparator( copy.m_pBuffer + copy.m_writeOffset, copy.m_bytesInBuf - copy.m_writeOffset, defaultDate); - - if (lineLen == -1) { - while ((lineLen = FindStartLine( copy)) == -1) { - copy.m_writeOffset = copy.m_bytesInBuf; - if (NS_FAILED( rv = FillMailBuffer( pState, copy))) { - IMPORT_LOG0( "*** Error, FillMailBuffer FAILED in ReadNextMessage, looking for next start line\n"); - return( rv); - } - if (!copy.m_bytesInBuf) { - IMPORT_LOG0( "*** Error, ReadNextMessage, looking for start of next line, got end of file.\n"); - return( NS_ERROR_FAILURE); - } - } - copy.m_writeOffset += lineLen; - lineLen = -1; - } - } - - // Skip past the from line separator - while ((lineLen = FindStartLine( copy)) == -1) { - copy.m_writeOffset = copy.m_bytesInBuf; - if (NS_FAILED( rv = FillMailBuffer( pState, copy))) { - IMPORT_LOG0( "*** Error, ReadNextMessage, FillMailBuffer failed looking for from sep\n"); - return( rv); - } - if (!copy.m_bytesInBuf) { - IMPORT_LOG0( "*** Error, ReadNextMessage, end of file looking for from sep\n"); - return( NS_ERROR_FAILURE); - } - } - copy.m_writeOffset += lineLen; - if (NS_FAILED( rv = FillMailBuffer( pState, copy))) { - IMPORT_LOG0( "*** Error, Unable to fill mail buffer after from sep.\n"); - return( rv); - } - - // This should be the headers... - PRInt32 endLen = -1; - while ((endLen = IsEndHeaders( copy)) == -1) { - while ((lineLen = FindNextEndLine( copy)) == -1) { - copy.m_writeOffset = copy.m_bytesInBuf; - if (!header.Write( copy.m_pBuffer, copy.m_writeOffset)) { - IMPORT_LOG0( "*** ERROR, writing headers\n"); - return( NS_ERROR_FAILURE); - } - if (NS_FAILED( rv = FillMailBuffer( pState, copy))) { - IMPORT_LOG0( "*** Error reading message headers\n"); - return( rv); - } - if (!copy.m_bytesInBuf) { - IMPORT_LOG0( "*** Error, end of file while reading headers\n"); - return( NS_ERROR_FAILURE); - } - } - copy.m_writeOffset += lineLen; - if ((copy.m_writeOffset + 4) >= copy.m_bytesInBuf) { - if (!header.Write( copy.m_pBuffer, copy.m_writeOffset)) { - IMPORT_LOG0( "*** ERROR, writing headers 2\n"); - return( NS_ERROR_FAILURE); - } - if (NS_FAILED( rv = FillMailBuffer( pState, copy))) { - IMPORT_LOG0( "*** Error reading message headers 2\n"); - return( rv); - } - } - } - - if (!header.Write( copy.m_pBuffer, copy.m_writeOffset)) { - IMPORT_LOG0( "*** Error writing final headers\n"); - return( NS_ERROR_FAILURE); - } - if (!header.Write( &endBuffer, 1)) { - IMPORT_LOG0( "*** Error writing header trailing null\n"); - return( NS_ERROR_FAILURE); - } - - - copy.m_writeOffset += endLen; - if (NS_FAILED( rv = FillMailBuffer( pState, copy))) { - IMPORT_LOG0( "*** Error reading beginning of message body\n"); - return( rv); - } - - EmptyAttachments(); - - // Get the body! - // Read one line at a time here and look for the next separator + header.m_writeOffset = 0; + body.m_writeOffset = 0; + + nsresult rv; + PRInt32 lineLen; + char endBuffer = 0; + + lineLen = -1; + // Find the from separator - we should actually be positioned at the + // from separator, but for now, we'll verify this. + while (lineLen == -1) { + if (NS_FAILED( rv = FillMailBuffer( pState, copy))) { + IMPORT_LOG0( "*** Error, FillMailBuffer FAILED in ReadNextMessage\n"); + return( rv); + } + lineLen = IsEudoraFromSeparator( copy.m_pBuffer + copy.m_writeOffset, copy.m_bytesInBuf - copy.m_writeOffset, defaultDate); + + if (lineLen == -1) { + while ((lineLen = FindStartLine( copy)) == -1) { + copy.m_writeOffset = copy.m_bytesInBuf; + if (NS_FAILED( rv = FillMailBuffer( pState, copy))) { + IMPORT_LOG0( "*** Error, FillMailBuffer FAILED in ReadNextMessage, looking for next start line\n"); + return( rv); + } + if (!copy.m_bytesInBuf) { + IMPORT_LOG0( "*** Error, ReadNextMessage, looking for start of next line, got end of file.\n"); + return( NS_ERROR_FAILURE); + } + } + copy.m_writeOffset += lineLen; + lineLen = -1; + } + } + + // Skip past the from line separator + while ((lineLen = FindStartLine( copy)) == -1) { + copy.m_writeOffset = copy.m_bytesInBuf; + if (NS_FAILED( rv = FillMailBuffer( pState, copy))) { + IMPORT_LOG0( "*** Error, ReadNextMessage, FillMailBuffer failed looking for from sep\n"); + return( rv); + } + if (!copy.m_bytesInBuf) { + IMPORT_LOG0( "*** Error, ReadNextMessage, end of file looking for from sep\n"); + return( NS_ERROR_FAILURE); + } + } + copy.m_writeOffset += lineLen; + if (NS_FAILED( rv = FillMailBuffer( pState, copy))) { + IMPORT_LOG0( "*** Error, Unable to fill mail buffer after from sep.\n"); + return( rv); + } + + // This should be the headers... + PRInt32 endLen = -1; + while ((endLen = IsEndHeaders( copy)) == -1) { + while ((lineLen = FindNextEndLine( copy)) == -1) { + copy.m_writeOffset = copy.m_bytesInBuf; + if (!header.Write( copy.m_pBuffer, copy.m_writeOffset)) { + IMPORT_LOG0( "*** ERROR, writing headers\n"); + return( NS_ERROR_FAILURE); + } + if (NS_FAILED( rv = FillMailBuffer( pState, copy))) { + IMPORT_LOG0( "*** Error reading message headers\n"); + return( rv); + } + if (!copy.m_bytesInBuf) { + IMPORT_LOG0( "*** Error, end of file while reading headers\n"); + return( NS_ERROR_FAILURE); + } + } + copy.m_writeOffset += lineLen; + if ((copy.m_writeOffset + 4) >= copy.m_bytesInBuf) { + if (!header.Write( copy.m_pBuffer, copy.m_writeOffset)) { + IMPORT_LOG0( "*** ERROR, writing headers 2\n"); + return( NS_ERROR_FAILURE); + } + if (NS_FAILED( rv = FillMailBuffer( pState, copy))) { + IMPORT_LOG0( "*** Error reading message headers 2\n"); + return( rv); + } + } + } + + if (!header.Write( copy.m_pBuffer, copy.m_writeOffset)) { + IMPORT_LOG0( "*** Error writing final headers\n"); + return( NS_ERROR_FAILURE); + } + if (!header.Write( &endBuffer, 1)) { + IMPORT_LOG0( "*** Error writing header trailing null\n"); + return( NS_ERROR_FAILURE); + } + + + copy.m_writeOffset += endLen; + if (NS_FAILED( rv = FillMailBuffer( pState, copy))) { + IMPORT_LOG0( "*** Error reading beginning of message body\n"); + return( rv); + } + + EmptyAttachments(); + + // Get the body! + // Read one line at a time here and look for the next separator nsCString tmp; PRBool insideEudoraTags = PR_FALSE; // by default we consider the body text to be plain text bodyType = "text/plain"; - while ((lineLen = IsEudoraFromSeparator( copy.m_pBuffer + copy.m_writeOffset, copy.m_bytesInBuf - copy.m_writeOffset, tmp)) == -1) { + while ((lineLen = IsEudoraFromSeparator( copy.m_pBuffer + copy.m_writeOffset, copy.m_bytesInBuf - copy.m_writeOffset, tmp)) == -1) { PRInt32 tagLength = 0; - if (IsEudoraTag ( copy.m_pBuffer + copy.m_writeOffset, copy.m_bytesInBuf - copy.m_writeOffset, insideEudoraTags, bodyType, tagLength)) { - // We don't want to keep eudora tags so skip over them. - - // let's write the previous text - if (!body.Write( copy.m_pBuffer, copy.m_writeOffset)) { - IMPORT_LOG0( "*** Error writing to message body\n"); - return( NS_ERROR_FAILURE); - } + if (IsEudoraTag ( copy.m_pBuffer + copy.m_writeOffset, copy.m_bytesInBuf - copy.m_writeOffset, insideEudoraTags, bodyType, tagLength)) { + // We don't want to keep eudora tags so skip over them. + + // let's write the previous text + if (!body.Write( copy.m_pBuffer, copy.m_writeOffset)) { + IMPORT_LOG0( "*** Error writing to message body\n"); + return( NS_ERROR_FAILURE); + } // we want to skip over the tag...for now we are assuming the tag is always at the start of line. copy.m_writeOffset += tagLength; - if (NS_FAILED( rv = FillMailBuffer( pState, copy))) { - IMPORT_LOG0( "*** Error reading message body\n"); - return( rv); - } - - if (!copy.m_bytesInBuf) - break; - - continue; - } - - // Eudora Attachment lines are always outside Eudora Tags - // so we shouldn't try to find one here - if (!insideEudoraTags) { - // Debatable is whether or not to exclude these lines from the - // text of the message, I prefer not to in case the original - // attachment is actually missing. - rv = ExamineAttachment( copy); - if (NS_FAILED( rv)) { - IMPORT_LOG0( "*** Error examining attachment line\n"); - return( rv); - } - } - - - while (((lineLen = FindStartLine( copy)) == -1) && copy.m_bytesInBuf) { - copy.m_writeOffset = copy.m_bytesInBuf; - if (!body.Write( copy.m_pBuffer, copy.m_writeOffset)) { - IMPORT_LOG0( "*** Error writing to message body\n"); - return( NS_ERROR_FAILURE); - } - if (NS_FAILED( rv = FillMailBuffer( pState, copy))) { - IMPORT_LOG0( "*** Error reading message body\n"); - return( rv); - } - } - if (!copy.m_bytesInBuf) - break; - - copy.m_writeOffset += lineLen; - - // found the start of the next line - // make sure it's long enough to check for the from line - if ((copy.m_writeOffset + 2048) >= copy.m_bytesInBuf) { - if (!body.Write( copy.m_pBuffer, copy.m_writeOffset)) { - IMPORT_LOG0( "*** Error writing to message body 2\n"); - return( NS_ERROR_FAILURE); - } - if (NS_FAILED( rv = FillMailBuffer( pState, copy))) { - IMPORT_LOG0( "*** Error reading message body 2\n"); - return( rv); - } - } - } - - // the start of the current line is a from, we-re done - if (!body.Write( copy.m_pBuffer, copy.m_writeOffset)) { - IMPORT_LOG0( "*** Error writing final message body\n"); - return( NS_ERROR_FAILURE); - } - if (!body.Write( &endBuffer, 1)) { - IMPORT_LOG0( "*** Error writing body trailing null\n"); - IMPORT_LOG2( "\tbody.m_size: %ld, body.m_writeOffset: %ld\n", body.m_size, body.m_writeOffset); - return( NS_ERROR_FAILURE); - } - if (NS_FAILED( rv = FillMailBuffer( pState, copy))) { - IMPORT_LOG0( "*** Error filling mail buffer for next read message\n"); - return( rv); - } - - return( NS_OK); + if (NS_FAILED( rv = FillMailBuffer( pState, copy))) { + IMPORT_LOG0( "*** Error reading message body\n"); + return( rv); + } + + if (!copy.m_bytesInBuf) + break; + + continue; + } + + // Eudora Attachment lines are always outside Eudora Tags + // so we shouldn't try to find one here + if (!insideEudoraTags) { + // Debatable is whether or not to exclude these lines from the + // text of the message, I prefer not to in case the original + // attachment is actually missing. + rv = ExamineAttachment( copy); + if (NS_FAILED( rv)) { + IMPORT_LOG0( "*** Error examining attachment line\n"); + return( rv); + } + } + + + while (((lineLen = FindStartLine( copy)) == -1) && copy.m_bytesInBuf) { + copy.m_writeOffset = copy.m_bytesInBuf; + if (!body.Write( copy.m_pBuffer, copy.m_writeOffset)) { + IMPORT_LOG0( "*** Error writing to message body\n"); + return( NS_ERROR_FAILURE); + } + if (NS_FAILED( rv = FillMailBuffer( pState, copy))) { + IMPORT_LOG0( "*** Error reading message body\n"); + return( rv); + } + } + if (!copy.m_bytesInBuf) + break; + + copy.m_writeOffset += lineLen; + + // found the start of the next line + // make sure it's long enough to check for the from line + if ((copy.m_writeOffset + 2048) >= copy.m_bytesInBuf) { + if (!body.Write( copy.m_pBuffer, copy.m_writeOffset)) { + IMPORT_LOG0( "*** Error writing to message body 2\n"); + return( NS_ERROR_FAILURE); + } + if (NS_FAILED( rv = FillMailBuffer( pState, copy))) { + IMPORT_LOG0( "*** Error reading message body 2\n"); + return( rv); + } + } + } + + // the start of the current line is a from, we-re done + if (!body.Write( copy.m_pBuffer, copy.m_writeOffset)) { + IMPORT_LOG0( "*** Error writing final message body\n"); + return( NS_ERROR_FAILURE); + } + if (!body.Write( &endBuffer, 1)) { + IMPORT_LOG0( "*** Error writing body trailing null\n"); + IMPORT_LOG2( "\tbody.m_size: %ld, body.m_writeOffset: %ld\n", body.m_size, body.m_writeOffset); + return( NS_ERROR_FAILURE); + } + if (NS_FAILED( rv = FillMailBuffer( pState, copy))) { + IMPORT_LOG0( "*** Error filling mail buffer for next read message\n"); + return( rv); + } + + return( NS_OK); } -PRInt32 nsEudoraMailbox::FindStartLine( SimpleBufferTonyRCopiedOnce& data) +PRInt32 nsEudoraMailbox::FindStartLine( SimpleBufferTonyRCopiedOnce& data) { - PRInt32 len = data.m_bytesInBuf - data.m_writeOffset; - if (!len) - return( -1); - PRInt32 count = 0; - const char *pData = data.m_pBuffer + data.m_writeOffset; - while ((*pData != 0x0D) && (*pData != 0x0A) && (count < len)) { - pData++; - count++; - } - if (count == len) - return( -1); - - while (((*pData == 0x0D) || (*pData == 0x0A)) && (count < len)) { - pData++; - count++; - } - - if (count < len) - return( count); + PRInt32 len = data.m_bytesInBuf - data.m_writeOffset; + if (!len) + return( -1); + PRInt32 count = 0; + const char *pData = data.m_pBuffer + data.m_writeOffset; + while ((*pData != 0x0D) && (*pData != 0x0A) && (count < len)) { + pData++; + count++; + } + if (count == len) + return( -1); + + while (((*pData == 0x0D) || (*pData == 0x0A)) && (count < len)) { + pData++; + count++; + } + + if (count < len) + return( count); - return( -1); + return( -1); } PRInt32 nsEudoraMailbox::FindNextEndLine( SimpleBufferTonyRCopiedOnce& data) { - PRInt32 len = data.m_bytesInBuf - data.m_writeOffset; - if (!len) - return( -1); - PRInt32 count = 0; - const char *pData = data.m_pBuffer + data.m_writeOffset; - while (((*pData == 0x0D) || (*pData == 0x0A)) && (count < len)) { - pData++; - count++; - } - while ((*pData != 0x0D) && (*pData != 0x0A) && (count < len)) { - pData++; - count++; - } - - if (count < len) - return( count); + PRInt32 len = data.m_bytesInBuf - data.m_writeOffset; + if (!len) + return( -1); + PRInt32 count = 0; + const char *pData = data.m_pBuffer + data.m_writeOffset; + while (((*pData == 0x0D) || (*pData == 0x0A)) && (count < len)) { + pData++; + count++; + } + while ((*pData != 0x0D) && (*pData != 0x0A) && (count < len)) { + pData++; + count++; + } + + if (count < len) + return( count); - return( -1); + return( -1); } PRInt32 nsEudoraMailbox::IsEndHeaders( SimpleBufferTonyRCopiedOnce& data) { - PRInt32 len = data.m_bytesInBuf - data.m_writeOffset; - if (len < 2) - return( -1); - const char *pChar = data.m_pBuffer + data.m_writeOffset; - if ((*pChar == 0x0D) && (*(pChar + 1) == 0x0D)) - return( 2); - - if (len < 4) - return( -1); - if ((*pChar == 0x0D) && (*(pChar + 1) == 0x0A) && - (*(pChar + 2) == 0x0D) && (*(pChar + 3) == 0x0A)) - return( 4); + PRInt32 len = data.m_bytesInBuf - data.m_writeOffset; + if (len < 2) + return( -1); + const char *pChar = data.m_pBuffer + data.m_writeOffset; + if ((*pChar == 0x0D) && (*(pChar + 1) == 0x0D)) + return( 2); + + if (len < 4) + return( -1); + if ((*pChar == 0x0D) && (*(pChar + 1) == 0x0A) && + (*(pChar + 2) == 0x0D) && (*(pChar + 3) == 0x0A)) + return( 4); - return( -1); + return( -1); } @@ -729,455 +729,455 @@ }; static PRInt32 eudoraTagLen[] = { - 8, - 9, - 8, - 9, - 10, - 11, - 0 + 8, + 9, + 8, + 9, + 10, + 11, + 0 }; static const char *TagContentType[] = { - "text/html", - "text/html", - "text/enriched", - "text/enriched", - "text/plain", - "text/plain", + "text/html", + "text/html", + "text/enriched", + "text/enriched", + "text/plain", + "text/plain", }; - // Determine if this line contains an eudora special tag -PRBool nsEudoraMailbox::IsEudoraTag( const char *pChar, PRInt32 maxLen, PRBool &insideEudoraTags, nsCString &bodyType, PRInt32 &tagLength) + // Determine if this line contains an eudora special tag +PRBool nsEudoraMailbox::IsEudoraTag( const char *pChar, PRInt32 maxLen, PRBool &insideEudoraTags, nsCString &bodyType, PRInt32 &tagLength) { - PRInt32 idx = 0; - while ((tagLength = eudoraTagLen[idx]) != 0) { - if (maxLen >= tagLength && !nsCRT::strncmp( eudoraTag[idx], pChar, tagLength)) { - insideEudoraTags = (pChar[1] != '/'); - bodyType = TagContentType[idx]; - return PR_TRUE; - } - idx++; - } + PRInt32 idx = 0; + while ((tagLength = eudoraTagLen[idx]) != 0) { + if (maxLen >= tagLength && !nsCRT::strncmp( eudoraTag[idx], pChar, tagLength)) { + insideEudoraTags = (pChar[1] != '/'); + bodyType = TagContentType[idx]; + return PR_TRUE; + } + idx++; + } - return PR_FALSE; + return PR_FALSE; } - // Determine if this line meets Eudora standards for a separator line - // This logic is based on Eudora 1.3.1's strict requirements for what - // makes a valid separator line. This may need to be relaxed for newer - // versions of Eudora. - // A sample from line: - // From john@uxc.cso.uiuc.edu Wed Jan 14 12:36:18 1989 -PRInt32 nsEudoraMailbox::IsEudoraFromSeparator( const char *pChar, PRInt32 maxLen, nsCString& defaultDate) -{ - if (maxLen < 12) - return( -1); - - PRInt32 len = 0; - if ((*pChar != 'F') || (*(pChar + 1) != 'r') || (*(pChar + 2) != 'o') || (*(pChar + 3) != 'm')) - return( -1); - pChar += 4; - len += 4; - - // According to Eudora the next char MUST be a space, and there can only be 1 space - // before the return mail address. - // I'll be nicer and allow any amount of whitespace - while (((*pChar == ' ') || (*pChar == '\t')) && (len < maxLen)) { - pChar++; - len++; - } - if (len == maxLen) - return( -1); - - // Determine the length of the line - PRInt32 lineLen = len; - const char * pTok = pChar; - while ((lineLen < maxLen) && (*pTok != 0x0D) && (*pTok != 0x0A)) { - lineLen++; - pTok++; - } - - if (len >= lineLen) - return( -1); - - // Eudora allows the return address to be double quoted or not at all.. - // I'll allow single or double quote, but other than that, just skip - // the return address until you hit a space char (I allow tab as well) - char quote = *pChar; - if ((quote == '"') || (quote == '\'')) { - pChar++; - len++; - while ((len < lineLen) && (*pChar != quote)) { - pChar++; - len++; - } - if (len == lineLen) - return( -1); - len++; - pChar++; - } - else { - while ((len < lineLen) && (*pChar != ' ') && (*pChar != '\t')) { - pChar++; - len++; - } - } - while (((*pChar == ' ') || (*pChar == '\t')) && (len < lineLen)) { - pChar++; - len++; - } - if (len == lineLen) - return( -1); - - // we've passed the address, now check for the remaining data - // Now it gets really funky! - // In no particular order, with token separators space, tab, comma, newline - // a - the phrase "remote from", remote must be first, from is optional. 2 froms or 2 remotes fails - // b - one and only one time value xx:xx or xx:xx:xx - // c - one and only one day, 1 to 31 - // d - one and only one year, 2 digit anything or 4 digit > 1900 - // e - one and only one weekday, 3 letter abreviation - // f - one and only one month, 3 letter abreviation - // 2 allowable "other" tokens - // to be valid, day, year, month, & tym must exist and other must be less than 3 - - int day = 0; - int month = 0; - int year = 0; - int weekDay = 0; - int other = 0; - int result; - char tymStr[9]; // Make it a null terminated string (used in PR_snprintf() call()). - PRBool tym = PR_FALSE; - PRBool remote = PR_FALSE; - PRBool from = PR_FALSE; - PRInt32 tokLen; - PRInt32 tokStart; - PRInt32 num; - - while ((len < lineLen) && (other < 3)) { - pTok = pChar; - tokStart = len; - while ((len < lineLen) && (*pChar != ' ') && (*pChar != '\t') && (*pChar != ',')) { - pChar++; - len++; - } - tokLen = len - tokStart; - if (tokLen) { - num = AsciiToLong( pTok, tokLen); - if ((tokLen == 3) && ((result = IsWeekDayStr( pTok)) != 0)) { - if (weekDay) - return( -1); - weekDay = result; - } - else if ((tokLen == 3) && ((result = IsMonthStr( pTok)) != 0)) { - if (month) - return( -1); - month = result; - } - else if ((tokLen == 6) && !nsCRT::strncasecmp( pTok, "remote", 6)) { - if (remote || from) - return( -1); - remote = PR_TRUE; - } - else if ((tokLen == 4) && !nsCRT::strncasecmp( pTok, "from", 4)) { - if (!remote || from) - return( -1); - from = PR_TRUE; - } - else if ((tokLen == 4) && ((num > 1900) || !nsCRT::strncmp( pTok, "0000", 4))) { - if (year) - return( -1); - year = (int)num; - if (!year) - year = 1900; - } - else if (!year && day && (tokLen == 2) && (*(pTok + 1) >= '0') && (*(pTok + 1) <= '9')) { - if (num < 65) - num += 1900; - else - num += 2000; - year = (int) num; - } - else if ((tokLen <= 2) && (*pTok >= '0') && (*pTok <= '9')) { - day = (int) num; - if ((day < 1) || (day > 31)) - day = 1; - } - else if ((tokLen >= 5) && (pTok[2] == ':') && ((tokLen == 5) || ((tokLen == 8) && (pTok[5] == ':')))) { - // looks like the tym... - for (result = 0; result < (int)tokLen; result++) { - if ((result != 2) && (result != 5)) { - if ((pTok[result] < '0') || (pTok[result] > '9')) { - break; - } - } - } - if (result == tokLen) { - if (tym) - return( -1); - tym = PR_TRUE; - // for future use, get the time value - memcpy( tymStr, pTok, tokLen); - if (tokLen == 5) { - tymStr[5] = ':'; - tymStr[6] = '0'; - tymStr[7] = '0'; - } + // Determine if this line meets Eudora standards for a separator line + // This logic is based on Eudora 1.3.1's strict requirements for what + // makes a valid separator line. This may need to be relaxed for newer + // versions of Eudora. + // A sample from line: + // From john@uxc.cso.uiuc.edu Wed Jan 14 12:36:18 1989 +PRInt32 nsEudoraMailbox::IsEudoraFromSeparator( const char *pChar, PRInt32 maxLen, nsCString& defaultDate) +{ + if (maxLen < 12) + return( -1); + + PRInt32 len = 0; + if ((*pChar != 'F') || (*(pChar + 1) != 'r') || (*(pChar + 2) != 'o') || (*(pChar + 3) != 'm')) + return( -1); + pChar += 4; + len += 4; + + // According to Eudora the next char MUST be a space, and there can only be 1 space + // before the return mail address. + // I'll be nicer and allow any amount of whitespace + while (((*pChar == ' ') || (*pChar == '\t')) && (len < maxLen)) { + pChar++; + len++; + } + if (len == maxLen) + return( -1); + + // Determine the length of the line + PRInt32 lineLen = len; + const char * pTok = pChar; + while ((lineLen < maxLen) && (*pTok != 0x0D) && (*pTok != 0x0A)) { + lineLen++; + pTok++; + } + + if (len >= lineLen) + return( -1); + + // Eudora allows the return address to be double quoted or not at all.. + // I'll allow single or double quote, but other than that, just skip + // the return address until you hit a space char (I allow tab as well) + char quote = *pChar; + if ((quote == '"') || (quote == '\'')) { + pChar++; + len++; + while ((len < lineLen) && (*pChar != quote)) { + pChar++; + len++; + } + if (len == lineLen) + return( -1); + len++; + pChar++; + } + else { + while ((len < lineLen) && (*pChar != ' ') && (*pChar != '\t')) { + pChar++; + len++; + } + } + while (((*pChar == ' ') || (*pChar == '\t')) && (len < lineLen)) { + pChar++; + len++; + } + if (len == lineLen) + return( -1); + + // we've passed the address, now check for the remaining data + // Now it gets really funky! + // In no particular order, with token separators space, tab, comma, newline + // a - the phrase "remote from", remote must be first, from is optional. 2 froms or 2 remotes fails + // b - one and only one time value xx:xx or xx:xx:xx + // c - one and only one day, 1 to 31 + // d - one and only one year, 2 digit anything or 4 digit > 1900 + // e - one and only one weekday, 3 letter abreviation + // f - one and only one month, 3 letter abreviation + // 2 allowable "other" tokens + // to be valid, day, year, month, & tym must exist and other must be less than 3 + + int day = 0; + int month = 0; + int year = 0; + int weekDay = 0; + int other = 0; + int result; + char tymStr[9]; // Make it a null terminated string (used in PR_snprintf() call()). + PRBool tym = PR_FALSE; + PRBool remote = PR_FALSE; + PRBool from = PR_FALSE; + PRInt32 tokLen; + PRInt32 tokStart; + PRInt32 num; + + while ((len < lineLen) && (other < 3)) { + pTok = pChar; + tokStart = len; + while ((len < lineLen) && (*pChar != ' ') && (*pChar != '\t') && (*pChar != ',')) { + pChar++; + len++; + } + tokLen = len - tokStart; + if (tokLen) { + num = AsciiToLong( pTok, tokLen); + if ((tokLen == 3) && ((result = IsWeekDayStr( pTok)) != 0)) { + if (weekDay) + return( -1); + weekDay = result; + } + else if ((tokLen == 3) && ((result = IsMonthStr( pTok)) != 0)) { + if (month) + return( -1); + month = result; + } + else if ((tokLen == 6) && !nsCRT::strncasecmp( pTok, "remote", 6)) { + if (remote || from) + return( -1); + remote = PR_TRUE; + } + else if ((tokLen == 4) && !nsCRT::strncasecmp( pTok, "from", 4)) { + if (!remote || from) + return( -1); + from = PR_TRUE; + } + else if ((tokLen == 4) && ((num > 1900) || !nsCRT::strncmp( pTok, "0000", 4))) { + if (year) + return( -1); + year = (int)num; + if (!year) + year = 1900; + } + else if (!year && day && (tokLen == 2) && (*(pTok + 1) >= '0') && (*(pTok + 1) <= '9')) { + if (num < 65) + num += 1900; + else + num += 2000; + year = (int) num; + } + else if ((tokLen <= 2) && (*pTok >= '0') && (*pTok <= '9')) { + day = (int) num; + if ((day < 1) || (day > 31)) + day = 1; + } + else if ((tokLen >= 5) && (pTok[2] == ':') && ((tokLen == 5) || ((tokLen == 8) && (pTok[5] == ':')))) { + // looks like the tym... + for (result = 0; result < (int)tokLen; result++) { + if ((result != 2) && (result != 5)) { + if ((pTok[result] < '0') || (pTok[result] > '9')) { + break; + } + } + } + if (result == tokLen) { + if (tym) + return( -1); + tym = PR_TRUE; + // for future use, get the time value + memcpy( tymStr, pTok, tokLen); + if (tokLen == 5) { + tymStr[5] = ':'; + tymStr[6] = '0'; + tymStr[7] = '0'; + } tymStr[8] = 0; - } - else { - other++; - } - } - else - other++; - } - // Skip the space chars... - while ((len < lineLen) && ((*pChar == ' ') || (*pChar == '\t') || (*pChar == ','))) { - pChar++; - len++; - } - } // end while (len < lineLen) token loop - - // Now let's see what we found on the line - if (day && year && month && tym && (other < 3)) { - // Now we need to make sure the next line - // isn't blank! - while (len < lineLen) { - len++; - pChar++; - } - if (len == maxLen) - return( -1); - - if (*pChar == 0x0D) { - len++; - pChar++; - if (*pChar == 0x0A) { - len++; - pChar++; - } - } - else if (*pChar == 0x0A) { - len++; - pChar++; - } - else - return( -1); - if (len >= maxLen) - return( -1); - - while (len < maxLen) { - if ((*pChar == 0x0D) || (*pChar == 0x0A)) - return( -1); - if ((*pChar != ' ') && (*pChar != '\t')) - break; - pChar++; - len++; - } + } + else { + other++; + } + } + else + other++; + } + // Skip the space chars... + while ((len < lineLen) && ((*pChar == ' ') || (*pChar == '\t') || (*pChar == ','))) { + pChar++; + len++; + } + } // end while (len < lineLen) token loop + + // Now let's see what we found on the line + if (day && year && month && tym && (other < 3)) { + // Now we need to make sure the next line + // isn't blank! + while (len < lineLen) { + len++; + pChar++; + } + if (len == maxLen) + return( -1); + + if (*pChar == 0x0D) { + len++; + pChar++; + if (*pChar == 0x0A) { + len++; + pChar++; + } + } + else if (*pChar == 0x0A) { + len++; + pChar++; + } + else + return( -1); + if (len >= maxLen) + return( -1); + + while (len < maxLen) { + if ((*pChar == 0x0D) || (*pChar == 0x0A)) + return( -1); + if ((*pChar != ' ') && (*pChar != '\t')) + break; + pChar++; + len++; + } - // Whew!, the next line isn't blank. + // Whew!, the next line isn't blank. // Generate the default date header in case the date header is missing when we // write out headers later. The header looks like "Date: Tue, 5 Feb 2002 23:05:04" char date_header_str[DATE_STR_LEN]; PR_snprintf(date_header_str, DATE_STR_LEN, "Date: %s, %2d %s %4d %s", eudoraWeekDays[weekDay-1], day, eudoraMonths[month-1], year, tymStr); defaultDate.Assign(date_header_str); - return( lineLen); - } - - return( -1); + return( lineLen); + } + + return( -1); } PRInt32 nsEudoraMailbox::AsciiToLong( const char *pChar, PRInt32 len) { - PRInt32 num = 0; - while (len) { - if ((*pChar < '0') || (*pChar > '9')) - return( num); - num *= 10; - num += (*pChar - '0'); - len--; - pChar++; - } - return( num); + PRInt32 num = 0; + while (len) { + if ((*pChar < '0') || (*pChar > '9')) + return( num); + num *= 10; + num += (*pChar - '0'); + len--; + pChar++; + } + return( num); } int nsEudoraMailbox::IsWeekDayStr( const char *pStr) { - for (int i = 0; i < 7; i++) { - if (!nsCRT::strncasecmp( pStr, eudoraWeekDays[i], 3)) - return( i + 1); - } - return( 0); + for (int i = 0; i < 7; i++) { + if (!nsCRT::strncasecmp( pStr, eudoraWeekDays[i], 3)) + return( i + 1); + } + return( 0); } int nsEudoraMailbox::IsMonthStr( const char *pStr) { - for (int i = 0; i < 12; i++) { - if (!nsCRT::strncasecmp( pStr, eudoraMonths[i], 3)) - return( i + 1); - } - return( 0); + for (int i = 0; i < 12; i++) { + if (!nsCRT::strncasecmp( pStr, eudoraMonths[i], 3)) + return( i + 1); + } + return( 0); } nsresult nsEudoraMailbox::WriteFromSep( nsIFileSpec *pDst) { - if (!m_fromLen) - m_fromLen = strlen( eudoraFromLine); - PRInt32 written = 0; - nsresult rv = pDst->Write( eudoraFromLine, m_fromLen, &written); - if (NS_SUCCEEDED( rv) && (written != m_fromLen)) - return( NS_ERROR_FAILURE); - return( rv); + if (!m_fromLen) + m_fromLen = strlen( eudoraFromLine); + PRInt32 written = 0; + nsresult rv = pDst->Write( eudoraFromLine, m_fromLen, &written); + if (NS_SUCCEEDED( rv) && (written != m_fromLen)) + return( NS_ERROR_FAILURE); + return( rv); } void nsEudoraMailbox::EmptyAttachments( void) { - PRInt32 max = m_attachments.Count(); - ImportAttachment * pAttach; - for (PRInt32 i = 0; i < max; i++) { - pAttach = (ImportAttachment *) m_attachments.ElementAt( i); - if (pAttach) { - NS_IF_RELEASE( pAttach->pAttachment); - nsCRT::free( pAttach->description); - nsCRT::free( pAttach->mimeType); - delete pAttach; - } - } + PRInt32 max = m_attachments.Count(); + ImportAttachment * pAttach; + for (PRInt32 i = 0; i < max; i++) { + pAttach = (ImportAttachment *) m_attachments.ElementAt( i); + if (pAttach) { + NS_IF_RELEASE( pAttach->pAttachment); + nsCRT::free( pAttach->description); + nsCRT::free( pAttach->mimeType); + delete pAttach; + } + } - m_attachments.Clear(); + m_attachments.Clear(); } static char *eudoraAttachLines[] = { - "Attachment Converted:", - "Attachment converted:", + "Attachment Converted:", + "Attachment converted:", "Pièce jointe convertie :" }; static PRInt32 eudoraAttachLen[] = { - 21, - 21, + 21, + 21, 24, - 0 + 0 }; nsresult nsEudoraMailbox::ExamineAttachment( SimpleBufferTonyRCopiedOnce& data) { - // get the file, then get the mime type, and add it to the array - // of attachments. - PRInt32 len = data.m_bytesInBuf - data.m_writeOffset; - const char *pChar = data.m_pBuffer + data.m_writeOffset; - const char *pData; - const char *pStart; - PRInt32 nameLen; - char quote; - PRInt32 cnt; - PRInt32 idx = 0; - while ((cnt = eudoraAttachLen[idx]) != 0) { - if (!nsCRT::strncmp( eudoraAttachLines[idx], pChar, cnt)) { - pData = pChar + cnt; - while (((*pData == ' ') || (*pData == '\t')) && (cnt < len)) { - cnt++; - pData++; - } - if (pData != pChar) { - quote = *pData; - nameLen = 0; - if ((quote == '"') || (quote == '\'')) { - pData++; - cnt++; - pStart = pData; - while ((*pData != quote) && (cnt < len)) { - cnt++; - pData++; - nameLen++; - } - } - else { - pStart = pData; - while ((*pData != 0x0D) && (*pData != 0x0A) && (cnt < len)) { - pData++; - cnt++; - nameLen++; - } - } - nsCString fileName; - fileName.Append( pStart, nameLen); - fileName.Trim( kWhitespace); - if (fileName.Length()) { + // get the file, then get the mime type, and add it to the array + // of attachments. + PRInt32 len = data.m_bytesInBuf - data.m_writeOffset; + const char *pChar = data.m_pBuffer + data.m_writeOffset; + const char *pData; + const char *pStart; + PRInt32 nameLen; + char quote; + PRInt32 cnt; + PRInt32 idx = 0; + while ((cnt = eudoraAttachLen[idx]) != 0) { + if (!nsCRT::strncmp( eudoraAttachLines[idx], pChar, cnt)) { + pData = pChar + cnt; + while (((*pData == ' ') || (*pData == '\t')) && (cnt < len)) { + cnt++; + pData++; + } + if (pData != pChar) { + quote = *pData; + nameLen = 0; + if ((quote == '"') || (quote == '\'')) { + pData++; + cnt++; + pStart = pData; + while ((*pData != quote) && (cnt < len)) { + cnt++; + pData++; + nameLen++; + } + } + else { + pStart = pData; + while ((*pData != 0x0D) && (*pData != 0x0A) && (cnt < len)) { + pData++; + cnt++; + nameLen++; + } + } + nsCString fileName; + fileName.Append( pStart, nameLen); + fileName.Trim( kWhitespace); + if (fileName.Length()) { #ifdef XP_MACOSX - return NS_OK; + return NS_OK; #else - if( AddAttachment( fileName)) - return( NS_OK); + if( AddAttachment( fileName)) + return( NS_OK); #endif - } - } - } - idx++; - } + } + } + } + idx++; + } - return( NS_OK); + return( NS_OK); } PRBool nsEudoraMailbox::AddAttachment( nsCString& fileName) { - IMPORT_LOG1( "Found attachment: %s\n", fileName.get()); + IMPORT_LOG1( "Found attachment: %s\n", fileName.get()); - nsIFileSpec * pSpec; - nsresult rv = NS_NewFileSpec( &pSpec); - if (NS_FAILED( rv)) - return( PR_FALSE); + nsIFileSpec * pSpec; + nsresult rv = NS_NewFileSpec( &pSpec); + if (NS_FAILED( rv)) + return( PR_FALSE); - nsCString mimeType; + nsCString mimeType; nsCString attachmentName; - if (NS_FAILED( GetAttachmentInfo( fileName.get(), pSpec, mimeType, attachmentName))) { - NS_RELEASE( pSpec); - return( PR_FALSE); - } + if (NS_FAILED( GetAttachmentInfo( fileName.get(), pSpec, mimeType, attachmentName))) { + NS_RELEASE( pSpec); + return( PR_FALSE); + } - ImportAttachment *a = new ImportAttachment; - a->mimeType = ToNewCString(mimeType); + ImportAttachment *a = new ImportAttachment; + a->mimeType = ToNewCString(mimeType); a->description = !attachmentName.IsEmpty() ? ToNewCString(attachmentName) : nsCRT::strdup( "Attached File"); - a->pAttachment = pSpec; + a->pAttachment = pSpec; - m_attachments.AppendElement( a); + m_attachments.AppendElement( a); - return( PR_TRUE); + return( PR_TRUE); } nsresult nsEudoraMailbox::FillMailBuffer( ReadFileState *pState, SimpleBufferTonyRCopiedOnce& read) { - if (read.m_writeOffset >= read.m_bytesInBuf) { - read.m_writeOffset = 0; - read.m_bytesInBuf = 0; - } - else if (read.m_writeOffset) { - memcpy( read.m_pBuffer, read.m_pBuffer + read.m_writeOffset, read.m_bytesInBuf - read.m_writeOffset); - read.m_bytesInBuf -= read.m_writeOffset; - read.m_writeOffset = 0; - } - - PRInt32 count = read.m_size - read.m_bytesInBuf; - if (((PRUint32)count + pState->offset) > pState->size) - count = pState->size - pState->offset; - if (count) { - PRInt32 bytesRead = 0; - char * pBuffer = read.m_pBuffer + read.m_bytesInBuf; - nsresult rv = pState->pFile->Read( &pBuffer, count, &bytesRead); - if (NS_FAILED( rv)) return( rv); - if (bytesRead != count) return( NS_ERROR_FAILURE); - read.m_bytesInBuf += bytesRead; - pState->offset += bytesRead; - } + if (read.m_writeOffset >= read.m_bytesInBuf) { + read.m_writeOffset = 0; + read.m_bytesInBuf = 0; + } + else if (read.m_writeOffset) { + memcpy( read.m_pBuffer, read.m_pBuffer + read.m_writeOffset, read.m_bytesInBuf - read.m_writeOffset); + read.m_bytesInBuf -= read.m_writeOffset; + read.m_writeOffset = 0; + } + + PRInt32 count = read.m_size - read.m_bytesInBuf; + if (((PRUint32)count + pState->offset) > pState->size) + count = pState->size - pState->offset; + if (count) { + PRInt32 bytesRead = 0; + char * pBuffer = read.m_pBuffer + read.m_bytesInBuf; + nsresult rv = pState->pFile->Read( &pBuffer, count, &bytesRead); + if (NS_FAILED( rv)) return( rv); + if (bytesRead != count) return( NS_ERROR_FAILURE); + read.m_bytesInBuf += bytesRead; + pState->offset += bytesRead; + } - return( NS_OK); + return( NS_OK); } Index: mozilla/mailnews/import/eudora/src/nsEudoraWin32.cpp =================================================================== RCS file: /cvsroot/mozilla/mailnews/import/eudora/src/nsEudoraWin32.cpp,v retrieving revision 1.43 diff -u -r1.43 mozilla/mailnews/import/eudora/src/nsEudoraWin32.cpp --- mozilla/mailnews/import/eudora/src/nsEudoraWin32.cpp +++ mozilla/mailnews/import/eudora/src/nsEudoraWin32.cpp @@ -1,4 +1,4 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- +/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 @@ -57,1410 +57,1410 @@ #include "nsUnicharUtils.h" #include "EudoraDebugLog.h" -static NS_DEFINE_IID(kISupportsIID, NS_ISUPPORTS_IID); +static NS_DEFINE_IID(kISupportsIID, NS_ISUPPORTS_IID); -static const char * kWhitespace = "\b\t\r\n "; +static const char * kWhitespace = "\b\t\r\n "; // ::RegOpenKeyEx( HKEY_CURRENT_USER, "Software\\Accounts", 0, KEY_QUERY_VALUE | KEY_ENUMERATE_SUB_KEYS, &sKey) == ERROR_SUCCESS) BYTE * nsEudoraWin32::GetValueBytes( HKEY hKey, const char *pValueName) { - LONG err; - DWORD bufSz; - LPBYTE pBytes = NULL; - - err = ::RegQueryValueEx( hKey, pValueName, NULL, NULL, NULL, &bufSz); - if (err == ERROR_SUCCESS) { - pBytes = new BYTE[bufSz]; - err = ::RegQueryValueEx( hKey, pValueName, NULL, NULL, pBytes, &bufSz); - if (err != ERROR_SUCCESS) { - delete [] pBytes; - pBytes = NULL; - } - } + LONG err; + DWORD bufSz; + LPBYTE pBytes = NULL; + + err = ::RegQueryValueEx( hKey, pValueName, NULL, NULL, NULL, &bufSz); + if (err == ERROR_SUCCESS) { + pBytes = new BYTE[bufSz]; + err = ::RegQueryValueEx( hKey, pValueName, NULL, NULL, pBytes, &bufSz); + if (err != ERROR_SUCCESS) { + delete [] pBytes; + pBytes = NULL; + } + } - return( pBytes); + return( pBytes); } nsEudoraWin32::nsEudoraWin32() { - m_mailImportLocation = nsnull; - m_addressImportFolder = nsnull; - m_pMimeSection = nsnull; + m_mailImportLocation = nsnull; + m_addressImportFolder = nsnull; + m_pMimeSection = nsnull; } nsEudoraWin32::~nsEudoraWin32() { - NS_IF_RELEASE( m_mailImportLocation); - NS_IF_RELEASE( m_addressImportFolder); - if (m_pMimeSection) - delete [] m_pMimeSection; + NS_IF_RELEASE( m_mailImportLocation); + NS_IF_RELEASE( m_addressImportFolder); + if (m_pMimeSection) + delete [] m_pMimeSection; } PRBool nsEudoraWin32::FindMailFolder( nsIFileSpec *pFolder) { - return( FindEudoraLocation( pFolder)); + return( FindEudoraLocation( pFolder)); } PRBool nsEudoraWin32::FindEudoraLocation( nsIFileSpec *pFolder, PRBool findIni) { - PRBool result = PR_FALSE; + PRBool result = PR_FALSE; PRBool exists = PR_FALSE; - // look in the registry to see where eudora is installed? - HKEY sKey; - if (::RegOpenKeyEx( HKEY_CURRENT_USER, "Software\\Qualcomm\\Eudora\\CommandLine", 0, KEY_QUERY_VALUE, &sKey) == ERROR_SUCCESS) { - // get the value of "Current" - BYTE *pBytes = GetValueBytes( sKey, "Current"); - if (pBytes) { - nsCString str((const char *)pBytes); - delete [] pBytes; - + // look in the registry to see where eudora is installed? + HKEY sKey; + if (::RegOpenKeyEx( HKEY_CURRENT_USER, "Software\\Qualcomm\\Eudora\\CommandLine", 0, KEY_QUERY_VALUE, &sKey) == ERROR_SUCCESS) { + // get the value of "Current" + BYTE *pBytes = GetValueBytes( sKey, "Current"); + if (pBytes) { + nsCString str((const char *)pBytes); + delete [] pBytes; + str.CompressWhitespace(); - - // Command line is Eudora mailfolder eudora.ini + + // Command line is Eudora mailfolder eudora.ini if (findIni) { // find the string coming after the last space PRInt32 index = str.RFind(" "); if (index != -1) { index++; // skip the space - nsCString path; - str.Mid( path, index, str.Length() - index); + nsCString path; + str.Mid( path, index, str.Length() - index); pFolder->SetNativePath( path.get()); pFolder->IsFile( &exists); if (exists) - result = exists; + result = exists; else // it may just be the mailbox location....guess that there will be a eudora.ini file there { pFolder->AppendRelativeUnixPath("eudora.ini"); pFolder->IsFile( &exists); - result = exists; + result = exists; } } } // if findIni else { - int idx = -1; - if (str.CharAt( 0) == '"') { - idx = str.FindChar( '"', 1); - if (idx != -1) - idx++; - } - else { - idx = str.FindChar( ' '); - } - - if (idx != -1) { - idx++; - while (str.CharAt( idx) == ' ') idx++; - int endIdx = -1; - if (str.CharAt( idx) == '"') { - endIdx = str.FindChar( '"', idx); - } - else { - endIdx = str.FindChar( ' ', idx); - } - if (endIdx != -1) { - nsCString path; - str.Mid( path, idx, endIdx - idx); - - pFolder->SetNativePath( path.get()); - - if (NS_SUCCEEDED( pFolder->IsDirectory( &exists))) - result = exists; - } - } - } + int idx = -1; + if (str.CharAt( 0) == '"') { + idx = str.FindChar( '"', 1); + if (idx != -1) + idx++; + } + else { + idx = str.FindChar( ' '); + } + + if (idx != -1) { + idx++; + while (str.CharAt( idx) == ' ') idx++; + int endIdx = -1; + if (str.CharAt( idx) == '"') { + endIdx = str.FindChar( '"', idx); + } + else { + endIdx = str.FindChar( ' ', idx); + } + if (endIdx != -1) { + nsCString path; + str.Mid( path, idx, endIdx - idx); + + pFolder->SetNativePath( path.get()); + + if (NS_SUCCEEDED( pFolder->IsDirectory( &exists))) + result = exists; + } + } + } } // if pBytes - ::RegCloseKey( sKey); - } + ::RegCloseKey( sKey); + } - return( result); + return( result); } nsresult nsEudoraWin32::FindMailboxes( nsIFileSpec *pRoot, nsISupportsArray **ppArray) { - nsresult rv = NS_NewISupportsArray( ppArray); - if (NS_FAILED( rv)) { - IMPORT_LOG0( "FAILED to allocate the nsISupportsArray\n"); - return( rv); - } - - nsCOMPtr impSvc(do_GetService(NS_IMPORTSERVICE_CONTRACTID, &rv)); - if (NS_FAILED( rv)) - return( rv); - - m_depth = 0; - NS_IF_RELEASE( m_mailImportLocation); - m_mailImportLocation = pRoot; - NS_IF_ADDREF( m_mailImportLocation); + nsresult rv = NS_NewISupportsArray( ppArray); + if (NS_FAILED( rv)) { + IMPORT_LOG0( "FAILED to allocate the nsISupportsArray\n"); + return( rv); + } + + nsCOMPtr impSvc(do_GetService(NS_IMPORTSERVICE_CONTRACTID, &rv)); + if (NS_FAILED( rv)) + return( rv); + + m_depth = 0; + NS_IF_RELEASE( m_mailImportLocation); + m_mailImportLocation = pRoot; + NS_IF_ADDREF( m_mailImportLocation); - return( ScanMailDir( pRoot, *ppArray, impSvc)); + return( ScanMailDir( pRoot, *ppArray, impSvc)); } nsresult nsEudoraWin32::ScanMailDir( nsIFileSpec *pFolder, nsISupportsArray *pArray, nsIImportService *pImport) { - PRBool exists = PR_FALSE; - PRBool isFile = PR_FALSE; - char * pContents = nsnull; - PRInt32 len = 0; - nsCOMPtr descMap; - nsresult rv; - - if (NS_FAILED( rv = NS_NewFileSpec( getter_AddRefs( descMap)))) - return( rv); - - m_depth++; - - descMap->FromFileSpec( pFolder); - rv = descMap->AppendRelativeUnixPath( "descmap.pce"); - if (NS_SUCCEEDED( rv)) - rv = descMap->IsFile( &isFile); - if (NS_SUCCEEDED( rv)) - rv = descMap->Exists( &exists); - if (NS_SUCCEEDED( rv) && exists && isFile) { - rv = descMap->GetFileContents( &pContents); - if (NS_SUCCEEDED( rv) && pContents) { - len = strlen( pContents); - if (NS_SUCCEEDED( rv)) - rv = ScanDescmap( pFolder, pArray, pImport, pContents, len); - nsCRT::free( pContents); - } - else - rv = NS_ERROR_FAILURE; - } - - if (NS_FAILED( rv) || !isFile || !exists) - rv = IterateMailDir( pFolder, pArray, pImport); - - m_depth--; + PRBool exists = PR_FALSE; + PRBool isFile = PR_FALSE; + char * pContents = nsnull; + PRInt32 len = 0; + nsCOMPtr descMap; + nsresult rv; + + if (NS_FAILED( rv = NS_NewFileSpec( getter_AddRefs( descMap)))) + return( rv); + + m_depth++; + + descMap->FromFileSpec( pFolder); + rv = descMap->AppendRelativeUnixPath( "descmap.pce"); + if (NS_SUCCEEDED( rv)) + rv = descMap->IsFile( &isFile); + if (NS_SUCCEEDED( rv)) + rv = descMap->Exists( &exists); + if (NS_SUCCEEDED( rv) && exists && isFile) { + rv = descMap->GetFileContents( &pContents); + if (NS_SUCCEEDED( rv) && pContents) { + len = strlen( pContents); + if (NS_SUCCEEDED( rv)) + rv = ScanDescmap( pFolder, pArray, pImport, pContents, len); + nsCRT::free( pContents); + } + else + rv = NS_ERROR_FAILURE; + } + + if (NS_FAILED( rv) || !isFile || !exists) + rv = IterateMailDir( pFolder, pArray, pImport); + + m_depth--; - return( rv); + return( rv); } nsresult nsEudoraWin32::IterateMailDir( nsIFileSpec *pFolder, nsISupportsArray *pArray, nsIImportService *pImport) { - nsCOMPtr dir; - nsresult rv = NS_NewDirectoryIterator( getter_AddRefs( dir)); - if (NS_FAILED( rv)) - return( rv); - - PRBool exists = PR_FALSE; - rv = dir->Init( pFolder, PR_TRUE); - if (NS_FAILED( rv)) - return( rv); - - rv = dir->Exists( &exists); - if (NS_FAILED( rv)) - return( rv); - - PRBool isFolder; - PRBool isFile; - nsCOMPtr entry; - char * pName; - nsCString fName; - nsCString ext; - nsCString name; - - while (exists && NS_SUCCEEDED( rv)) { - rv = dir->GetCurrentSpec( getter_AddRefs( entry)); - if (NS_SUCCEEDED( rv)) { - rv = entry->GetLeafName( &pName); - if (NS_SUCCEEDED( rv) && pName) { - fName = pName; - nsCRT::free( pName); - if (fName.Length() > 4) { - fName.Right( ext, 4); - fName.Left( name, fName.Length() - 4); - } - else { - ext.Truncate(); - name = fName; - } - ToLowerCase(ext); - if (ext.EqualsLiteral(".fol")) { - isFolder = PR_FALSE; - entry->IsDirectory( &isFolder); - if (isFolder) { - // add the folder - rv = FoundMailFolder( entry, name.get(), pArray, pImport); - if (NS_SUCCEEDED( rv)) { - rv = ScanMailDir( entry, pArray, pImport); - if (NS_FAILED( rv)) { - IMPORT_LOG0( "*** Error scanning mail directory\n"); - } - } - } - } - else if (ext.EqualsLiteral(".mbx")) { - isFile = PR_FALSE; - entry->IsFile( &isFile); - if (isFile) { - rv = FoundMailbox( entry, name.get(), pArray, pImport); - } - } - } - } - - rv = dir->Next(); - if (NS_SUCCEEDED( rv)) - rv = dir->Exists( &exists); - } + nsCOMPtr dir; + nsresult rv = NS_NewDirectoryIterator( getter_AddRefs( dir)); + if (NS_FAILED( rv)) + return( rv); - return( rv); + PRBool exists = PR_FALSE; + rv = dir->Init( pFolder, PR_TRUE); + if (NS_FAILED( rv)) + return( rv); + + rv = dir->Exists( &exists); + if (NS_FAILED( rv)) + return( rv); + + PRBool isFolder; + PRBool isFile; + nsCOMPtr entry; + char * pName; + nsCString fName; + nsCString ext; + nsCString name; + + while (exists && NS_SUCCEEDED( rv)) { + rv = dir->GetCurrentSpec( getter_AddRefs( entry)); + if (NS_SUCCEEDED( rv)) { + rv = entry->GetLeafName( &pName); + if (NS_SUCCEEDED( rv) && pName) { + fName = pName; + nsCRT::free( pName); + if (fName.Length() > 4) { + fName.Right( ext, 4); + fName.Left( name, fName.Length() - 4); + } + else { + ext.Truncate(); + name = fName; + } + ToLowerCase(ext); + if (ext.EqualsLiteral(".fol")) { + isFolder = PR_FALSE; + entry->IsDirectory( &isFolder); + if (isFolder) { + // add the folder + rv = FoundMailFolder( entry, name.get(), pArray, pImport); + if (NS_SUCCEEDED( rv)) { + rv = ScanMailDir( entry, pArray, pImport); + if (NS_FAILED( rv)) { + IMPORT_LOG0( "*** Error scanning mail directory\n"); + } + } + } + } + else if (ext.EqualsLiteral(".mbx")) { + isFile = PR_FALSE; + entry->IsFile( &isFile); + if (isFile) { + rv = FoundMailbox( entry, name.get(), pArray, pImport); + } + } + } + } + + rv = dir->Next(); + if (NS_SUCCEEDED( rv)) + rv = dir->Exists( &exists); + } + + return( rv); } nsresult nsEudoraWin32::ScanDescmap( nsIFileSpec *pFolder, nsISupportsArray *pArray, nsIImportService *pImport, const char *pData, PRInt32 len) { - // use this to find stuff in the directory. + // use this to find stuff in the directory. - nsCOMPtr entry; - nsresult rv; + nsCOMPtr entry; + nsresult rv; - if (NS_FAILED( rv = NS_NewFileSpec( getter_AddRefs( entry)))) - return( rv); - - // format is Name,FileName,Type,Flag? - // Type = M or S for mailbox - // = F for folder - - PRInt32 fieldLen; - PRInt32 pos = 0; - const char * pStart; - nsCString name; - nsCString fName; - nsCString type; - nsCString flag; - PRBool isFile; - PRBool isFolder; - while (pos < len) { - pStart = pData; - fieldLen = 0; - while ((pos < len) && (*pData != ',')) { - pos++; - pData++; - fieldLen++; - } - name.Truncate(); - if (fieldLen) - name.Append( pStart, fieldLen); - name.Trim( kWhitespace); - pos++; - pData++; - pStart = pData; - fieldLen = 0; - while ((pos < len) && (*pData != ',')) { - pos++; - pData++; - fieldLen++; - } - fName.Truncate(); - if (fieldLen) - fName.Append( pStart, fieldLen); - fName.Trim( kWhitespace); - pos++; - pData++; - pStart = pData; - fieldLen = 0; - while ((pos < len) && (*pData != ',')) { - pos++; - pData++; - fieldLen++; - } - type.Truncate(); - if (fieldLen) - type.Append( pStart, fieldLen); - type.Trim( kWhitespace); - pos++; - pData++; - pStart = pData; - fieldLen = 0; - while ((pos < len) && (*pData != 0x0D) && (*pData != 0x0A) && (*pData != ',')) { - pos++; - pData++; - fieldLen++; - } - flag.Truncate(); - if (fieldLen) - flag.Append( pStart, fieldLen); - flag.Trim( kWhitespace); - while ((pos < len) && ((*pData == 0x0D) || (*pData == 0x0A))) { - pos++; - pData++; - } - - IMPORT_LOG2( "name: %s, fName: %s\n", name.get(), fName.get()); - - if (!fName.IsEmpty() && !name.IsEmpty() && (type.Length() == 1)) { - entry->FromFileSpec( pFolder); - rv = entry->AppendRelativeUnixPath( fName.get()); - if (NS_SUCCEEDED( rv)) { - if (type.CharAt( 0) == 'F') { - isFolder = PR_FALSE; - entry->IsDirectory( &isFolder); - if (isFolder) { - rv = FoundMailFolder( entry, name.get(), pArray, pImport); - if (NS_SUCCEEDED( rv)) { - rv = ScanMailDir( entry, pArray, pImport); - if (NS_FAILED( rv)) { - IMPORT_LOG0( "*** Error scanning mail directory\n"); - } - } - } - } - else if ((type.CharAt( 0) == 'M') || (type.CharAt( 0) == 'S')) { - isFile = PR_FALSE; - entry->IsFile( &isFile); - if (isFile) { - FoundMailbox( entry, name.get(), pArray, pImport); - } - } - } - } - } + if (NS_FAILED( rv = NS_NewFileSpec( getter_AddRefs( entry)))) + return( rv); + + // format is Name,FileName,Type,Flag? + // Type = M or S for mailbox + // = F for folder + + PRInt32 fieldLen; + PRInt32 pos = 0; + const char * pStart; + nsCString name; + nsCString fName; + nsCString type; + nsCString flag; + PRBool isFile; + PRBool isFolder; + while (pos < len) { + pStart = pData; + fieldLen = 0; + while ((pos < len) && (*pData != ',')) { + pos++; + pData++; + fieldLen++; + } + name.Truncate(); + if (fieldLen) + name.Append( pStart, fieldLen); + name.Trim( kWhitespace); + pos++; + pData++; + pStart = pData; + fieldLen = 0; + while ((pos < len) && (*pData != ',')) { + pos++; + pData++; + fieldLen++; + } + fName.Truncate(); + if (fieldLen) + fName.Append( pStart, fieldLen); + fName.Trim( kWhitespace); + pos++; + pData++; + pStart = pData; + fieldLen = 0; + while ((pos < len) && (*pData != ',')) { + pos++; + pData++; + fieldLen++; + } + type.Truncate(); + if (fieldLen) + type.Append( pStart, fieldLen); + type.Trim( kWhitespace); + pos++; + pData++; + pStart = pData; + fieldLen = 0; + while ((pos < len) && (*pData != 0x0D) && (*pData != 0x0A) && (*pData != ',')) { + pos++; + pData++; + fieldLen++; + } + flag.Truncate(); + if (fieldLen) + flag.Append( pStart, fieldLen); + flag.Trim( kWhitespace); + while ((pos < len) && ((*pData == 0x0D) || (*pData == 0x0A))) { + pos++; + pData++; + } + + IMPORT_LOG2( "name: %s, fName: %s\n", name.get(), fName.get()); + + if (!fName.IsEmpty() && !name.IsEmpty() && (type.Length() == 1)) { + entry->FromFileSpec( pFolder); + rv = entry->AppendRelativeUnixPath( fName.get()); + if (NS_SUCCEEDED( rv)) { + if (type.CharAt( 0) == 'F') { + isFolder = PR_FALSE; + entry->IsDirectory( &isFolder); + if (isFolder) { + rv = FoundMailFolder( entry, name.get(), pArray, pImport); + if (NS_SUCCEEDED( rv)) { + rv = ScanMailDir( entry, pArray, pImport); + if (NS_FAILED( rv)) { + IMPORT_LOG0( "*** Error scanning mail directory\n"); + } + } + } + } + else if ((type.CharAt( 0) == 'M') || (type.CharAt( 0) == 'S')) { + isFile = PR_FALSE; + entry->IsFile( &isFile); + if (isFile) { + FoundMailbox( entry, name.get(), pArray, pImport); + } + } + } + } + } - return( NS_OK); + return( NS_OK); } nsresult nsEudoraWin32::FoundMailbox( nsIFileSpec *mailFile, const char *pName, nsISupportsArray *pArray, nsIImportService *pImport) { - nsString displayName; - nsCOMPtr desc; - nsISupports * pInterface; + nsString displayName; + nsCOMPtr desc; + nsISupports * pInterface; - NS_CopyNativeToUnicode(nsDependentCString(pName), displayName); + NS_CopyNativeToUnicode(nsDependentCString(pName), displayName); #ifdef IMPORT_DEBUG - char *pPath = nsnull; - mailFile->GetNativePath( &pPath); - if (pPath) { - IMPORT_LOG2( "Found eudora mailbox, %s: %s\n", pPath, pName); - nsCRT::free( pPath); - } - else { - IMPORT_LOG1( "Found eudora mailbox, %s\n", pName); - } - IMPORT_LOG1( "\tm_depth = %d\n", (int)m_depth); + char *pPath = nsnull; + mailFile->GetNativePath( &pPath); + if (pPath) { + IMPORT_LOG2( "Found eudora mailbox, %s: %s\n", pPath, pName); + nsCRT::free( pPath); + } + else { + IMPORT_LOG1( "Found eudora mailbox, %s\n", pName); + } + IMPORT_LOG1( "\tm_depth = %d\n", (int)m_depth); #endif - nsresult rv = pImport->CreateNewMailboxDescriptor( getter_AddRefs( desc)); - if (NS_SUCCEEDED( rv)) { - PRUint32 sz = 0; - mailFile->GetFileSize( &sz); - desc->SetDisplayName( displayName.get()); - desc->SetDepth( m_depth); - desc->SetSize( sz); - nsIFileSpec *pSpec = nsnull; - desc->GetFileSpec( &pSpec); - if (pSpec) { - pSpec->FromFileSpec( mailFile); - NS_RELEASE( pSpec); - } - rv = desc->QueryInterface( kISupportsIID, (void **) &pInterface); - pArray->AppendElement( pInterface); - pInterface->Release(); - } + nsresult rv = pImport->CreateNewMailboxDescriptor( getter_AddRefs( desc)); + if (NS_SUCCEEDED( rv)) { + PRUint32 sz = 0; + mailFile->GetFileSize( &sz); + desc->SetDisplayName( displayName.get()); + desc->SetDepth( m_depth); + desc->SetSize( sz); + nsIFileSpec *pSpec = nsnull; + desc->GetFileSpec( &pSpec); + if (pSpec) { + pSpec->FromFileSpec( mailFile); + NS_RELEASE( pSpec); + } + rv = desc->QueryInterface( kISupportsIID, (void **) &pInterface); + pArray->AppendElement( pInterface); + pInterface->Release(); + } - return( NS_OK); + return( NS_OK); } nsresult nsEudoraWin32::FoundMailFolder( nsIFileSpec *mailFolder, const char *pName, nsISupportsArray *pArray, nsIImportService *pImport) { - nsString displayName; - nsCOMPtr desc; - nsISupports * pInterface; + nsString displayName; + nsCOMPtr desc; + nsISupports * pInterface; - NS_CopyNativeToUnicode(nsDependentCString(pName), displayName); + NS_CopyNativeToUnicode(nsDependentCString(pName), displayName); #ifdef IMPORT_DEBUG - char *pPath = nsnull; - mailFolder->GetNativePath( &pPath); - if (pPath) { - IMPORT_LOG2( "Found eudora folder, %s: %s\n", pPath, pName); - nsCRT::free( pPath); - } - else { - IMPORT_LOG1( "Found eudora folder, %s\n", pName); - } - IMPORT_LOG1( "\tm_depth = %d\n", (int)m_depth); + char *pPath = nsnull; + mailFolder->GetNativePath( &pPath); + if (pPath) { + IMPORT_LOG2( "Found eudora folder, %s: %s\n", pPath, pName); + nsCRT::free( pPath); + } + else { + IMPORT_LOG1( "Found eudora folder, %s\n", pName); + } + IMPORT_LOG1( "\tm_depth = %d\n", (int)m_depth); #endif - nsresult rv = pImport->CreateNewMailboxDescriptor( getter_AddRefs( desc)); - if (NS_SUCCEEDED( rv)) { - PRUint32 sz = 0; - desc->SetDisplayName( displayName.get()); - desc->SetDepth( m_depth); - desc->SetSize( sz); - nsIFileSpec *pSpec = nsnull; - desc->GetFileSpec( &pSpec); - if (pSpec) { - pSpec->FromFileSpec( mailFolder); - NS_RELEASE( pSpec); - } - rv = desc->QueryInterface( kISupportsIID, (void **) &pInterface); - pArray->AppendElement( pInterface); - pInterface->Release(); - } + nsresult rv = pImport->CreateNewMailboxDescriptor( getter_AddRefs( desc)); + if (NS_SUCCEEDED( rv)) { + PRUint32 sz = 0; + desc->SetDisplayName( displayName.get()); + desc->SetDepth( m_depth); + desc->SetSize( sz); + nsIFileSpec *pSpec = nsnull; + desc->GetFileSpec( &pSpec); + if (pSpec) { + pSpec->FromFileSpec( mailFolder); + NS_RELEASE( pSpec); + } + rv = desc->QueryInterface( kISupportsIID, (void **) &pInterface); + pArray->AppendElement( pInterface); + pInterface->Release(); + } - return( NS_OK); + return( NS_OK); } nsresult nsEudoraWin32::FindTOCFile( nsIFileSpec *pMailFile, nsIFileSpec **ppTOCFile, PRBool *pDeleteToc) { - nsresult rv; - char * pName = nsnull; + nsresult rv; + char * pName = nsnull; + + *pDeleteToc = PR_FALSE; + *ppTOCFile = nsnull; + rv = pMailFile->GetLeafName( &pName); + if (NS_FAILED( rv)) + return( rv); + rv = pMailFile->GetParent( ppTOCFile); + if (NS_FAILED( rv)) + return( rv); + + nsCString leaf(pName); + nsCRT::free( pName); + nsCString name; + if ((leaf.Length() > 4) && (leaf.CharAt( leaf.Length() - 4) == '.')) + leaf.Left( name, leaf.Length() - 4); + else + name = leaf; + name.Append( ".toc"); + rv = (*ppTOCFile)->AppendRelativeUnixPath( name.get()); + if (NS_FAILED( rv)) + return( rv); - *pDeleteToc = PR_FALSE; - *ppTOCFile = nsnull; - rv = pMailFile->GetLeafName( &pName); - if (NS_FAILED( rv)) - return( rv); - rv = pMailFile->GetParent( ppTOCFile); - if (NS_FAILED( rv)) - return( rv); - - nsCString leaf(pName); - nsCRT::free( pName); - nsCString name; - if ((leaf.Length() > 4) && (leaf.CharAt( leaf.Length() - 4) == '.')) - leaf.Left( name, leaf.Length() - 4); - else - name = leaf; - name.Append( ".toc"); - rv = (*ppTOCFile)->AppendRelativeUnixPath( name.get()); - if (NS_FAILED( rv)) - return( rv); - - PRBool exists = PR_FALSE; - rv = (*ppTOCFile)->Exists( &exists); - if (NS_FAILED( rv)) - return( rv); - PRBool isFile = PR_FALSE; - rv = (*ppTOCFile)->IsFile( &isFile); - if (NS_FAILED( rv)) - return( rv); - if (exists && isFile) - return( NS_OK); - - return( NS_ERROR_FAILURE); + PRBool exists = PR_FALSE; + rv = (*ppTOCFile)->Exists( &exists); + if (NS_FAILED( rv)) + return( rv); + PRBool isFile = PR_FALSE; + rv = (*ppTOCFile)->IsFile( &isFile); + if (NS_FAILED( rv)) + return( rv); + if (exists && isFile) + return( NS_OK); + + return( NS_ERROR_FAILURE); } PRBool nsEudoraWin32::ImportSettings( nsIFileSpec *pIniFile, nsIMsgAccount **localMailAccount) { - PRBool result = PR_FALSE; - nsresult rv; + PRBool result = PR_FALSE; + nsresult rv; - nsCOMPtr accMgr = - do_GetService(NS_MSGACCOUNTMANAGER_CONTRACTID, &rv); + nsCOMPtr accMgr = + do_GetService(NS_MSGACCOUNTMANAGER_CONTRACTID, &rv); if (NS_FAILED(rv)) { - IMPORT_LOG0( "*** Failed to create a account manager!\n"); - return( PR_FALSE); - } - - // Eudora info is arranged by key, 1 for the default, then persona's for additional - // accounts. - // Start with the first one, then do each persona - char *pIniPath = nsnull; - pIniFile->GetNativePath( &pIniPath); - if (!pIniPath) - return( PR_FALSE); - - nsCString iniPath(pIniPath); - nsCRT::free( pIniPath); - - UINT valInt; - SimpleBufferTonyRCopiedOnce section; - DWORD sSize; - DWORD sOffset = 0; - DWORD start; - nsCString sectionName("Settings"); - int popCount = 0; - int accounts = 0; - - DWORD allocSize = 0; - do { - allocSize += 2048; - section.Allocate( allocSize); - sSize = ::GetPrivateProfileSection( "Personalities", section.m_pBuffer, allocSize, iniPath.get()); - } while (sSize == (allocSize - 2)); - - nsIMsgAccount * pAccount; - - do { - if (!sectionName.IsEmpty()) { - pAccount = nsnull; - valInt = ::GetPrivateProfileInt( sectionName.get(), "UsesPOP", 1, iniPath.get()); - if (valInt) { - // This is a POP account - if (BuildPOPAccount( accMgr, sectionName.get(), iniPath.get(), &pAccount)) { - accounts++; - popCount++; - if (popCount > 1) { - if (localMailAccount && *localMailAccount) { - NS_RELEASE( *localMailAccount); - *localMailAccount = nsnull; - } - } - else { - if (localMailAccount) { - *localMailAccount = pAccount; - NS_IF_ADDREF( pAccount); - } - } - } - } - else { - valInt = ::GetPrivateProfileInt( sectionName.get(), "UsesIMAP", 0, iniPath.get()); - if (valInt) { - // This is an IMAP account - if (BuildIMAPAccount( accMgr, sectionName.get(), iniPath.get(), &pAccount)) { - accounts++; - } - } - } - if (pAccount && (sOffset == 0)) { - accMgr->SetDefaultAccount( pAccount); - } - - NS_IF_RELEASE( pAccount); - } - - sectionName.Truncate(); - while ((sOffset < sSize) && (section.m_pBuffer[sOffset] != '=')) - sOffset++; - sOffset++; - start = sOffset; - while ((sOffset < sSize) && (section.m_pBuffer[sOffset] != 0)) - sOffset++; - if (sOffset > start) { - sectionName.Append( section.m_pBuffer + start, sOffset - start); - sectionName.Trim( kWhitespace); - } - - } while (sOffset < sSize); - - // Now save the new acct info to pref file. - rv = accMgr->SaveAccountInfo(); - NS_ASSERTION(NS_SUCCEEDED(rv), "Can't save account info to pref file"); + IMPORT_LOG0( "*** Failed to create a account manager!\n"); + return( PR_FALSE); + } + + // Eudora info is arranged by key, 1 for the default, then persona's for additional + // accounts. + // Start with the first one, then do each persona + char *pIniPath = nsnull; + pIniFile->GetNativePath( &pIniPath); + if (!pIniPath) + return( PR_FALSE); + + nsCString iniPath(pIniPath); + nsCRT::free( pIniPath); + + UINT valInt; + SimpleBufferTonyRCopiedOnce section; + DWORD sSize; + DWORD sOffset = 0; + DWORD start; + nsCString sectionName("Settings"); + int popCount = 0; + int accounts = 0; + + DWORD allocSize = 0; + do { + allocSize += 2048; + section.Allocate( allocSize); + sSize = ::GetPrivateProfileSection( "Personalities", section.m_pBuffer, allocSize, iniPath.get()); + } while (sSize == (allocSize - 2)); + + nsIMsgAccount * pAccount; + + do { + if (!sectionName.IsEmpty()) { + pAccount = nsnull; + valInt = ::GetPrivateProfileInt( sectionName.get(), "UsesPOP", 1, iniPath.get()); + if (valInt) { + // This is a POP account + if (BuildPOPAccount( accMgr, sectionName.get(), iniPath.get(), &pAccount)) { + accounts++; + popCount++; + if (popCount > 1) { + if (localMailAccount && *localMailAccount) { + NS_RELEASE( *localMailAccount); + *localMailAccount = nsnull; + } + } + else { + if (localMailAccount) { + *localMailAccount = pAccount; + NS_IF_ADDREF( pAccount); + } + } + } + } + else { + valInt = ::GetPrivateProfileInt( sectionName.get(), "UsesIMAP", 0, iniPath.get()); + if (valInt) { + // This is an IMAP account + if (BuildIMAPAccount( accMgr, sectionName.get(), iniPath.get(), &pAccount)) { + accounts++; + } + } + } + if (pAccount && (sOffset == 0)) { + accMgr->SetDefaultAccount( pAccount); + } + + NS_IF_RELEASE( pAccount); + } + + sectionName.Truncate(); + while ((sOffset < sSize) && (section.m_pBuffer[sOffset] != '=')) + sOffset++; + sOffset++; + start = sOffset; + while ((sOffset < sSize) && (section.m_pBuffer[sOffset] != 0)) + sOffset++; + if (sOffset > start) { + sectionName.Append( section.m_pBuffer + start, sOffset - start); + sectionName.Trim( kWhitespace); + } + + } while (sOffset < sSize); + + // Now save the new acct info to pref file. + rv = accMgr->SaveAccountInfo(); + NS_ASSERTION(NS_SUCCEEDED(rv), "Can't save account info to pref file"); - return( accounts != 0); + return( accounts != 0); } // maximium size of settings strings -#define kIniValueSize 384 +#define kIniValueSize 384 void nsEudoraWin32::GetServerAndUserName( const char *pSection, const char *pIni, nsCString& serverName, nsCString& userName, char *pBuff) { - DWORD valSize; - int idx; - nsCString tStr; - - serverName.Truncate(); - userName.Truncate(); - - valSize = ::GetPrivateProfileString( pSection, "PopServer", "", pBuff, kIniValueSize, pIni); - if (valSize) - serverName = pBuff; - else { - valSize = ::GetPrivateProfileString( pSection, "POPAccount", "", pBuff, kIniValueSize, pIni); - if (valSize) { - serverName = pBuff; - idx = serverName.FindChar( '@'); - if (idx != -1) { - serverName.Right( tStr, serverName.Length() - idx - 1); - serverName = tStr; - } - } - } - valSize = ::GetPrivateProfileString( pSection, "LoginName", "", pBuff, kIniValueSize, pIni); - if (valSize) - userName = pBuff; - else { - valSize = ::GetPrivateProfileString( pSection, "POPAccount", "", pBuff, kIniValueSize, pIni); - if (valSize) { - userName = pBuff; - idx = userName.FindChar( '@'); - if (idx != -1) { - userName.Left( tStr, idx); - userName = tStr; - } - } - } + DWORD valSize; + int idx; + nsCString tStr; + + serverName.Truncate(); + userName.Truncate(); + + valSize = ::GetPrivateProfileString( pSection, "PopServer", "", pBuff, kIniValueSize, pIni); + if (valSize) + serverName = pBuff; + else { + valSize = ::GetPrivateProfileString( pSection, "POPAccount", "", pBuff, kIniValueSize, pIni); + if (valSize) { + serverName = pBuff; + idx = serverName.FindChar( '@'); + if (idx != -1) { + serverName.Right( tStr, serverName.Length() - idx - 1); + serverName = tStr; + } + } + } + valSize = ::GetPrivateProfileString( pSection, "LoginName", "", pBuff, kIniValueSize, pIni); + if (valSize) + userName = pBuff; + else { + valSize = ::GetPrivateProfileString( pSection, "POPAccount", "", pBuff, kIniValueSize, pIni); + if (valSize) { + userName = pBuff; + idx = userName.FindChar( '@'); + if (idx != -1) { + userName.Left( tStr, idx); + userName = tStr; + } + } + } } void nsEudoraWin32::GetAccountName( const char *pSection, nsString& str) { - str.Truncate(); + str.Truncate(); - nsCString s(pSection); - - if (s.Equals(NS_LITERAL_CSTRING("Settings"), nsCaseInsensitiveCStringComparator())) { - str.AssignLiteral("Eudora "); - str.AppendWithConversion( pSection); - } - else { - nsCString tStr; - str.AssignWithConversion(pSection); - if (s.Length() > 8) { - s.Left( tStr, 8); - if (tStr.Equals(NS_LITERAL_CSTRING("Persona-"), nsCaseInsensitiveCStringComparator())) { - s.Right( tStr, s.Length() - 8); - str.AssignWithConversion(tStr.get()); - } - } - } + nsCString s(pSection); + + if (s.Equals(NS_LITERAL_CSTRING("Settings"), nsCaseInsensitiveCStringComparator())) { + str.AssignLiteral("Eudora "); + str.AppendWithConversion( pSection); + } + else { + nsCString tStr; + str.AssignWithConversion(pSection); + if (s.Length() > 8) { + s.Left( tStr, 8); + if (tStr.Equals(NS_LITERAL_CSTRING("Persona-"), nsCaseInsensitiveCStringComparator())) { + s.Right( tStr, s.Length() - 8); + str.AssignWithConversion(tStr.get()); + } + } + } } PRBool nsEudoraWin32::BuildPOPAccount( nsIMsgAccountManager *accMgr, const char *pSection, const char *pIni, nsIMsgAccount **ppAccount) { - if (ppAccount) - *ppAccount = nsnull; - - char valBuff[kIniValueSize]; - nsCString serverName; - nsCString userName; - - GetServerAndUserName( pSection, pIni, serverName, userName, valBuff); - - if (serverName.IsEmpty() || userName.IsEmpty()) - return( PR_FALSE); - - PRBool result = PR_FALSE; - - // I now have a user name/server name pair, find out if it already exists? - nsCOMPtr in; - nsresult rv = accMgr->FindServer( userName.get(), serverName.get(), "pop3", getter_AddRefs( in)); - if (NS_FAILED( rv) || (in == nsnull)) { - // Create the incoming server and an account for it? - rv = accMgr->CreateIncomingServer( userName.get(), serverName.get(), "pop3", getter_AddRefs( in)); - if (NS_SUCCEEDED( rv) && in) { - rv = in->SetType( "pop3"); - // rv = in->SetHostName( serverName); - // rv = in->SetUsername( userName); - - IMPORT_LOG2( "Created POP3 server named: %s, userName: %s\n", serverName.get(), userName.get()); - - nsString prettyName; - GetAccountName( pSection, prettyName); - - PRUnichar *pretty = ToNewUnicode(prettyName); - IMPORT_LOG1( "\tSet pretty name to: %S\n", pretty); - rv = in->SetPrettyName( pretty); - nsCRT::free( pretty); - - // We have a server, create an account. - nsCOMPtr account; - rv = accMgr->CreateAccount( getter_AddRefs( account)); - if (NS_SUCCEEDED( rv) && account) { - rv = account->SetIncomingServer( in); + if (ppAccount) + *ppAccount = nsnull; + + char valBuff[kIniValueSize]; + nsCString serverName; + nsCString userName; + + GetServerAndUserName( pSection, pIni, serverName, userName, valBuff); + + if (serverName.IsEmpty() || userName.IsEmpty()) + return( PR_FALSE); + + PRBool result = PR_FALSE; + + // I now have a user name/server name pair, find out if it already exists? + nsCOMPtr in; + nsresult rv = accMgr->FindServer( userName.get(), serverName.get(), "pop3", getter_AddRefs( in)); + if (NS_FAILED( rv) || (in == nsnull)) { + // Create the incoming server and an account for it? + rv = accMgr->CreateIncomingServer( userName.get(), serverName.get(), "pop3", getter_AddRefs( in)); + if (NS_SUCCEEDED( rv) && in) { + rv = in->SetType( "pop3"); + // rv = in->SetHostName( serverName); + // rv = in->SetUsername( userName); + + IMPORT_LOG2( "Created POP3 server named: %s, userName: %s\n", serverName.get(), userName.get()); + + nsString prettyName; + GetAccountName( pSection, prettyName); + + PRUnichar *pretty = ToNewUnicode(prettyName); + IMPORT_LOG1( "\tSet pretty name to: %S\n", pretty); + rv = in->SetPrettyName( pretty); + nsCRT::free( pretty); + + // We have a server, create an account. + nsCOMPtr account; + rv = accMgr->CreateAccount( getter_AddRefs( account)); + if (NS_SUCCEEDED( rv) && account) { + rv = account->SetIncomingServer( in); - IMPORT_LOG0( "Created a new account and set the incoming server to the POP3 server.\n"); - + IMPORT_LOG0( "Created a new account and set the incoming server to the POP3 server.\n"); + nsCOMPtr pop3Server = do_QueryInterface(in, &rv); NS_ENSURE_SUCCESS(rv,rv); UINT valInt = ::GetPrivateProfileInt(pSection, "LeaveMailOnServer", 0, pIni); pop3Server->SetLeaveMessagesOnServer(valInt ? PR_TRUE : PR_FALSE); - - // Fiddle with the identities - SetIdentities(accMgr, account, pSection, pIni, userName.get(), serverName.get(), valBuff); - result = PR_TRUE; - if (ppAccount) - account->QueryInterface( NS_GET_IID(nsIMsgAccount), (void **)ppAccount); - } - } - } - else - result = PR_TRUE; - - return( result); + + // Fiddle with the identities + SetIdentities(accMgr, account, pSection, pIni, userName.get(), serverName.get(), valBuff); + result = PR_TRUE; + if (ppAccount) + CallQueryInterface(account, ppAccount); + } + } + } + else + result = PR_TRUE; + + return( result); } PRBool nsEudoraWin32::BuildIMAPAccount( nsIMsgAccountManager *accMgr, const char *pSection, const char *pIni, nsIMsgAccount **ppAccount) { - char valBuff[kIniValueSize]; - nsCString serverName; - nsCString userName; - - GetServerAndUserName( pSection, pIni, serverName, userName, valBuff); - - if (serverName.IsEmpty() || userName.IsEmpty()) - return( PR_FALSE); - - PRBool result = PR_FALSE; - - nsCOMPtr in; - nsresult rv = accMgr->FindServer( userName.get(), serverName.get(), "imap", getter_AddRefs( in)); - if (NS_FAILED( rv) || (in == nsnull)) { - // Create the incoming server and an account for it? - rv = accMgr->CreateIncomingServer( userName.get(), serverName.get(), "imap", getter_AddRefs( in)); - if (NS_SUCCEEDED( rv) && in) { - rv = in->SetType( "imap"); - // rv = in->SetHostName( serverName); - // rv = in->SetUsername( userName); - - IMPORT_LOG2( "Created IMAP server named: %s, userName: %s\n", serverName.get(), userName.get()); - - nsString prettyName; - GetAccountName( pSection, prettyName); - - PRUnichar *pretty = ToNewUnicode(prettyName); - - IMPORT_LOG1( "\tSet pretty name to: %S\n", pretty); - - rv = in->SetPrettyName( pretty); - nsCRT::free( pretty); - - // We have a server, create an account. - nsCOMPtr account; - rv = accMgr->CreateAccount( getter_AddRefs( account)); - if (NS_SUCCEEDED( rv) && account) { - rv = account->SetIncomingServer( in); - - IMPORT_LOG0( "Created an account and set the IMAP server as the incoming server\n"); - - // Fiddle with the identities - SetIdentities(accMgr, account, pSection, pIni, userName.get(), serverName.get(), valBuff); - result = PR_TRUE; - if (ppAccount) - account->QueryInterface( NS_GET_IID(nsIMsgAccount), (void **)ppAccount); - } - } - } - else - result = PR_TRUE; + char valBuff[kIniValueSize]; + nsCString serverName; + nsCString userName; + + GetServerAndUserName( pSection, pIni, serverName, userName, valBuff); + + if (serverName.IsEmpty() || userName.IsEmpty()) + return( PR_FALSE); + + PRBool result = PR_FALSE; + + nsCOMPtr in; + nsresult rv = accMgr->FindServer( userName.get(), serverName.get(), "imap", getter_AddRefs( in)); + if (NS_FAILED( rv) || (in == nsnull)) { + // Create the incoming server and an account for it? + rv = accMgr->CreateIncomingServer( userName.get(), serverName.get(), "imap", getter_AddRefs( in)); + if (NS_SUCCEEDED( rv) && in) { + rv = in->SetType( "imap"); + // rv = in->SetHostName( serverName); + // rv = in->SetUsername( userName); + + IMPORT_LOG2( "Created IMAP server named: %s, userName: %s\n", serverName.get(), userName.get()); + + nsString prettyName; + GetAccountName( pSection, prettyName); + + PRUnichar *pretty = ToNewUnicode(prettyName); + + IMPORT_LOG1( "\tSet pretty name to: %S\n", pretty); + + rv = in->SetPrettyName( pretty); + nsCRT::free( pretty); + + // We have a server, create an account. + nsCOMPtr account; + rv = accMgr->CreateAccount( getter_AddRefs( account)); + if (NS_SUCCEEDED( rv) && account) { + rv = account->SetIncomingServer( in); + + IMPORT_LOG0( "Created an account and set the IMAP server as the incoming server\n"); + + // Fiddle with the identities + SetIdentities(accMgr, account, pSection, pIni, userName.get(), serverName.get(), valBuff); + result = PR_TRUE; + if (ppAccount) + CallQueryInterface(account, ppAccount); + } + } + } + else + result = PR_TRUE; - return( result); + return( result); } void nsEudoraWin32::SetIdentities(nsIMsgAccountManager *accMgr, nsIMsgAccount *acc, const char *pSection, const char *pIniFile, const char *userName, const char *serverName, char *pBuff) { - nsCAutoString realName; - nsCAutoString email; - nsCAutoString server; - DWORD valSize; - nsresult rv; - - valSize = ::GetPrivateProfileString( pSection, "RealName", "", pBuff, kIniValueSize, pIniFile); - if (valSize) - realName = pBuff; - valSize = ::GetPrivateProfileString( pSection, "SMTPServer", "", pBuff, kIniValueSize, pIniFile); - if (valSize) - server = pBuff; - valSize = ::GetPrivateProfileString( pSection, "ReturnAddress", "", pBuff, kIniValueSize, pIniFile); - if (valSize) - email = pBuff; - - nsCOMPtr id; - rv = accMgr->CreateIdentity( getter_AddRefs( id)); - if (id) { - nsAutoString fullName; - fullName.AssignWithConversion(realName.get()); - id->SetFullName( fullName.get()); - id->SetIdentityName( fullName.get()); - if (email.IsEmpty()) { - email = userName; - email += "@"; - email += serverName; - } - id->SetEmail(email.get()); - acc->AddIdentity( id); - - IMPORT_LOG0( "Created identity and added to the account\n"); - IMPORT_LOG1( "\tname: %s\n", realName.get()); - IMPORT_LOG1( "\temail: %s\n", email.get()); - } + nsCAutoString realName; + nsCAutoString email; + nsCAutoString server; + DWORD valSize; + nsresult rv; + + valSize = ::GetPrivateProfileString( pSection, "RealName", "", pBuff, kIniValueSize, pIniFile); + if (valSize) + realName = pBuff; + valSize = ::GetPrivateProfileString( pSection, "SMTPServer", "", pBuff, kIniValueSize, pIniFile); + if (valSize) + server = pBuff; + valSize = ::GetPrivateProfileString( pSection, "ReturnAddress", "", pBuff, kIniValueSize, pIniFile); + if (valSize) + email = pBuff; + + nsCOMPtr id; + rv = accMgr->CreateIdentity( getter_AddRefs( id)); + if (id) { + nsAutoString fullName; + fullName.AssignWithConversion(realName.get()); + id->SetFullName( fullName.get()); + id->SetIdentityName( fullName.get()); + if (email.IsEmpty()) { + email = userName; + email += "@"; + email += serverName; + } + id->SetEmail(email.get()); + acc->AddIdentity( id); + + IMPORT_LOG0( "Created identity and added to the account\n"); + IMPORT_LOG1( "\tname: %s\n", realName.get()); + IMPORT_LOG1( "\temail: %s\n", email.get()); + } - SetSmtpServer( accMgr, acc, server.get(), userName); - + SetSmtpServer( accMgr, acc, server.get(), userName); + } void nsEudoraWin32::SetSmtpServer( nsIMsgAccountManager *pMgr, nsIMsgAccount *pAcc, const char *pServer, const char *pUser) { - nsresult rv; - - nsCOMPtr smtpService(do_GetService(NS_SMTPSERVICE_CONTRACTID, &rv)); - if (NS_SUCCEEDED(rv) && smtpService) { - nsCOMPtr foundServer; - - rv = smtpService->FindServer( pUser, pServer, getter_AddRefs( foundServer)); - if (NS_SUCCEEDED( rv) && foundServer) { - IMPORT_LOG1( "SMTP server already exists: %s\n", pServer); - return; - } - nsCOMPtr smtpServer; - - rv = smtpService->CreateSmtpServer( getter_AddRefs( smtpServer)); - if (NS_SUCCEEDED( rv) && smtpServer) { - smtpServer->SetHostname( pServer); - if (pUser) - smtpServer->SetUsername( pUser); - - IMPORT_LOG1( "Created new SMTP server: %s\n", pServer); - } - } + nsresult rv; + + nsCOMPtr smtpService(do_GetService(NS_SMTPSERVICE_CONTRACTID, &rv)); + if (NS_SUCCEEDED(rv) && smtpService) { + nsCOMPtr foundServer; + + rv = smtpService->FindServer( pUser, pServer, getter_AddRefs( foundServer)); + if (NS_SUCCEEDED( rv) && foundServer) { + IMPORT_LOG1( "SMTP server already exists: %s\n", pServer); + return; + } + nsCOMPtr smtpServer; + + rv = smtpService->CreateSmtpServer( getter_AddRefs( smtpServer)); + if (NS_SUCCEEDED( rv) && smtpServer) { + smtpServer->SetHostname( pServer); + if (pUser) + smtpServer->SetUsername( pUser); + + IMPORT_LOG1( "Created new SMTP server: %s\n", pServer); + } + } } nsresult nsEudoraWin32::GetAttachmentInfo( const char *pFileName, nsIFileSpec *pSpec, nsCString& mimeType, nsCString& aAttachmentName) { - mimeType.Truncate(); - pSpec->SetNativePath( pFileName); - nsresult rv; - PRBool isFile = PR_FALSE; - PRBool exists = PR_FALSE; - if (NS_FAILED( rv = pSpec->Exists( &exists))) - return( rv); - if (NS_FAILED( rv = pSpec->IsFile( &isFile))) - return( rv); - if (exists && isFile) { - char *pLeaf = nsnull; - pSpec->GetLeafName( &pLeaf); - if (!pLeaf) - return( NS_ERROR_FAILURE); - nsCString name(pLeaf); - nsCRT::free( pLeaf); - if (name.Length() > 4) { - nsCString ext; - PRInt32 idx = name.RFindChar( '.'); - if (idx != -1) { - name.Right( ext, name.Length() - idx); - GetMimeTypeFromExtension( ext, mimeType); - } - } - if (mimeType.IsEmpty()) - mimeType = "application/octet-stream"; + mimeType.Truncate(); + pSpec->SetNativePath( pFileName); + nsresult rv; + PRBool isFile = PR_FALSE; + PRBool exists = PR_FALSE; + if (NS_FAILED( rv = pSpec->Exists( &exists))) + return( rv); + if (NS_FAILED( rv = pSpec->IsFile( &isFile))) + return( rv); + if (exists && isFile) { + char *pLeaf = nsnull; + pSpec->GetLeafName( &pLeaf); + if (!pLeaf) + return( NS_ERROR_FAILURE); + nsCString name(pLeaf); + nsCRT::free( pLeaf); + if (name.Length() > 4) { + nsCString ext; + PRInt32 idx = name.RFindChar( '.'); + if (idx != -1) { + name.Right( ext, name.Length() - idx); + GetMimeTypeFromExtension( ext, mimeType); + } + } + if (mimeType.IsEmpty()) + mimeType = "application/octet-stream"; aAttachmentName = name; // use the leaf name of the attachment file url as the attachment name - return( NS_OK); - } - - return( NS_ERROR_FAILURE); + return( NS_OK); + } + + return( NS_ERROR_FAILURE); } PRBool nsEudoraWin32::FindMimeIniFile( nsIFileSpec *pSpec) { - nsCOMPtr dir; - nsresult rv = NS_NewDirectoryIterator( getter_AddRefs( dir)); - if (NS_FAILED( rv)) - return( PR_FALSE); - - PRBool exists = PR_FALSE; - rv = dir->Init( pSpec, PR_TRUE); - if (NS_FAILED( rv)) - return( PR_FALSE); - - rv = dir->Exists( &exists); - if (NS_FAILED( rv)) - return( PR_FALSE); - - PRBool isFile; - nsCOMPtr entry; - char * pName; - nsCString fName; - nsCString ext; - nsCString name; - PRBool found = PR_FALSE; - - while (exists && NS_SUCCEEDED( rv)) { - rv = dir->GetCurrentSpec( getter_AddRefs( entry)); - if (NS_SUCCEEDED( rv)) { - rv = entry->GetLeafName( &pName); - if (NS_SUCCEEDED( rv) && pName) { - fName = pName; - nsCRT::free( pName); - if (fName.Length() > 4) { - fName.Right( ext, 4); - fName.Left( name, fName.Length() - 4); - } - else { - ext.Truncate(); - name = fName; - } - ToLowerCase(ext); - if (ext.EqualsLiteral(".ini")) { - isFile = PR_FALSE; - entry->IsFile( &isFile); - if (isFile) { - if (found) { - // which one of these files is newer? - PRUint32 modDate1, modDate2; - entry->GetModDate( &modDate2); - pSpec->GetModDate( &modDate1); - if (modDate2 > modDate1) - pSpec->FromFileSpec( entry); - } - else { - pSpec->FromFileSpec( entry); - found = PR_TRUE; - } - } - } - } - } - - rv = dir->Next(); - if (NS_SUCCEEDED( rv)) - rv = dir->Exists( &exists); - } - - if (found) - return( PR_TRUE); - else - return( PR_FALSE); + nsCOMPtr dir; + nsresult rv = NS_NewDirectoryIterator( getter_AddRefs( dir)); + if (NS_FAILED( rv)) + return( PR_FALSE); + + PRBool exists = PR_FALSE; + rv = dir->Init( pSpec, PR_TRUE); + if (NS_FAILED( rv)) + return( PR_FALSE); + + rv = dir->Exists( &exists); + if (NS_FAILED( rv)) + return( PR_FALSE); + + PRBool isFile; + nsCOMPtr entry; + char * pName; + nsCString fName; + nsCString ext; + nsCString name; + PRBool found = PR_FALSE; + + while (exists && NS_SUCCEEDED( rv)) { + rv = dir->GetCurrentSpec( getter_AddRefs( entry)); + if (NS_SUCCEEDED( rv)) { + rv = entry->GetLeafName( &pName); + if (NS_SUCCEEDED( rv) && pName) { + fName = pName; + nsCRT::free( pName); + if (fName.Length() > 4) { + fName.Right( ext, 4); + fName.Left( name, fName.Length() - 4); + } + else { + ext.Truncate(); + name = fName; + } + ToLowerCase(ext); + if (ext.EqualsLiteral(".ini")) { + isFile = PR_FALSE; + entry->IsFile( &isFile); + if (isFile) { + if (found) { + // which one of these files is newer? + PRUint32 modDate1, modDate2; + entry->GetModDate( &modDate2); + pSpec->GetModDate( &modDate1); + if (modDate2 > modDate1) + pSpec->FromFileSpec( entry); + } + else { + pSpec->FromFileSpec( entry); + found = PR_TRUE; + } + } + } + } + } + + rv = dir->Next(); + if (NS_SUCCEEDED( rv)) + rv = dir->Exists( &exists); + } + + if (found) + return( PR_TRUE); + else + return( PR_FALSE); } void nsEudoraWin32::GetMimeTypeFromExtension( nsCString& ext, nsCString& mimeType) { - HKEY sKey; - if (::RegOpenKeyEx( HKEY_CLASSES_ROOT, ext.get(), 0, KEY_QUERY_VALUE, &sKey) == ERROR_SUCCESS) { - // get the value of "Current" - BYTE *pBytes = GetValueBytes( sKey, "Content Type"); - if (pBytes) { - mimeType = (const char *)pBytes; - delete [] pBytes; - } - ::RegCloseKey( sKey); - } - - if (!mimeType.IsEmpty() || !m_mailImportLocation || (ext.Length() > 10)) - return; - - // TLR: FIXME: We should/could cache the extension to mime type maps we find - // and check the cache first before scanning all of eudora's mappings? - - // It's not in the registry, try and find the .ini file for Eudora's private - // mime type list - if (!m_pMimeSection) { - nsIFileSpec *pSpec; - nsresult rv = NS_NewFileSpec( &pSpec); - if (NS_FAILED( rv) || !pSpec) - return; - - pSpec->FromFileSpec( m_mailImportLocation); - - pSpec->AppendRelativeUnixPath( "eudora.ini"); - PRBool exists = PR_FALSE; - PRBool isFile = PR_FALSE; - rv = pSpec->Exists( &exists); - if (NS_SUCCEEDED( rv)) - rv = pSpec->IsFile( &isFile); - - if (!isFile || !exists) { - rv = pSpec->FromFileSpec( m_mailImportLocation); - if (NS_FAILED( rv)) - return; - if (!FindMimeIniFile( pSpec)) - return; - } - - char *pName = nsnull; - pSpec->GetNativePath( &pName); - if (!pName) - return; - nsCString fileName(pName); - nsCRT::free( pName); - - // Read the mime map section - DWORD size = 1024; - DWORD dSize = size - 2; - while (dSize == (size - 2)) { - if (m_pMimeSection) - delete [] m_pMimeSection; - size += 1024; - m_pMimeSection = new char[size]; - dSize = ::GetPrivateProfileSection( "Mappings", m_pMimeSection, size, fileName.get()); - } - } - - if (!m_pMimeSection) - return; - - IMPORT_LOG1( "Looking for mime type for extension: %s\n", ext.get()); - - // out/in/both=extension,mac creator,mac type,mime type1,mime type2 - const char *pExt = ext.get(); - pExt++; - - char * pChar = m_pMimeSection; - char * pStart; - int len; - nsCString tStr; - for(;;) { - while (*pChar != '=') { - if (!(*pChar) && !(*(pChar + 1))) - return; - pChar++; - } - if (*pChar) - pChar++; - pStart = pChar; - len = 0; - while (*pChar && (*pChar != ',')) { - pChar++; - len++; - } - if (!*pChar) return; - tStr.Truncate(); - tStr.Append( pStart, len); - tStr.Trim( kWhitespace); - if (!nsCRT::strcasecmp( tStr.get(), pExt)) { - // skip the mac creator and type - pChar++; - while (*pChar && (*pChar != ',')) - pChar++; - if (!*pChar) return; - pChar++; - while (*pChar && (*pChar != ',')) - pChar++; - if (!*pChar) return; - pChar++; - // Get the first mime type - len = 0; - pStart = pChar; - while (*pChar && (*pChar != ',')) { - pChar++; - len++; - } - if (!*pChar) return; - pChar++; - if (!len) continue; - tStr.Truncate(); - tStr.Append( pStart, len); - tStr.Trim( kWhitespace); - if (tStr.IsEmpty()) continue; - mimeType.Truncate(); - mimeType.Append( tStr.get()); - mimeType.Append( "/"); - pStart = pChar; - len = 0; - while (*pChar && (*pChar != 0x0D) && (*pChar != 0x0A)) { - pChar++; - len++; - } - if (!len) continue; - tStr.Truncate(); - tStr.Append( pStart, len); - tStr.Trim( kWhitespace); - if (tStr.IsEmpty()) continue; - mimeType.Append( tStr.get()); - - IMPORT_LOG1( "Found Mime Type: %s\n", mimeType.get()); - - return; - } - } + HKEY sKey; + if (::RegOpenKeyEx( HKEY_CLASSES_ROOT, ext.get(), 0, KEY_QUERY_VALUE, &sKey) == ERROR_SUCCESS) { + // get the value of "Current" + BYTE *pBytes = GetValueBytes( sKey, "Content Type"); + if (pBytes) { + mimeType = (const char *)pBytes; + delete [] pBytes; + } + ::RegCloseKey( sKey); + } + + if (!mimeType.IsEmpty() || !m_mailImportLocation || (ext.Length() > 10)) + return; + + // TLR: FIXME: We should/could cache the extension to mime type maps we find + // and check the cache first before scanning all of eudora's mappings? + + // It's not in the registry, try and find the .ini file for Eudora's private + // mime type list + if (!m_pMimeSection) { + nsIFileSpec *pSpec; + nsresult rv = NS_NewFileSpec( &pSpec); + if (NS_FAILED( rv) || !pSpec) + return; + + pSpec->FromFileSpec( m_mailImportLocation); + + pSpec->AppendRelativeUnixPath( "eudora.ini"); + PRBool exists = PR_FALSE; + PRBool isFile = PR_FALSE; + rv = pSpec->Exists( &exists); + if (NS_SUCCEEDED( rv)) + rv = pSpec->IsFile( &isFile); + + if (!isFile || !exists) { + rv = pSpec->FromFileSpec( m_mailImportLocation); + if (NS_FAILED( rv)) + return; + if (!FindMimeIniFile( pSpec)) + return; + } + + char *pName = nsnull; + pSpec->GetNativePath( &pName); + if (!pName) + return; + nsCString fileName(pName); + nsCRT::free( pName); + + // Read the mime map section + DWORD size = 1024; + DWORD dSize = size - 2; + while (dSize == (size - 2)) { + if (m_pMimeSection) + delete [] m_pMimeSection; + size += 1024; + m_pMimeSection = new char[size]; + dSize = ::GetPrivateProfileSection( "Mappings", m_pMimeSection, size, fileName.get()); + } + } + + if (!m_pMimeSection) + return; + + IMPORT_LOG1( "Looking for mime type for extension: %s\n", ext.get()); + + // out/in/both=extension,mac creator,mac type,mime type1,mime type2 + const char *pExt = ext.get(); + pExt++; + + char * pChar = m_pMimeSection; + char * pStart; + int len; + nsCString tStr; + for(;;) { + while (*pChar != '=') { + if (!(*pChar) && !(*(pChar + 1))) + return; + pChar++; + } + if (*pChar) + pChar++; + pStart = pChar; + len = 0; + while (*pChar && (*pChar != ',')) { + pChar++; + len++; + } + if (!*pChar) return; + tStr.Truncate(); + tStr.Append( pStart, len); + tStr.Trim( kWhitespace); + if (!nsCRT::strcasecmp( tStr.get(), pExt)) { + // skip the mac creator and type + pChar++; + while (*pChar && (*pChar != ',')) + pChar++; + if (!*pChar) return; + pChar++; + while (*pChar && (*pChar != ',')) + pChar++; + if (!*pChar) return; + pChar++; + // Get the first mime type + len = 0; + pStart = pChar; + while (*pChar && (*pChar != ',')) { + pChar++; + len++; + } + if (!*pChar) return; + pChar++; + if (!len) continue; + tStr.Truncate(); + tStr.Append( pStart, len); + tStr.Trim( kWhitespace); + if (tStr.IsEmpty()) continue; + mimeType.Truncate(); + mimeType.Append( tStr.get()); + mimeType.Append( "/"); + pStart = pChar; + len = 0; + while (*pChar && (*pChar != 0x0D) && (*pChar != 0x0A)) { + pChar++; + len++; + } + if (!len) continue; + tStr.Truncate(); + tStr.Append( pStart, len); + tStr.Trim( kWhitespace); + if (tStr.IsEmpty()) continue; + mimeType.Append( tStr.get()); + + IMPORT_LOG1( "Found Mime Type: %s\n", mimeType.get()); + + return; + } + } } PRBool nsEudoraWin32::FindAddressFolder( nsIFileSpec *pFolder) { - IMPORT_LOG0( "*** Looking for Eudora address folder\n"); + IMPORT_LOG0( "*** Looking for Eudora address folder\n"); - return( FindEudoraLocation( pFolder)); + return( FindEudoraLocation( pFolder)); } nsresult nsEudoraWin32::FindAddressBooks( nsIFileSpec *pRoot, nsISupportsArray **ppArray) { - nsCOMPtr spec; - nsresult rv = NS_NewFileSpec( getter_AddRefs( spec)); - if (NS_FAILED( rv)) - return( rv); - rv = spec->FromFileSpec( pRoot); - if (NS_FAILED( rv)) - return( rv); - - rv = NS_NewISupportsArray( ppArray); - if (NS_FAILED( rv)) { - IMPORT_LOG0( "FAILED to allocate the nsISupportsArray\n"); - return( rv); - } - - nsCOMPtr impSvc(do_GetService(NS_IMPORTSERVICE_CONTRACTID, &rv)); - if (NS_FAILED( rv)) - return( rv); - - NS_IF_RELEASE( m_addressImportFolder); - m_addressImportFolder = pRoot; - NS_IF_ADDREF( pRoot); - - - nsString displayName; - nsEudoraStringBundle::GetStringByID( EUDORAIMPORT_NICKNAMES_NAME, displayName); - - // First off, get the default nndbase.txt, then scan the default nicknames subdir, - // then look in the .ini file for additional directories to scan for address books! - rv = spec->AppendRelativeUnixPath( "nndbase.txt"); - PRBool exists = PR_FALSE; - PRBool isFile = PR_FALSE; - if (NS_SUCCEEDED( rv)) - rv = spec->Exists( &exists); - if (NS_SUCCEEDED( rv) && exists) - rv = spec->IsFile( &isFile); - if (exists && isFile) { - if (NS_FAILED( rv = FoundAddressBook( spec, displayName.get(), *ppArray, impSvc))) - return( rv); - } - - // Try the default directory - rv = spec->FromFileSpec( pRoot); - if (NS_FAILED( rv)) - return( rv); - rv = spec->AppendRelativeUnixPath( "Nickname"); - PRBool isDir = PR_FALSE; - exists = PR_FALSE; - if (NS_SUCCEEDED( rv)) - rv = spec->Exists( &exists); - if (NS_SUCCEEDED( rv) && exists) - rv = spec->IsDirectory( &isDir); - if (exists && isDir) { - if (NS_FAILED( rv = ScanAddressDir( spec, *ppArray, impSvc))) - return( rv); - } - - // Try the ini file to find other directories! - rv = spec->FromFileSpec( pRoot); - if (NS_SUCCEEDED( rv)) - rv = spec->AppendRelativeUnixPath( "eudora.ini"); - exists = PR_FALSE; - isFile = PR_FALSE; - if (NS_SUCCEEDED( rv)) - rv = spec->Exists( &exists); - if (NS_SUCCEEDED( rv) && exists) - rv = spec->IsFile( &isFile); - - if (!isFile || !exists) { - rv = spec->FromFileSpec( pRoot); - if (NS_FAILED( rv)) - return( NS_OK); - if (!FindMimeIniFile( spec)) - return( NS_OK); - } - - char *pName = nsnull; - spec->GetNativePath( &pName); - if (!pName) - return( NS_OK); - nsCString fileName(pName); - nsCRT::free( pName); - - // This is the supposed ini file name! - // Get the extra directories for nicknames and parse it for valid nickname directories - // to look into... - char *pBuffer = new char[2048]; - DWORD len = ::GetPrivateProfileString( "Settings", "ExtraNicknameDirs", "", pBuffer, 2048, fileName.get()); - if (len == 2047) { - // If the value is really that large then don't bother! - delete [] pBuffer; - return( NS_OK); - } - nsCString dirs(pBuffer); - delete [] pBuffer; - dirs.Trim( kWhitespace); - PRInt32 idx = 0; - nsCString currentDir; - while ((idx = dirs.FindChar( ';')) != -1) { - dirs.Left( currentDir, idx); - currentDir.Trim( kWhitespace); - if (!currentDir.IsEmpty()) { - rv = spec->SetNativePath( currentDir.get()); - exists = PR_FALSE; - isDir = PR_FALSE; - if (NS_SUCCEEDED( rv)) - rv = spec->Exists( &exists); - if (NS_SUCCEEDED( rv) && exists) - rv = spec->IsDirectory( &isDir); - if (exists && isDir) { - if (NS_FAILED( rv = ScanAddressDir( spec, *ppArray, impSvc))) - return( rv); - } - } - dirs.Right( currentDir, dirs.Length() - idx - 1); - dirs = currentDir; - dirs.Trim( kWhitespace); - } - if (!dirs.IsEmpty()) { - rv = spec->SetNativePath( dirs.get()); - exists = PR_FALSE; - isDir = PR_FALSE; - if (NS_SUCCEEDED( rv)) - rv = spec->Exists( &exists); - if (NS_SUCCEEDED( rv) && exists) - rv = spec->IsDirectory( &isDir); - if (exists && isDir) { - if (NS_FAILED( rv = ScanAddressDir( spec, *ppArray, impSvc))) - return( rv); - } - } - - return( NS_OK); + nsCOMPtr spec; + nsresult rv = NS_NewFileSpec( getter_AddRefs( spec)); + if (NS_FAILED( rv)) + return( rv); + rv = spec->FromFileSpec( pRoot); + if (NS_FAILED( rv)) + return( rv); + + rv = NS_NewISupportsArray( ppArray); + if (NS_FAILED( rv)) { + IMPORT_LOG0( "FAILED to allocate the nsISupportsArray\n"); + return( rv); + } + + nsCOMPtr impSvc(do_GetService(NS_IMPORTSERVICE_CONTRACTID, &rv)); + if (NS_FAILED( rv)) + return( rv); + + NS_IF_RELEASE( m_addressImportFolder); + m_addressImportFolder = pRoot; + NS_IF_ADDREF( pRoot); + + + nsString displayName; + nsEudoraStringBundle::GetStringByID( EUDORAIMPORT_NICKNAMES_NAME, displayName); + + // First off, get the default nndbase.txt, then scan the default nicknames subdir, + // then look in the .ini file for additional directories to scan for address books! + rv = spec->AppendRelativeUnixPath( "nndbase.txt"); + PRBool exists = PR_FALSE; + PRBool isFile = PR_FALSE; + if (NS_SUCCEEDED( rv)) + rv = spec->Exists( &exists); + if (NS_SUCCEEDED( rv) && exists) + rv = spec->IsFile( &isFile); + if (exists && isFile) { + if (NS_FAILED( rv = FoundAddressBook( spec, displayName.get(), *ppArray, impSvc))) + return( rv); + } + + // Try the default directory + rv = spec->FromFileSpec( pRoot); + if (NS_FAILED( rv)) + return( rv); + rv = spec->AppendRelativeUnixPath( "Nickname"); + PRBool isDir = PR_FALSE; + exists = PR_FALSE; + if (NS_SUCCEEDED( rv)) + rv = spec->Exists( &exists); + if (NS_SUCCEEDED( rv) && exists) + rv = spec->IsDirectory( &isDir); + if (exists && isDir) { + if (NS_FAILED( rv = ScanAddressDir( spec, *ppArray, impSvc))) + return( rv); + } + + // Try the ini file to find other directories! + rv = spec->FromFileSpec( pRoot); + if (NS_SUCCEEDED( rv)) + rv = spec->AppendRelativeUnixPath( "eudora.ini"); + exists = PR_FALSE; + isFile = PR_FALSE; + if (NS_SUCCEEDED( rv)) + rv = spec->Exists( &exists); + if (NS_SUCCEEDED( rv) && exists) + rv = spec->IsFile( &isFile); + + if (!isFile || !exists) { + rv = spec->FromFileSpec( pRoot); + if (NS_FAILED( rv)) + return( NS_OK); + if (!FindMimeIniFile( spec)) + return( NS_OK); + } + + char *pName = nsnull; + spec->GetNativePath( &pName); + if (!pName) + return( NS_OK); + nsCString fileName(pName); + nsCRT::free( pName); + + // This is the supposed ini file name! + // Get the extra directories for nicknames and parse it for valid nickname directories + // to look into... + char *pBuffer = new char[2048]; + DWORD len = ::GetPrivateProfileString( "Settings", "ExtraNicknameDirs", "", pBuffer, 2048, fileName.get()); + if (len == 2047) { + // If the value is really that large then don't bother! + delete [] pBuffer; + return( NS_OK); + } + nsCString dirs(pBuffer); + delete [] pBuffer; + dirs.Trim( kWhitespace); + PRInt32 idx = 0; + nsCString currentDir; + while ((idx = dirs.FindChar( ';')) != -1) { + dirs.Left( currentDir, idx); + currentDir.Trim( kWhitespace); + if (!currentDir.IsEmpty()) { + rv = spec->SetNativePath( currentDir.get()); + exists = PR_FALSE; + isDir = PR_FALSE; + if (NS_SUCCEEDED( rv)) + rv = spec->Exists( &exists); + if (NS_SUCCEEDED( rv) && exists) + rv = spec->IsDirectory( &isDir); + if (exists && isDir) { + if (NS_FAILED( rv = ScanAddressDir( spec, *ppArray, impSvc))) + return( rv); + } + } + dirs.Right( currentDir, dirs.Length() - idx - 1); + dirs = currentDir; + dirs.Trim( kWhitespace); + } + if (!dirs.IsEmpty()) { + rv = spec->SetNativePath( dirs.get()); + exists = PR_FALSE; + isDir = PR_FALSE; + if (NS_SUCCEEDED( rv)) + rv = spec->Exists( &exists); + if (NS_SUCCEEDED( rv) && exists) + rv = spec->IsDirectory( &isDir); + if (exists && isDir) { + if (NS_FAILED( rv = ScanAddressDir( spec, *ppArray, impSvc))) + return( rv); + } + } + + return( NS_OK); } nsresult nsEudoraWin32::ScanAddressDir( nsIFileSpec *pDir, nsISupportsArray *pArray, nsIImportService *impSvc) { - nsCOMPtr dir; - nsresult rv = NS_NewDirectoryIterator( getter_AddRefs( dir)); - if (NS_FAILED( rv)) - return( rv); - - PRBool exists = PR_FALSE; - rv = dir->Init( pDir, PR_TRUE); - if (NS_FAILED( rv)) - return( rv); - - rv = dir->Exists( &exists); - if (NS_FAILED( rv)) - return( rv); - - PRBool isFile; - nsCOMPtr entry; - char * pName; - nsCString fName; - nsCString ext; - nsCString name; - - while (exists && NS_SUCCEEDED( rv)) { - rv = dir->GetCurrentSpec( getter_AddRefs( entry)); - if (NS_SUCCEEDED( rv)) { - rv = entry->GetLeafName( &pName); - if (NS_SUCCEEDED( rv) && pName) { - fName = pName; - nsCRT::free( pName); - if (fName.Length() > 4) { - fName.Right( ext, 4); - fName.Left( name, fName.Length() - 4); - } - else { - ext.Truncate(); - name = fName; - } - ToLowerCase(ext); - if (ext.EqualsLiteral(".txt")) { - isFile = PR_FALSE; - entry->IsFile( &isFile); - if (isFile) { - rv = FoundAddressBook( entry, nsnull, pArray, impSvc); - if (NS_FAILED( rv)) - return( rv); - } - } - } - } - - rv = dir->Next(); - if (NS_SUCCEEDED( rv)) - rv = dir->Exists( &exists); - } + nsCOMPtr dir; + nsresult rv = NS_NewDirectoryIterator( getter_AddRefs( dir)); + if (NS_FAILED( rv)) + return( rv); + + PRBool exists = PR_FALSE; + rv = dir->Init( pDir, PR_TRUE); + if (NS_FAILED( rv)) + return( rv); + + rv = dir->Exists( &exists); + if (NS_FAILED( rv)) + return( rv); + + PRBool isFile; + nsCOMPtr entry; + char * pName; + nsCString fName; + nsCString ext; + nsCString name; + + while (exists && NS_SUCCEEDED( rv)) { + rv = dir->GetCurrentSpec( getter_AddRefs( entry)); + if (NS_SUCCEEDED( rv)) { + rv = entry->GetLeafName( &pName); + if (NS_SUCCEEDED( rv) && pName) { + fName = pName; + nsCRT::free( pName); + if (fName.Length() > 4) { + fName.Right( ext, 4); + fName.Left( name, fName.Length() - 4); + } + else { + ext.Truncate(); + name = fName; + } + ToLowerCase(ext); + if (ext.EqualsLiteral(".txt")) { + isFile = PR_FALSE; + entry->IsFile( &isFile); + if (isFile) { + rv = FoundAddressBook( entry, nsnull, pArray, impSvc); + if (NS_FAILED( rv)) + return( rv); + } + } + } + } + + rv = dir->Next(); + if (NS_SUCCEEDED( rv)) + rv = dir->Exists( &exists); + } - return( rv); + return( rv); } nsresult nsEudoraWin32::FoundAddressBook( nsIFileSpec *spec, const PRUnichar *pName, nsISupportsArray *pArray, nsIImportService *impSvc) { - nsCOMPtr desc; - nsISupports * pInterface; - nsString name; - nsresult rv; - - if (pName) - name = pName; - else { - char *pLeaf = nsnull; - rv = spec->GetLeafName( &pLeaf); - if (NS_FAILED( rv)) - return( rv); - if (!pLeaf) - return( NS_ERROR_FAILURE); - NS_CopyNativeToUnicode(nsDependentCString(pLeaf), name); - nsCRT::free( pLeaf); - nsString tStr; - name.Right( tStr, 4); - if (tStr.LowerCaseEqualsLiteral(".txt")) { - name.Left( tStr, name.Length() - 4); - name = tStr; - } - } - - rv = impSvc->CreateNewABDescriptor( getter_AddRefs( desc)); - if (NS_SUCCEEDED( rv)) { - PRUint32 sz = 0; - spec->GetFileSize( &sz); - desc->SetPreferredName( name.get()); - desc->SetSize( sz); - nsIFileSpec *pSpec = nsnull; - desc->GetFileSpec( &pSpec); - if (pSpec) { - pSpec->FromFileSpec( spec); - NS_RELEASE( pSpec); - } - rv = desc->QueryInterface( kISupportsIID, (void **) &pInterface); - pArray->AppendElement( pInterface); - pInterface->Release(); - } - if (NS_FAILED( rv)) { - IMPORT_LOG0( "*** Error creating address book descriptor for eudora\n"); - return( rv); - } + nsCOMPtr desc; + nsISupports * pInterface; + nsString name; + nsresult rv; + + if (pName) + name = pName; + else { + char *pLeaf = nsnull; + rv = spec->GetLeafName( &pLeaf); + if (NS_FAILED( rv)) + return( rv); + if (!pLeaf) + return( NS_ERROR_FAILURE); + NS_CopyNativeToUnicode(nsDependentCString(pLeaf), name); + nsCRT::free( pLeaf); + nsString tStr; + name.Right( tStr, 4); + if (tStr.LowerCaseEqualsLiteral(".txt")) { + name.Left( tStr, name.Length() - 4); + name = tStr; + } + } + + rv = impSvc->CreateNewABDescriptor( getter_AddRefs( desc)); + if (NS_SUCCEEDED( rv)) { + PRUint32 sz = 0; + spec->GetFileSize( &sz); + desc->SetPreferredName( name.get()); + desc->SetSize( sz); + nsIFileSpec *pSpec = nsnull; + desc->GetFileSpec( &pSpec); + if (pSpec) { + pSpec->FromFileSpec( spec); + NS_RELEASE( pSpec); + } + rv = desc->QueryInterface( kISupportsIID, (void **) &pInterface); + pArray->AppendElement( pInterface); + pInterface->Release(); + } + if (NS_FAILED( rv)) { + IMPORT_LOG0( "*** Error creating address book descriptor for eudora\n"); + return( rv); + } - return( NS_OK); + return( NS_OK); } void nsEudoraWin32::ConvertPath( nsCString& str) { - nsCString temp; - nsCString path; - PRInt32 idx = 0; - PRInt32 start = 0; - nsCString search; - - idx = str.FindChar( '\\', idx); - if ((idx == 2) && (str.CharAt( 1) == ':')) { - str.Left( path, 3); - idx++; - idx = str.FindChar( '\\', idx); - start = 3; - if ((idx == -1) && (str.Length() > 3)) { - str.Right( temp, str.Length() - start); - path.Append( temp); - } - } - - WIN32_FIND_DATA findFileData; - while (idx != -1) { - str.Mid( temp, start, idx - start); - search = path; - search.Append( temp); - HANDLE h = FindFirstFile( search.get(), &findFileData); - if (h == INVALID_HANDLE_VALUE) - return; - path.Append( findFileData.cFileName); - idx++; - start = idx; - idx = str.FindChar( '\\', idx); - FindClose( h); - if (idx != -1) - path.Append( '\\'); - else { - str.Right( temp, str.Length() - start); - path.Append( '\\'); - path.Append( temp); - } - } + nsCString temp; + nsCString path; + PRInt32 idx = 0; + PRInt32 start = 0; + nsCString search; + + idx = str.FindChar( '\\', idx); + if ((idx == 2) && (str.CharAt( 1) == ':')) { + str.Left( path, 3); + idx++; + idx = str.FindChar( '\\', idx); + start = 3; + if ((idx == -1) && (str.Length() > 3)) { + str.Right( temp, str.Length() - start); + path.Append( temp); + } + } + + WIN32_FIND_DATA findFileData; + while (idx != -1) { + str.Mid( temp, start, idx - start); + search = path; + search.Append( temp); + HANDLE h = FindFirstFile( search.get(), &findFileData); + if (h == INVALID_HANDLE_VALUE) + return; + path.Append( findFileData.cFileName); + idx++; + start = idx; + idx = str.FindChar( '\\', idx); + FindClose( h); + if (idx != -1) + path.Append( '\\'); + else { + str.Right( temp, str.Length() - start); + path.Append( '\\'); + path.Append( temp); + } + } - str = path; + str = path; } Index: mozilla/mailnews/import/oexpress/nsOESettings.cpp =================================================================== RCS file: /cvsroot/mozilla/mailnews/import/oexpress/nsOESettings.cpp,v retrieving revision 1.31 diff -u -r1.31 mozilla/mailnews/import/oexpress/nsOESettings.cpp --- mozilla/mailnews/import/oexpress/nsOESettings.cpp +++ mozilla/mailnews/import/oexpress/nsOESettings.cpp @@ -1,4 +1,4 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * @@ -65,19 +65,19 @@ class OESettings { public: - static HKEY Find50Key( void); - static HKEY Find40Key( void); - static HKEY FindAccountsKey( void); - - static PRBool DoImport( nsIMsgAccount **ppAccount); - - static PRBool DoIMAPServer( nsIMsgAccountManager *pMgr, HKEY hKey, char *pServerName, nsIMsgAccount **ppAccount); - static PRBool DoPOP3Server( nsIMsgAccountManager *pMgr, HKEY hKey, char *pServerName, nsIMsgAccount **ppAccount); - - static void SetIdentities( nsIMsgAccountManager *pMgr, nsIMsgAccount *pAcc, HKEY hKey); - static PRBool IdentityMatches( nsIMsgIdentity *pIdent, const char *pName, const char *pServer, const char *pEmail, const char *pReply, const char *pUserName); + static HKEY Find50Key( void); + static HKEY Find40Key( void); + static HKEY FindAccountsKey( void); + + static PRBool DoImport( nsIMsgAccount **ppAccount); + + static PRBool DoIMAPServer( nsIMsgAccountManager *pMgr, HKEY hKey, char *pServerName, nsIMsgAccount **ppAccount); + static PRBool DoPOP3Server( nsIMsgAccountManager *pMgr, HKEY hKey, char *pServerName, nsIMsgAccount **ppAccount); + + static void SetIdentities( nsIMsgAccountManager *pMgr, nsIMsgAccount *pAcc, HKEY hKey); + static PRBool IdentityMatches( nsIMsgIdentity *pIdent, const char *pName, const char *pServer, const char *pEmail, const char *pReply, const char *pUserName); - static void SetSmtpServer( nsIMsgAccountManager *pMgr, nsIMsgAccount *pAcc, char *pServer, char *pUser); + static void SetSmtpServer( nsIMsgAccountManager *pMgr, nsIMsgAccount *pAcc, char *pServer, char *pUser); static nsresult GetAccountName(HKEY hKey, char *defaultName, nsString &acctName); }; @@ -111,210 +111,210 @@ { NS_PRECONDITION(description != nsnull, "null ptr"); NS_PRECONDITION(_retval != nsnull, "null ptr"); - if (!description || !_retval) - return( NS_ERROR_NULL_POINTER); - - *description = nsOEStringBundle::GetStringByID( OEIMPORT_NAME); - *_retval = PR_FALSE; - - if (location) - *location = nsnull; - HKEY key; - key = OESettings::Find50Key(); - if (key != nsnull) { - *_retval = PR_TRUE; - ::RegCloseKey( key); - } - else { - key = OESettings::Find40Key(); - if (key != nsnull) { - *_retval = PR_TRUE; - ::RegCloseKey( key); - } - } - if (*_retval) { - key = OESettings::FindAccountsKey(); - if (key == nsnull) { - *_retval = PR_FALSE; - } - else { - ::RegCloseKey( key); - } - } + if (!description || !_retval) + return( NS_ERROR_NULL_POINTER); + + *description = nsOEStringBundle::GetStringByID( OEIMPORT_NAME); + *_retval = PR_FALSE; + + if (location) + *location = nsnull; + HKEY key; + key = OESettings::Find50Key(); + if (key != nsnull) { + *_retval = PR_TRUE; + ::RegCloseKey( key); + } + else { + key = OESettings::Find40Key(); + if (key != nsnull) { + *_retval = PR_TRUE; + ::RegCloseKey( key); + } + } + if (*_retval) { + key = OESettings::FindAccountsKey(); + if (key == nsnull) { + *_retval = PR_FALSE; + } + else { + ::RegCloseKey( key); + } + } - return( NS_OK); + return( NS_OK); } NS_IMETHODIMP nsOESettings::SetLocation(nsIFileSpec *location) { - return( NS_OK); + return( NS_OK); } NS_IMETHODIMP nsOESettings::Import(nsIMsgAccount **localMailAccount, PRBool *_retval) { - NS_PRECONDITION( _retval != nsnull, "null ptr"); - - if (OESettings::DoImport( localMailAccount)) { - *_retval = PR_TRUE; - IMPORT_LOG0( "Settings import appears successful\n"); - } - else { - *_retval = PR_FALSE; - IMPORT_LOG0( "Settings import returned FALSE\n"); - } + NS_PRECONDITION( _retval != nsnull, "null ptr"); + + if (OESettings::DoImport( localMailAccount)) { + *_retval = PR_TRUE; + IMPORT_LOG0( "Settings import appears successful\n"); + } + else { + *_retval = PR_FALSE; + IMPORT_LOG0( "Settings import returned FALSE\n"); + } - return( NS_OK); + return( NS_OK); } HKEY OESettings::FindAccountsKey( void) { - HKEY sKey; - if (::RegOpenKeyEx( HKEY_CURRENT_USER, "Software\\Microsoft\\Internet Account Manager\\Accounts", 0, KEY_QUERY_VALUE | KEY_ENUMERATE_SUB_KEYS, &sKey) == ERROR_SUCCESS) { - return( sKey); - } + HKEY sKey; + if (::RegOpenKeyEx( HKEY_CURRENT_USER, "Software\\Microsoft\\Internet Account Manager\\Accounts", 0, KEY_QUERY_VALUE | KEY_ENUMERATE_SUB_KEYS, &sKey) == ERROR_SUCCESS) { + return( sKey); + } - return( nsnull); + return( nsnull); } HKEY OESettings::Find50Key( void) { - PRBool success = PR_FALSE; - HKEY sKey; + PRBool success = PR_FALSE; + HKEY sKey; - if (::RegOpenKeyEx( HKEY_CURRENT_USER, "Identities", 0, KEY_QUERY_VALUE, &sKey) == ERROR_SUCCESS) { - BYTE * pBytes = nsOERegUtil::GetValueBytes( sKey, "Default User ID"); - ::RegCloseKey( sKey); - if (pBytes) { - nsCString key( "Identities\\"); - key += (const char *)pBytes; - nsOERegUtil::FreeValueBytes( pBytes); - key += "\\Software\\Microsoft\\Outlook Express\\5.0"; - if (::RegOpenKeyEx( HKEY_CURRENT_USER, key.get(), 0, KEY_QUERY_VALUE, &sKey) == ERROR_SUCCESS) { - return( sKey); - } - } - } + if (::RegOpenKeyEx( HKEY_CURRENT_USER, "Identities", 0, KEY_QUERY_VALUE, &sKey) == ERROR_SUCCESS) { + BYTE * pBytes = nsOERegUtil::GetValueBytes( sKey, "Default User ID"); + ::RegCloseKey( sKey); + if (pBytes) { + nsCString key( "Identities\\"); + key += (const char *)pBytes; + nsOERegUtil::FreeValueBytes( pBytes); + key += "\\Software\\Microsoft\\Outlook Express\\5.0"; + if (::RegOpenKeyEx( HKEY_CURRENT_USER, key.get(), 0, KEY_QUERY_VALUE, &sKey) == ERROR_SUCCESS) { + return( sKey); + } + } + } - return( nsnull); + return( nsnull); } HKEY OESettings::Find40Key( void) { - HKEY sKey; - if (::RegOpenKeyEx( HKEY_CURRENT_USER, "Software\\Microsoft\\Outlook Express", 0, KEY_QUERY_VALUE, &sKey) == ERROR_SUCCESS) { - return( sKey); - } + HKEY sKey; + if (::RegOpenKeyEx( HKEY_CURRENT_USER, "Software\\Microsoft\\Outlook Express", 0, KEY_QUERY_VALUE, &sKey) == ERROR_SUCCESS) { + return( sKey); + } - return( nsnull); + return( nsnull); } PRBool OESettings::DoImport( nsIMsgAccount **ppAccount) { - HKEY hKey = FindAccountsKey(); - if (hKey == nsnull) { - IMPORT_LOG0( "*** Error finding Outlook Express registry account keys\n"); - return( PR_FALSE); - } - - nsresult rv; - - nsCOMPtr accMgr = - do_GetService(NS_MSGACCOUNTMANAGER_CONTRACTID, &rv); + HKEY hKey = FindAccountsKey(); + if (hKey == nsnull) { + IMPORT_LOG0( "*** Error finding Outlook Express registry account keys\n"); + return( PR_FALSE); + } + + nsresult rv; + + nsCOMPtr accMgr = + do_GetService(NS_MSGACCOUNTMANAGER_CONTRACTID, &rv); if (NS_FAILED(rv)) { - IMPORT_LOG0( "*** Failed to create a account manager!\n"); - return( PR_FALSE); - } - - HKEY subKey; - nsCString defMailName; - - // First let's get the default mail account key name - if (::RegOpenKeyEx( HKEY_CURRENT_USER, "Software\\Microsoft\\Outlook Express", 0, KEY_QUERY_VALUE, &subKey) == ERROR_SUCCESS) { - BYTE * pBytes = nsOERegUtil::GetValueBytes( subKey, "Default Mail Account"); - ::RegCloseKey( subKey); - if (pBytes) { - defMailName = (const char *)pBytes; - nsOERegUtil::FreeValueBytes( pBytes); - } - } - - // Iterate the accounts looking for POP3 & IMAP accounts... - // Ignore LDAP & NNTP for now! - DWORD index = 0; - DWORD numChars; - TCHAR keyName[256]; - FILETIME modTime; - LONG result = ERROR_SUCCESS; - BYTE * pBytes; - int popCount = 0; - int accounts = 0; - nsCString keyComp; - - while (result == ERROR_SUCCESS) { - numChars = 256; - result = ::RegEnumKeyEx( hKey, index, keyName, &numChars, NULL, NULL, NULL, &modTime); - index++; - if (result == ERROR_SUCCESS) { - if (::RegOpenKeyEx( hKey, keyName, 0, KEY_QUERY_VALUE, &subKey) == ERROR_SUCCESS) { - // Get the values for this account. - IMPORT_LOG1( "Opened Outlook Express account: %s\n", (char *)keyName); - - nsIMsgAccount *anAccount = nsnull; - pBytes = nsOERegUtil::GetValueBytes( subKey, "IMAP Server"); - if (pBytes) { - if (DoIMAPServer( accMgr, subKey, (char *)pBytes, &anAccount)) - accounts++; - nsOERegUtil::FreeValueBytes( pBytes); - } - - pBytes = nsOERegUtil::GetValueBytes( subKey, "POP3 Server"); - if (pBytes) { - if (popCount == 0) { - if (DoPOP3Server( accMgr, subKey, (char *)pBytes, &anAccount)) { - popCount++; - accounts++; - if (ppAccount && anAccount) { - *ppAccount = anAccount; - NS_ADDREF( anAccount); - } - } - } - else { - if (DoPOP3Server( accMgr, subKey, (char *)pBytes, &anAccount)) { - popCount++; - accounts++; - // If we created a mail account, get rid of it since - // we have 2 POP accounts! - if (ppAccount && *ppAccount) { - NS_RELEASE( *ppAccount); - *ppAccount = nsnull; - } - } - } - nsOERegUtil::FreeValueBytes( pBytes); - } - - if (anAccount) { - // Is this the default account? - keyComp = keyName; - if (keyComp.Equals( defMailName)) { - accMgr->SetDefaultAccount( anAccount); - } - NS_RELEASE( anAccount); - } - - ::RegCloseKey( subKey); - } - } - } - - // Now save the new acct info to pref file. - rv = accMgr->SaveAccountInfo(); - NS_ASSERTION(NS_SUCCEEDED(rv), "Can't save account info to pref file"); + IMPORT_LOG0( "*** Failed to create a account manager!\n"); + return( PR_FALSE); + } + + HKEY subKey; + nsCString defMailName; + + // First let's get the default mail account key name + if (::RegOpenKeyEx( HKEY_CURRENT_USER, "Software\\Microsoft\\Outlook Express", 0, KEY_QUERY_VALUE, &subKey) == ERROR_SUCCESS) { + BYTE * pBytes = nsOERegUtil::GetValueBytes( subKey, "Default Mail Account"); + ::RegCloseKey( subKey); + if (pBytes) { + defMailName = (const char *)pBytes; + nsOERegUtil::FreeValueBytes( pBytes); + } + } + + // Iterate the accounts looking for POP3 & IMAP accounts... + // Ignore LDAP & NNTP for now! + DWORD index = 0; + DWORD numChars; + TCHAR keyName[256]; + FILETIME modTime; + LONG result = ERROR_SUCCESS; + BYTE * pBytes; + int popCount = 0; + int accounts = 0; + nsCString keyComp; + + while (result == ERROR_SUCCESS) { + numChars = 256; + result = ::RegEnumKeyEx( hKey, index, keyName, &numChars, NULL, NULL, NULL, &modTime); + index++; + if (result == ERROR_SUCCESS) { + if (::RegOpenKeyEx( hKey, keyName, 0, KEY_QUERY_VALUE, &subKey) == ERROR_SUCCESS) { + // Get the values for this account. + IMPORT_LOG1( "Opened Outlook Express account: %s\n", (char *)keyName); + + nsIMsgAccount *anAccount = nsnull; + pBytes = nsOERegUtil::GetValueBytes( subKey, "IMAP Server"); + if (pBytes) { + if (DoIMAPServer( accMgr, subKey, (char *)pBytes, &anAccount)) + accounts++; + nsOERegUtil::FreeValueBytes( pBytes); + } + + pBytes = nsOERegUtil::GetValueBytes( subKey, "POP3 Server"); + if (pBytes) { + if (popCount == 0) { + if (DoPOP3Server( accMgr, subKey, (char *)pBytes, &anAccount)) { + popCount++; + accounts++; + if (ppAccount && anAccount) { + *ppAccount = anAccount; + NS_ADDREF( anAccount); + } + } + } + else { + if (DoPOP3Server( accMgr, subKey, (char *)pBytes, &anAccount)) { + popCount++; + accounts++; + // If we created a mail account, get rid of it since + // we have 2 POP accounts! + if (ppAccount && *ppAccount) { + NS_RELEASE( *ppAccount); + *ppAccount = nsnull; + } + } + } + nsOERegUtil::FreeValueBytes( pBytes); + } + + if (anAccount) { + // Is this the default account? + keyComp = keyName; + if (keyComp.Equals( defMailName)) { + accMgr->SetDefaultAccount( anAccount); + } + NS_RELEASE( anAccount); + } + + ::RegCloseKey( subKey); + } + } + } - return( accounts != 0); + // Now save the new acct info to pref file. + rv = accMgr->SaveAccountInfo(); + NS_ASSERTION(NS_SUCCEEDED(rv), "Can't save account info to pref file"); + + return( accounts != 0); } nsresult OESettings::GetAccountName(HKEY hKey, char *defaultName, nsString &acctName) @@ -334,86 +334,86 @@ PRBool OESettings::DoIMAPServer( nsIMsgAccountManager *pMgr, HKEY hKey, char *pServerName, nsIMsgAccount **ppAccount) { - if (ppAccount) - *ppAccount = nsnull; + if (ppAccount) + *ppAccount = nsnull; - BYTE *pBytes; - pBytes = nsOERegUtil::GetValueBytes( hKey, "IMAP User Name"); - if (!pBytes) - return( PR_FALSE); - - PRBool result = PR_FALSE; - - // I now have a user name/server name pair, find out if it already exists? - nsCOMPtr in; - nsresult rv = pMgr->FindServer( (const char *)pBytes, pServerName, "imap", getter_AddRefs( in)); - if (NS_FAILED( rv) || (in == nsnull)) { - // Create the incoming server and an account for it? - rv = pMgr->CreateIncomingServer( (const char *)pBytes, pServerName, "imap", getter_AddRefs( in)); - if (NS_SUCCEEDED( rv) && in) { - rv = in->SetType( "imap"); - // rv = in->SetHostName( pServerName); - // rv = in->SetUsername( (char *)pBytes); - - IMPORT_LOG2( "Created IMAP server named: %s, userName: %s\n", pServerName, (char *)pBytes); + BYTE *pBytes; + pBytes = nsOERegUtil::GetValueBytes( hKey, "IMAP User Name"); + if (!pBytes) + return( PR_FALSE); + + PRBool result = PR_FALSE; + + // I now have a user name/server name pair, find out if it already exists? + nsCOMPtr in; + nsresult rv = pMgr->FindServer( (const char *)pBytes, pServerName, "imap", getter_AddRefs( in)); + if (NS_FAILED( rv) || (in == nsnull)) { + // Create the incoming server and an account for it? + rv = pMgr->CreateIncomingServer( (const char *)pBytes, pServerName, "imap", getter_AddRefs( in)); + if (NS_SUCCEEDED( rv) && in) { + rv = in->SetType( "imap"); + // rv = in->SetHostName( pServerName); + // rv = in->SetUsername( (char *)pBytes); + + IMPORT_LOG2( "Created IMAP server named: %s, userName: %s\n", pServerName, (char *)pBytes); - nsString prettyName; + nsString prettyName; if (NS_SUCCEEDED(GetAccountName(hKey, pServerName, prettyName))) { - PRUnichar *pretty = ToNewUnicode(prettyName); + PRUnichar *pretty = ToNewUnicode(prettyName); if (pretty) { - rv = in->SetPrettyName( pretty); - nsCRT::free( pretty); + rv = in->SetPrettyName( pretty); + nsCRT::free( pretty); } } - - // We have a server, create an account. - nsCOMPtr account; - rv = pMgr->CreateAccount( getter_AddRefs( account)); - if (NS_SUCCEEDED( rv) && account) { - rv = account->SetIncomingServer( in); - - IMPORT_LOG0( "Created an account and set the IMAP server as the incoming server\n"); - - // Fiddle with the identities - SetIdentities( pMgr, account, hKey); - result = PR_TRUE; - if (ppAccount) - account->QueryInterface( NS_GET_IID(nsIMsgAccount), (void **)ppAccount); - } - } - } - else - result = PR_TRUE; - - nsOERegUtil::FreeValueBytes( pBytes); + + // We have a server, create an account. + nsCOMPtr account; + rv = pMgr->CreateAccount( getter_AddRefs( account)); + if (NS_SUCCEEDED( rv) && account) { + rv = account->SetIncomingServer( in); + + IMPORT_LOG0( "Created an account and set the IMAP server as the incoming server\n"); + + // Fiddle with the identities + SetIdentities( pMgr, account, hKey); + result = PR_TRUE; + if (ppAccount) + CallQueryInterface(account, ppAccount); + } + } + } + else + result = PR_TRUE; + + nsOERegUtil::FreeValueBytes( pBytes); - return( result); + return( result); } PRBool OESettings::DoPOP3Server( nsIMsgAccountManager *pMgr, HKEY hKey, char *pServerName, nsIMsgAccount **ppAccount) { - if (ppAccount) - *ppAccount = nsnull; + if (ppAccount) + *ppAccount = nsnull; - BYTE *pBytes; - pBytes = nsOERegUtil::GetValueBytes( hKey, "POP3 User Name"); - if (!pBytes) - return( PR_FALSE); - - PRBool result = PR_FALSE; - - // I now have a user name/server name pair, find out if it already exists? - nsCOMPtr in; - nsresult rv = pMgr->FindServer( (const char *)pBytes, pServerName, "pop3", getter_AddRefs( in)); - if (NS_FAILED( rv) || (in == nsnull)) { - // Create the incoming server and an account for it? - rv = pMgr->CreateIncomingServer( (const char *)pBytes, pServerName, "pop3", getter_AddRefs( in)); - if (NS_SUCCEEDED( rv) && in) { - rv = in->SetType( "pop3"); - rv = in->SetHostName( pServerName); - rv = in->SetUsername( (char *)pBytes); + BYTE *pBytes; + pBytes = nsOERegUtil::GetValueBytes( hKey, "POP3 User Name"); + if (!pBytes) + return( PR_FALSE); + + PRBool result = PR_FALSE; + + // I now have a user name/server name pair, find out if it already exists? + nsCOMPtr in; + nsresult rv = pMgr->FindServer( (const char *)pBytes, pServerName, "pop3", getter_AddRefs( in)); + if (NS_FAILED( rv) || (in == nsnull)) { + // Create the incoming server and an account for it? + rv = pMgr->CreateIncomingServer( (const char *)pBytes, pServerName, "pop3", getter_AddRefs( in)); + if (NS_SUCCEEDED( rv) && in) { + rv = in->SetType( "pop3"); + rv = in->SetHostName( pServerName); + rv = in->SetUsername( (char *)pBytes); nsCOMPtr pop3Server = do_QueryInterface(in); if (pop3Server) { @@ -454,26 +454,26 @@ } } - IMPORT_LOG2( "Created POP3 server named: %s, userName: %s\n", pServerName, (char *)pBytes); + IMPORT_LOG2( "Created POP3 server named: %s, userName: %s\n", pServerName, (char *)pBytes); - nsString prettyName; + nsString prettyName; if (NS_SUCCEEDED(GetAccountName(hKey, pServerName, prettyName))) { - PRUnichar *pretty = ToNewUnicode(prettyName); + PRUnichar *pretty = ToNewUnicode(prettyName); if (pretty) { - rv = in->SetPrettyName( pretty); - nsCRT::free( pretty); + rv = in->SetPrettyName( pretty); + nsCRT::free( pretty); } } - - // We have a server, create an account. - nsCOMPtr account; - rv = pMgr->CreateAccount( getter_AddRefs( account)); - if (NS_SUCCEEDED( rv) && account) { - rv = account->SetIncomingServer( in); - IMPORT_LOG0( "Created a new account and set the incoming server to the POP3 server.\n"); - + + // We have a server, create an account. + nsCOMPtr account; + rv = pMgr->CreateAccount( getter_AddRefs( account)); + if (NS_SUCCEEDED( rv) && account) { + rv = account->SetIncomingServer( in); + IMPORT_LOG0( "Created a new account and set the incoming server to the POP3 server.\n"); + nsCOMPtr pop3Server = do_QueryInterface(in, &rv); NS_ENSURE_SUCCESS(rv,rv); BYTE *pLeaveOnServer = nsOERegUtil::GetValueBytes( hKey, "Leave Mail On Server"); @@ -484,84 +484,84 @@ } // Fiddle with the identities - SetIdentities( pMgr, account, hKey); - result = PR_TRUE; - if (ppAccount) - account->QueryInterface( NS_GET_IID(nsIMsgAccount), (void **)ppAccount); - } - } - } - else - result = PR_TRUE; - - nsOERegUtil::FreeValueBytes( pBytes); + SetIdentities( pMgr, account, hKey); + result = PR_TRUE; + if (ppAccount) + CallQueryInterface(account, ppAccount); + } + } + } + else + result = PR_TRUE; + + nsOERegUtil::FreeValueBytes( pBytes); - return( result); + return( result); } PRBool OESettings::IdentityMatches( nsIMsgIdentity *pIdent, const char *pName, const char *pServer, const char *pEmail, const char *pReply, const char *pUserName) { - if (!pIdent) - return( PR_FALSE); + if (!pIdent) + return( PR_FALSE); + + char * pIName = nsnull; + char * pIEmail = nsnull; + char * pIReply = nsnull; + + PRBool result = PR_TRUE; + + // The test here is: + // If the smtp host is the same + // and the email address is the same (if it is supplied) + // and the reply to address is the same (if it is supplied) + // then we match regardless of the full name. + PRUnichar * ppIName = nsnull; + + nsresult rv = pIdent->GetFullName( &ppIName); + rv = pIdent->GetEmail( &pIEmail); + rv = pIdent->GetReplyTo( &pIReply); + if (ppIName) { + nsString name(ppIName); + nsCRT::free( ppIName); + pIName = ToNewCString(name); + } - char * pIName = nsnull; - char * pIEmail = nsnull; - char * pIReply = nsnull; - - PRBool result = PR_TRUE; - - // The test here is: - // If the smtp host is the same - // and the email address is the same (if it is supplied) - // and the reply to address is the same (if it is supplied) - // then we match regardless of the full name. - PRUnichar * ppIName = nsnull; - - nsresult rv = pIdent->GetFullName( &ppIName); - rv = pIdent->GetEmail( &pIEmail); - rv = pIdent->GetReplyTo( &pIReply); - if (ppIName) { - nsString name(ppIName); - nsCRT::free( ppIName); - pIName = ToNewCString(name); - } - - // for now, if it's the same server and reply to and email then it matches - if (pReply) { - if (!pIReply || nsCRT::strcasecmp( pReply, pIReply)) - result = PR_FALSE; - } - if (pEmail) { - if (!pIEmail || nsCRT::strcasecmp( pEmail, pIEmail)) - result = PR_FALSE; - } - - nsCRT::free( pIName); - nsCRT::free( pIEmail); - nsCRT::free( pIReply); + // for now, if it's the same server and reply to and email then it matches + if (pReply) { + if (!pIReply || nsCRT::strcasecmp( pReply, pIReply)) + result = PR_FALSE; + } + if (pEmail) { + if (!pIEmail || nsCRT::strcasecmp( pEmail, pIEmail)) + result = PR_FALSE; + } + + nsCRT::free( pIName); + nsCRT::free( pIEmail); + nsCRT::free( pIReply); - return( result); + return( result); } void OESettings::SetIdentities( nsIMsgAccountManager *pMgr, nsIMsgAccount *pAcc, HKEY hKey) { - // Get the relevant information for an identity - char *pName = (char *)nsOERegUtil::GetValueBytes( hKey, "SMTP Display Name"); - char *pServer = (char *)nsOERegUtil::GetValueBytes( hKey, "SMTP Server"); - char *pEmail = (char *)nsOERegUtil::GetValueBytes( hKey, "SMTP Email Address"); - char *pReply = (char *)nsOERegUtil::GetValueBytes( hKey, "SMTP Reply To Email Address"); - char *pUserName = (char *)nsOERegUtil::GetValueBytes( hKey, "SMTP User Name"); + // Get the relevant information for an identity + char *pName = (char *)nsOERegUtil::GetValueBytes( hKey, "SMTP Display Name"); + char *pServer = (char *)nsOERegUtil::GetValueBytes( hKey, "SMTP Server"); + char *pEmail = (char *)nsOERegUtil::GetValueBytes( hKey, "SMTP Email Address"); + char *pReply = (char *)nsOERegUtil::GetValueBytes( hKey, "SMTP Reply To Email Address"); + char *pUserName = (char *)nsOERegUtil::GetValueBytes( hKey, "SMTP User Name"); char *pOrgName = (char *)nsOERegUtil::GetValueBytes( hKey, "SMTP Organization Name"); - nsresult rv; + nsresult rv; - if (pEmail && pName && pServer) { - // The default identity, nor any other identities matched, - // create a new one and add it to the account. - nsCOMPtr id; - rv = pMgr->CreateIdentity( getter_AddRefs( id)); - if (id) { + if (pEmail && pName && pServer) { + // The default identity, nor any other identities matched, + // create a new one and add it to the account. + nsCOMPtr id; + rv = pMgr->CreateIdentity( getter_AddRefs( id)); + if (id) { nsAutoString fullName, organization; nsCOMPtr impSvc = do_GetService(NS_IMPORTSERVICE_CONTRACTID); if (impSvc) @@ -569,75 +569,75 @@ rv = impSvc->SystemStringToUnicode((const char *)pName, fullName); if (NS_SUCCEEDED(rv)) { - id->SetFullName( fullName.get()); - id->SetIdentityName( fullName.get()); + id->SetFullName( fullName.get()); + id->SetIdentityName( fullName.get()); } rv = impSvc->SystemStringToUnicode((const char *)pOrgName, organization); if (NS_SUCCEEDED(rv)) id->SetOrganization( organization.get()); } - id->SetEmail( pEmail); - if (pReply) - id->SetReplyTo( pReply); + id->SetEmail( pEmail); + if (pReply) + id->SetReplyTo( pReply); // Outlook Express users are used to top style quoting. id->SetReplyOnTop(1); - pAcc->AddIdentity( id); + pAcc->AddIdentity( id); - IMPORT_LOG0( "Created identity and added to the account\n"); - IMPORT_LOG1( "\tname: %s\n", pName); - IMPORT_LOG1( "\temail: %s\n", pEmail); - } - } + IMPORT_LOG0( "Created identity and added to the account\n"); + IMPORT_LOG1( "\tname: %s\n", pName); + IMPORT_LOG1( "\temail: %s\n", pEmail); + } + } if (!pUserName) { - nsCOMPtr incomingServer; + nsCOMPtr incomingServer; rv = pAcc->GetIncomingServer(getter_AddRefs( incomingServer)); if (NS_SUCCEEDED(rv) && incomingServer) rv = incomingServer->GetUsername(&pUserName); NS_ASSERTION(NS_SUCCEEDED(rv), "Unable to get UserName from incomingServer"); } - SetSmtpServer( pMgr, pAcc, pServer, pUserName); + SetSmtpServer( pMgr, pAcc, pServer, pUserName); - nsOERegUtil::FreeValueBytes( (BYTE *)pName); - nsOERegUtil::FreeValueBytes( (BYTE *)pServer); - nsOERegUtil::FreeValueBytes( (BYTE *)pEmail); - nsOERegUtil::FreeValueBytes( (BYTE *)pReply); - nsOERegUtil::FreeValueBytes( (BYTE *)pUserName); + nsOERegUtil::FreeValueBytes( (BYTE *)pName); + nsOERegUtil::FreeValueBytes( (BYTE *)pServer); + nsOERegUtil::FreeValueBytes( (BYTE *)pEmail); + nsOERegUtil::FreeValueBytes( (BYTE *)pReply); + nsOERegUtil::FreeValueBytes( (BYTE *)pUserName); } void OESettings::SetSmtpServer( nsIMsgAccountManager *pMgr, nsIMsgAccount *pAcc, char *pServer, char *pUser) { - nsresult rv; + nsresult rv; - nsCOMPtr smtpService(do_GetService(NS_SMTPSERVICE_CONTRACTID, &rv)); - if (NS_SUCCEEDED(rv) && smtpService) { - nsCOMPtr foundServer; - - rv = smtpService->FindServer( pUser, pServer, getter_AddRefs( foundServer)); - if (NS_SUCCEEDED( rv) && foundServer) { - IMPORT_LOG1( "SMTP server already exists: %s\n", pServer); - return; - } - nsCOMPtr smtpServer; - - rv = smtpService->CreateSmtpServer( getter_AddRefs( smtpServer)); - if (NS_SUCCEEDED( rv) && smtpServer) { - smtpServer->SetHostname( pServer); - if (pUser) - smtpServer->SetUsername( pUser); - - IMPORT_LOG1( "Created new SMTP server: %s\n", pServer); - } - } + nsCOMPtr smtpService(do_GetService(NS_SMTPSERVICE_CONTRACTID, &rv)); + if (NS_SUCCEEDED(rv) && smtpService) { + nsCOMPtr foundServer; + + rv = smtpService->FindServer( pUser, pServer, getter_AddRefs( foundServer)); + if (NS_SUCCEEDED( rv) && foundServer) { + IMPORT_LOG1( "SMTP server already exists: %s\n", pServer); + return; + } + nsCOMPtr smtpServer; + + rv = smtpService->CreateSmtpServer( getter_AddRefs( smtpServer)); + if (NS_SUCCEEDED( rv) && smtpServer) { + smtpServer->SetHostname( pServer); + if (pUser) + smtpServer->SetUsername( pUser); + + IMPORT_LOG1( "Created new SMTP server: %s\n", pServer); + } + } /* - nsXPIDLCString hostName; - nsXPIDLCString senderName; - smtpServer->GetHostname( getter_Copies(hostName)); - smtpServer->GetUsername( getter_Copies(senderName)); - */ + nsXPIDLCString hostName; + nsXPIDLCString senderName; + smtpServer->GetHostname( getter_Copies(hostName)); + smtpServer->GetUsername( getter_Copies(senderName)); + */ } Index: mozilla/mailnews/import/outlook/src/nsOutlookSettings.cpp =================================================================== RCS file: /cvsroot/mozilla/mailnews/import/outlook/src/nsOutlookSettings.cpp,v retrieving revision 1.27 diff -u -r1.27 mozilla/mailnews/import/outlook/src/nsOutlookSettings.cpp --- mozilla/mailnews/import/outlook/src/nsOutlookSettings.cpp +++ mozilla/mailnews/import/outlook/src/nsOutlookSettings.cpp @@ -1,4 +1,4 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * @@ -65,17 +65,17 @@ class OutlookSettings { public: - static HKEY FindAccountsKey( void); + static HKEY FindAccountsKey( void); - static PRBool DoImport( nsIMsgAccount **ppAccount); + static PRBool DoImport( nsIMsgAccount **ppAccount); - static PRBool DoIMAPServer( nsIMsgAccountManager *pMgr, HKEY hKey, char *pServerName, nsIMsgAccount **ppAccount); - static PRBool DoPOP3Server( nsIMsgAccountManager *pMgr, HKEY hKey, char *pServerName, nsIMsgAccount **ppAccount); - - static void SetIdentities( nsIMsgAccountManager *pMgr, nsIMsgAccount *pAcc, HKEY hKey); - static PRBool IdentityMatches( nsIMsgIdentity *pIdent, const char *pName, const char *pServer, const char *pEmail, const char *pReply, const char *pUserName); + static PRBool DoIMAPServer( nsIMsgAccountManager *pMgr, HKEY hKey, char *pServerName, nsIMsgAccount **ppAccount); + static PRBool DoPOP3Server( nsIMsgAccountManager *pMgr, HKEY hKey, char *pServerName, nsIMsgAccount **ppAccount); + + static void SetIdentities( nsIMsgAccountManager *pMgr, nsIMsgAccount *pAcc, HKEY hKey); + static PRBool IdentityMatches( nsIMsgIdentity *pIdent, const char *pName, const char *pServer, const char *pEmail, const char *pReply, const char *pUserName); - static void SetSmtpServer( nsIMsgAccountManager *pMgr, nsIMsgAccount *pAcc, char *pServer, char *pUser); + static void SetSmtpServer( nsIMsgAccountManager *pMgr, nsIMsgAccount *pAcc, char *pServer, char *pUser); static nsresult GetAccountName(HKEY hKey, char *defaultName, nsString &acctName); }; @@ -109,169 +109,169 @@ { NS_PRECONDITION(description != nsnull, "null ptr"); NS_PRECONDITION(_retval != nsnull, "null ptr"); - if (!description || !_retval) - return( NS_ERROR_NULL_POINTER); - - *description = nsOutlookStringBundle::GetStringByID( OUTLOOKIMPORT_NAME); - *_retval = PR_FALSE; - - if (location) - *location = nsnull; - - // look for the registry key for the accounts - HKEY key = OutlookSettings::FindAccountsKey(); - if (key != nsnull) { - *_retval = PR_TRUE; - ::RegCloseKey( key); - } + if (!description || !_retval) + return( NS_ERROR_NULL_POINTER); + + *description = nsOutlookStringBundle::GetStringByID( OUTLOOKIMPORT_NAME); + *_retval = PR_FALSE; + + if (location) + *location = nsnull; + + // look for the registry key for the accounts + HKEY key = OutlookSettings::FindAccountsKey(); + if (key != nsnull) { + *_retval = PR_TRUE; + ::RegCloseKey( key); + } - return( NS_OK); + return( NS_OK); } NS_IMETHODIMP nsOutlookSettings::SetLocation(nsIFileSpec *location) { - return( NS_OK); + return( NS_OK); } NS_IMETHODIMP nsOutlookSettings::Import(nsIMsgAccount **localMailAccount, PRBool *_retval) { - NS_PRECONDITION( _retval != nsnull, "null ptr"); - - if (OutlookSettings::DoImport( localMailAccount)) { - *_retval = PR_TRUE; - IMPORT_LOG0( "Settings import appears successful\n"); - } - else { - *_retval = PR_FALSE; - IMPORT_LOG0( "Settings import returned FALSE\n"); - } + NS_PRECONDITION( _retval != nsnull, "null ptr"); + + if (OutlookSettings::DoImport( localMailAccount)) { + *_retval = PR_TRUE; + IMPORT_LOG0( "Settings import appears successful\n"); + } + else { + *_retval = PR_FALSE; + IMPORT_LOG0( "Settings import returned FALSE\n"); + } - return( NS_OK); + return( NS_OK); } HKEY OutlookSettings::FindAccountsKey( void) { - HKEY sKey; - if (::RegOpenKeyEx( HKEY_CURRENT_USER, "Software\\Microsoft\\Office\\Outlook\\OMI Account Manager\\Accounts", 0, KEY_QUERY_VALUE | KEY_ENUMERATE_SUB_KEYS, &sKey) == ERROR_SUCCESS) { - return( sKey); - } - if (::RegOpenKeyEx( HKEY_CURRENT_USER, "Software\\Microsoft\\Office\\8.0\\Outlook\\OMI Account Manager\\Accounts", 0, KEY_QUERY_VALUE | KEY_ENUMERATE_SUB_KEYS, &sKey) == ERROR_SUCCESS) { - return( sKey); - } + HKEY sKey; + if (::RegOpenKeyEx( HKEY_CURRENT_USER, "Software\\Microsoft\\Office\\Outlook\\OMI Account Manager\\Accounts", 0, KEY_QUERY_VALUE | KEY_ENUMERATE_SUB_KEYS, &sKey) == ERROR_SUCCESS) { + return( sKey); + } + if (::RegOpenKeyEx( HKEY_CURRENT_USER, "Software\\Microsoft\\Office\\8.0\\Outlook\\OMI Account Manager\\Accounts", 0, KEY_QUERY_VALUE | KEY_ENUMERATE_SUB_KEYS, &sKey) == ERROR_SUCCESS) { + return( sKey); + } - return( nsnull); + return( nsnull); } PRBool OutlookSettings::DoImport( nsIMsgAccount **ppAccount) { - HKEY hKey = FindAccountsKey(); - if (hKey == nsnull) { - IMPORT_LOG0( "*** Error finding Outlook registry account keys\n"); - return( PR_FALSE); - } - - nsresult rv; - - nsCOMPtr accMgr = - do_GetService(NS_MSGACCOUNTMANAGER_CONTRACTID, &rv); + HKEY hKey = FindAccountsKey(); + if (hKey == nsnull) { + IMPORT_LOG0( "*** Error finding Outlook registry account keys\n"); + return( PR_FALSE); + } + + nsresult rv; + + nsCOMPtr accMgr = + do_GetService(NS_MSGACCOUNTMANAGER_CONTRACTID, &rv); if (NS_FAILED(rv)) { - IMPORT_LOG0( "*** Failed to create a account manager!\n"); - return( PR_FALSE); - } - - HKEY subKey = NULL; - nsCString defMailName; - - if (::RegOpenKeyEx( HKEY_CURRENT_USER, "Software\\Microsoft\\Office\\Outlook\\OMI Account Manager", 0, KEY_QUERY_VALUE, &subKey) != ERROR_SUCCESS) - if (::RegOpenKeyEx( HKEY_CURRENT_USER, "Software\\Microsoft\\Office\\8.0\\Outlook\\OMI Account Manager", 0, KEY_QUERY_VALUE, &subKey) != ERROR_SUCCESS) - subKey = NULL; - - if (subKey != NULL) { - // First let's get the default mail account key name - BYTE * pBytes = nsOutlookRegUtil::GetValueBytes( subKey, "Default Mail Account"); - ::RegCloseKey( subKey); - if (pBytes) { - defMailName = (const char *)pBytes; - nsOutlookRegUtil::FreeValueBytes( pBytes); - } - } - - // Iterate the accounts looking for POP3 & IMAP accounts... - // Ignore LDAP & NNTP for now! - DWORD index = 0; - DWORD numChars; - TCHAR keyName[256]; - FILETIME modTime; - LONG result = ERROR_SUCCESS; - BYTE * pBytes; - int popCount = 0; - int accounts = 0; - nsCString keyComp; - - while (result == ERROR_SUCCESS) { - numChars = 256; - result = ::RegEnumKeyEx( hKey, index, keyName, &numChars, NULL, NULL, NULL, &modTime); - index++; - if (result == ERROR_SUCCESS) { - if (::RegOpenKeyEx( hKey, keyName, 0, KEY_QUERY_VALUE, &subKey) == ERROR_SUCCESS) { - // Get the values for this account. - IMPORT_LOG1( "Opened Outlook account: %s\n", (char *)keyName); - - nsIMsgAccount *anAccount = nsnull; - pBytes = nsOutlookRegUtil::GetValueBytes( subKey, "IMAP Server"); - if (pBytes) { - if (DoIMAPServer( accMgr, subKey, (char *)pBytes, &anAccount)) - accounts++; - nsOutlookRegUtil::FreeValueBytes( pBytes); - } - - pBytes = nsOutlookRegUtil::GetValueBytes( subKey, "POP3 Server"); - if (pBytes) { - if (popCount == 0) { - if (DoPOP3Server( accMgr, subKey, (char *)pBytes, &anAccount)) { - popCount++; - accounts++; - if (ppAccount && anAccount) { - *ppAccount = anAccount; - NS_ADDREF( anAccount); - } - } - } - else { - if (DoPOP3Server( accMgr, subKey, (char *)pBytes, &anAccount)) { - popCount++; - accounts++; - // If we created a mail account, get rid of it since - // we have 2 POP accounts! - if (ppAccount && *ppAccount) { - NS_RELEASE( *ppAccount); - *ppAccount = nsnull; - } - } - } - nsOutlookRegUtil::FreeValueBytes( pBytes); - } - - if (anAccount) { - // Is this the default account? - keyComp = keyName; - if (keyComp.Equals( defMailName)) { - accMgr->SetDefaultAccount( anAccount); - } - NS_RELEASE( anAccount); - } - - ::RegCloseKey( subKey); - } - } - } - - // Now save the new acct info to pref file. - rv = accMgr->SaveAccountInfo(); - NS_ASSERTION(NS_SUCCEEDED(rv), "Can't save account info to pref file"); + IMPORT_LOG0( "*** Failed to create a account manager!\n"); + return( PR_FALSE); + } + + HKEY subKey = NULL; + nsCString defMailName; + + if (::RegOpenKeyEx( HKEY_CURRENT_USER, "Software\\Microsoft\\Office\\Outlook\\OMI Account Manager", 0, KEY_QUERY_VALUE, &subKey) != ERROR_SUCCESS) + if (::RegOpenKeyEx( HKEY_CURRENT_USER, "Software\\Microsoft\\Office\\8.0\\Outlook\\OMI Account Manager", 0, KEY_QUERY_VALUE, &subKey) != ERROR_SUCCESS) + subKey = NULL; + + if (subKey != NULL) { + // First let's get the default mail account key name + BYTE * pBytes = nsOutlookRegUtil::GetValueBytes( subKey, "Default Mail Account"); + ::RegCloseKey( subKey); + if (pBytes) { + defMailName = (const char *)pBytes; + nsOutlookRegUtil::FreeValueBytes( pBytes); + } + } + + // Iterate the accounts looking for POP3 & IMAP accounts... + // Ignore LDAP & NNTP for now! + DWORD index = 0; + DWORD numChars; + TCHAR keyName[256]; + FILETIME modTime; + LONG result = ERROR_SUCCESS; + BYTE * pBytes; + int popCount = 0; + int accounts = 0; + nsCString keyComp; + + while (result == ERROR_SUCCESS) { + numChars = 256; + result = ::RegEnumKeyEx( hKey, index, keyName, &numChars, NULL, NULL, NULL, &modTime); + index++; + if (result == ERROR_SUCCESS) { + if (::RegOpenKeyEx( hKey, keyName, 0, KEY_QUERY_VALUE, &subKey) == ERROR_SUCCESS) { + // Get the values for this account. + IMPORT_LOG1( "Opened Outlook account: %s\n", (char *)keyName); + + nsIMsgAccount *anAccount = nsnull; + pBytes = nsOutlookRegUtil::GetValueBytes( subKey, "IMAP Server"); + if (pBytes) { + if (DoIMAPServer( accMgr, subKey, (char *)pBytes, &anAccount)) + accounts++; + nsOutlookRegUtil::FreeValueBytes( pBytes); + } + + pBytes = nsOutlookRegUtil::GetValueBytes( subKey, "POP3 Server"); + if (pBytes) { + if (popCount == 0) { + if (DoPOP3Server( accMgr, subKey, (char *)pBytes, &anAccount)) { + popCount++; + accounts++; + if (ppAccount && anAccount) { + *ppAccount = anAccount; + NS_ADDREF( anAccount); + } + } + } + else { + if (DoPOP3Server( accMgr, subKey, (char *)pBytes, &anAccount)) { + popCount++; + accounts++; + // If we created a mail account, get rid of it since + // we have 2 POP accounts! + if (ppAccount && *ppAccount) { + NS_RELEASE( *ppAccount); + *ppAccount = nsnull; + } + } + } + nsOutlookRegUtil::FreeValueBytes( pBytes); + } + + if (anAccount) { + // Is this the default account? + keyComp = keyName; + if (keyComp.Equals( defMailName)) { + accMgr->SetDefaultAccount( anAccount); + } + NS_RELEASE( anAccount); + } - return( accounts != 0); + ::RegCloseKey( subKey); + } + } + } + + // Now save the new acct info to pref file. + rv = accMgr->SaveAccountInfo(); + NS_ASSERTION(NS_SUCCEEDED(rv), "Can't save account info to pref file"); + + return( accounts != 0); } nsresult OutlookSettings::GetAccountName(HKEY hKey, char *defaultName, nsString &acctName) @@ -291,84 +291,84 @@ PRBool OutlookSettings::DoIMAPServer( nsIMsgAccountManager *pMgr, HKEY hKey, char *pServerName, nsIMsgAccount **ppAccount) { - if (ppAccount) - *ppAccount = nsnull; + if (ppAccount) + *ppAccount = nsnull; - BYTE *pBytes; - pBytes = nsOutlookRegUtil::GetValueBytes( hKey, "IMAP User Name"); - if (!pBytes) - return( PR_FALSE); - - PRBool result = PR_FALSE; - - // I now have a user name/server name pair, find out if it already exists? - nsCOMPtr in; - nsresult rv = pMgr->FindServer( (const char *)pBytes, pServerName, "imap", getter_AddRefs( in)); - if (NS_FAILED( rv) || (in == nsnull)) { - // Create the incoming server and an account for it? - rv = pMgr->CreateIncomingServer( (const char *)pBytes, pServerName, "imap", getter_AddRefs( in)); - if (NS_SUCCEEDED( rv) && in) { - rv = in->SetType( "imap"); - // rv = in->SetHostName( pServerName); - // rv = in->SetUsername( (char *)pBytes); - - IMPORT_LOG2( "Created IMAP server named: %s, userName: %s\n", pServerName, (char *)pBytes); + BYTE *pBytes; + pBytes = nsOutlookRegUtil::GetValueBytes( hKey, "IMAP User Name"); + if (!pBytes) + return( PR_FALSE); + + PRBool result = PR_FALSE; + + // I now have a user name/server name pair, find out if it already exists? + nsCOMPtr in; + nsresult rv = pMgr->FindServer( (const char *)pBytes, pServerName, "imap", getter_AddRefs( in)); + if (NS_FAILED( rv) || (in == nsnull)) { + // Create the incoming server and an account for it? + rv = pMgr->CreateIncomingServer( (const char *)pBytes, pServerName, "imap", getter_AddRefs( in)); + if (NS_SUCCEEDED( rv) && in) { + rv = in->SetType( "imap"); + // rv = in->SetHostName( pServerName); + // rv = in->SetUsername( (char *)pBytes); + + IMPORT_LOG2( "Created IMAP server named: %s, userName: %s\n", pServerName, (char *)pBytes); - nsString prettyName; + nsString prettyName; if (NS_SUCCEEDED(GetAccountName(hKey, pServerName, prettyName))) { - PRUnichar *pretty = ToNewUnicode(prettyName); + PRUnichar *pretty = ToNewUnicode(prettyName); if (pretty) { - rv = in->SetPrettyName( pretty); - nsCRT::free( pretty); + rv = in->SetPrettyName( pretty); + nsCRT::free( pretty); } } - - // We have a server, create an account. - nsCOMPtr account; - rv = pMgr->CreateAccount( getter_AddRefs( account)); - if (NS_SUCCEEDED( rv) && account) { - rv = account->SetIncomingServer( in); - - IMPORT_LOG0( "Created an account and set the IMAP server as the incoming server\n"); - - // Fiddle with the identities - SetIdentities( pMgr, account, hKey); - result = PR_TRUE; - if (ppAccount) - account->QueryInterface( NS_GET_IID(nsIMsgAccount), (void **)ppAccount); - } - } - } - else - result = PR_TRUE; - - nsOutlookRegUtil::FreeValueBytes( pBytes); + + // We have a server, create an account. + nsCOMPtr account; + rv = pMgr->CreateAccount( getter_AddRefs( account)); + if (NS_SUCCEEDED( rv) && account) { + rv = account->SetIncomingServer( in); + + IMPORT_LOG0( "Created an account and set the IMAP server as the incoming server\n"); - return( result); + // Fiddle with the identities + SetIdentities( pMgr, account, hKey); + result = PR_TRUE; + if (ppAccount) + CallQueryInterface(account, ppAccount); + } + } + } + else + result = PR_TRUE; + + nsOutlookRegUtil::FreeValueBytes( pBytes); + + return( result); } PRBool OutlookSettings::DoPOP3Server( nsIMsgAccountManager *pMgr, HKEY hKey, char *pServerName, nsIMsgAccount **ppAccount) { - if (ppAccount) - *ppAccount = nsnull; + if (ppAccount) + *ppAccount = nsnull; - BYTE *pBytes; - pBytes = nsOutlookRegUtil::GetValueBytes( hKey, "POP3 User Name"); - if (!pBytes) - return( PR_FALSE); - - PRBool result = PR_FALSE; - - // I now have a user name/server name pair, find out if it already exists? - nsCOMPtr in; - nsresult rv = pMgr->FindServer( (const char *)pBytes, pServerName, "pop3", getter_AddRefs( in)); - if (NS_FAILED( rv) || (in == nsnull)) { - // Create the incoming server and an account for it? - rv = pMgr->CreateIncomingServer( (const char *)pBytes, pServerName, "pop3", getter_AddRefs( in)); - if (NS_SUCCEEDED( rv) && in) { - rv = in->SetType( "pop3"); + BYTE *pBytes; + pBytes = nsOutlookRegUtil::GetValueBytes( hKey, "POP3 User Name"); + if (!pBytes) + return( PR_FALSE); + + PRBool result = PR_FALSE; + + // I now have a user name/server name pair, find out if it already exists? + nsCOMPtr in; + nsresult rv = pMgr->FindServer( (const char *)pBytes, pServerName, "pop3", getter_AddRefs( in)); + if (NS_FAILED( rv) || (in == nsnull)) { + // Create the incoming server and an account for it? + rv = pMgr->CreateIncomingServer( (const char *)pBytes, pServerName, "pop3", getter_AddRefs( in)); + if (NS_SUCCEEDED( rv) && in) { + rv = in->SetType( "pop3"); nsCOMPtr pop3Server = do_QueryInterface(in); if (pop3Server) { @@ -408,27 +408,27 @@ } } - IMPORT_LOG2( "Created POP3 server named: %s, userName: %s\n", pServerName, (char *)pBytes); + IMPORT_LOG2( "Created POP3 server named: %s, userName: %s\n", pServerName, (char *)pBytes); - nsString prettyName; + nsString prettyName; if (NS_SUCCEEDED(GetAccountName(hKey, pServerName, prettyName))) { - PRUnichar *pretty = ToNewUnicode(prettyName); + PRUnichar *pretty = ToNewUnicode(prettyName); if (pretty) { - rv = in->SetPrettyName( pretty); - nsCRT::free( pretty); + rv = in->SetPrettyName( pretty); + nsCRT::free( pretty); } } - - // We have a server, create an account. - nsCOMPtr account; - rv = pMgr->CreateAccount( getter_AddRefs( account)); - if (NS_SUCCEEDED( rv) && account) { - rv = account->SetIncomingServer( in); - - IMPORT_LOG0( "Created a new account and set the incoming server to the POP3 server.\n"); - + + // We have a server, create an account. + nsCOMPtr account; + rv = pMgr->CreateAccount( getter_AddRefs( account)); + if (NS_SUCCEEDED( rv) && account) { + rv = account->SetIncomingServer( in); + + IMPORT_LOG0( "Created a new account and set the incoming server to the POP3 server.\n"); + nsCOMPtr pop3Server = do_QueryInterface(in, &rv); NS_ENSURE_SUCCESS(rv,rv); BYTE *pLeaveOnServer = nsOutlookRegUtil::GetValueBytes( hKey, "Leave Mail On Server"); @@ -439,85 +439,85 @@ } // Fiddle with the identities - SetIdentities( pMgr, account, hKey); - result = PR_TRUE; - if (ppAccount) - account->QueryInterface( NS_GET_IID(nsIMsgAccount), (void **)ppAccount); - } - } - } - else - result = PR_TRUE; - - nsOutlookRegUtil::FreeValueBytes( pBytes); + SetIdentities( pMgr, account, hKey); + result = PR_TRUE; + if (ppAccount) + CallQueryInterface(account, ppAccount); + } + } + } + else + result = PR_TRUE; + + nsOutlookRegUtil::FreeValueBytes( pBytes); - return( result); + return( result); } PRBool OutlookSettings::IdentityMatches( nsIMsgIdentity *pIdent, const char *pName, const char *pServer, const char *pEmail, const char *pReply, const char *pUserName) { - if (!pIdent) - return( PR_FALSE); + if (!pIdent) + return( PR_FALSE); - char * pIName = nsnull; - char * pIEmail = nsnull; - char * pIReply = nsnull; - - PRBool result = PR_TRUE; - - // The test here is: - // If the smtp host is the same - // and the email address is the same (if it is supplied) - // and the reply to address is the same (if it is supplied) - // then we match regardless of the full name. - - PRUnichar *ppIName = nsnull; - - nsresult rv = pIdent->GetFullName( &ppIName); - rv = pIdent->GetEmail( &pIEmail); - rv = pIdent->GetReplyTo( &pIReply); - - if (ppIName) { - nsString name(ppIName); - nsCRT::free( ppIName); - pIName = ToNewCString(name); - } - - // for now, if it's the same server and reply to and email then it matches - if (pReply) { - if (!pIReply || nsCRT::strcasecmp( pReply, pIReply)) - result = PR_FALSE; - } - if (pEmail) { - if (!pIEmail || nsCRT::strcasecmp( pEmail, pIEmail)) - result = PR_FALSE; - } - - nsCRT::free( pIName); - nsCRT::free( pIEmail); - nsCRT::free( pIReply); + char * pIName = nsnull; + char * pIEmail = nsnull; + char * pIReply = nsnull; + + PRBool result = PR_TRUE; + + // The test here is: + // If the smtp host is the same + // and the email address is the same (if it is supplied) + // and the reply to address is the same (if it is supplied) + // then we match regardless of the full name. + + PRUnichar *ppIName = nsnull; + + nsresult rv = pIdent->GetFullName( &ppIName); + rv = pIdent->GetEmail( &pIEmail); + rv = pIdent->GetReplyTo( &pIReply); + + if (ppIName) { + nsString name(ppIName); + nsCRT::free( ppIName); + pIName = ToNewCString(name); + } - return( result); + // for now, if it's the same server and reply to and email then it matches + if (pReply) { + if (!pIReply || nsCRT::strcasecmp( pReply, pIReply)) + result = PR_FALSE; + } + if (pEmail) { + if (!pIEmail || nsCRT::strcasecmp( pEmail, pIEmail)) + result = PR_FALSE; + } + + nsCRT::free( pIName); + nsCRT::free( pIEmail); + nsCRT::free( pIReply); + + return( result); } void OutlookSettings::SetIdentities( nsIMsgAccountManager *pMgr, nsIMsgAccount *pAcc, HKEY hKey) { - // Get the relevant information for an identity - char *pName = (char *)nsOutlookRegUtil::GetValueBytes( hKey, "SMTP Display Name"); - char *pServer = (char *)nsOutlookRegUtil::GetValueBytes( hKey, "SMTP Server"); - char *pEmail = (char *)nsOutlookRegUtil::GetValueBytes( hKey, "SMTP Email Address"); - char *pReply = (char *)nsOutlookRegUtil::GetValueBytes( hKey, "SMTP Reply To Email Address"); - char *pUserName = (char *)nsOutlookRegUtil::GetValueBytes( hKey, "SMTP User Name"); + // Get the relevant information for an identity + char *pName = (char *)nsOutlookRegUtil::GetValueBytes( hKey, "SMTP Display Name"); + char *pServer = (char *)nsOutlookRegUtil::GetValueBytes( hKey, "SMTP Server"); + char *pEmail = (char *)nsOutlookRegUtil::GetValueBytes( hKey, "SMTP Email Address"); + char *pReply = (char *)nsOutlookRegUtil::GetValueBytes( hKey, "SMTP Reply To Email Address"); + char *pUserName = (char *)nsOutlookRegUtil::GetValueBytes( hKey, "SMTP User Name"); char *pOrgName = (char *)nsOutlookRegUtil::GetValueBytes( hKey, "SMTP Organization Name"); - nsresult rv; + nsresult rv; - if (pEmail && pName && pServer) { - // The default identity, nor any other identities matched, - // create a new one and add it to the account. - nsCOMPtr id; - rv = pMgr->CreateIdentity( getter_AddRefs( id)); - if (id) { + if (pEmail && pName && pServer) { + // The default identity, nor any other identities matched, + // create a new one and add it to the account. + nsCOMPtr id; + rv = pMgr->CreateIdentity( getter_AddRefs( id)); + if (id) { nsAutoString name, organization; nsCOMPtr impSvc = do_GetService(NS_IMPORTSERVICE_CONTRACTID); if (impSvc) @@ -525,66 +525,66 @@ rv = impSvc->SystemStringToUnicode((const char *)pName, name); if (NS_SUCCEEDED(rv)) { - id->SetFullName( name.get()); - id->SetIdentityName( name.get()); + id->SetFullName( name.get()); + id->SetIdentityName( name.get()); } rv = impSvc->SystemStringToUnicode((const char *)pOrgName, organization); if (NS_SUCCEEDED(rv)) id->SetOrganization( organization.get()); } - id->SetEmail( pEmail); - if (pReply) - id->SetReplyTo( pReply); - pAcc->AddIdentity( id); - - IMPORT_LOG0( "Created identity and added to the account\n"); - IMPORT_LOG1( "\tname: %s\n", pName); - IMPORT_LOG1( "\temail: %s\n", pEmail); - } - } - + id->SetEmail( pEmail); + if (pReply) + id->SetReplyTo( pReply); + pAcc->AddIdentity( id); + + IMPORT_LOG0( "Created identity and added to the account\n"); + IMPORT_LOG1( "\tname: %s\n", pName); + IMPORT_LOG1( "\temail: %s\n", pEmail); + } + } + if (!pUserName) { - nsCOMPtr incomingServer; + nsCOMPtr incomingServer; rv = pAcc->GetIncomingServer(getter_AddRefs( incomingServer)); if (NS_SUCCEEDED(rv) && incomingServer) rv = incomingServer->GetUsername(&pUserName); NS_ASSERTION(NS_SUCCEEDED(rv), "Unable to get UserName from incomingServer"); } - SetSmtpServer( pMgr, pAcc, pServer, pUserName); + SetSmtpServer( pMgr, pAcc, pServer, pUserName); - nsOutlookRegUtil::FreeValueBytes( (BYTE *)pName); - nsOutlookRegUtil::FreeValueBytes( (BYTE *)pServer); - nsOutlookRegUtil::FreeValueBytes( (BYTE *)pEmail); - nsOutlookRegUtil::FreeValueBytes( (BYTE *)pReply); - nsOutlookRegUtil::FreeValueBytes( (BYTE *)pUserName); + nsOutlookRegUtil::FreeValueBytes( (BYTE *)pName); + nsOutlookRegUtil::FreeValueBytes( (BYTE *)pServer); + nsOutlookRegUtil::FreeValueBytes( (BYTE *)pEmail); + nsOutlookRegUtil::FreeValueBytes( (BYTE *)pReply); + nsOutlookRegUtil::FreeValueBytes( (BYTE *)pUserName); } void OutlookSettings::SetSmtpServer( nsIMsgAccountManager *pMgr, nsIMsgAccount *pAcc, char *pServer, char *pUser) { - nsresult rv; + nsresult rv; - nsCOMPtr smtpService(do_GetService(NS_SMTPSERVICE_CONTRACTID, &rv)); - if (NS_SUCCEEDED(rv) && smtpService) { - nsCOMPtr foundServer; - - rv = smtpService->FindServer( pUser, pServer, getter_AddRefs( foundServer)); - if (NS_SUCCEEDED( rv) && foundServer) { - IMPORT_LOG1( "SMTP server already exists: %s\n", pServer); - return; - } - nsCOMPtr smtpServer; - - rv = smtpService->CreateSmtpServer( getter_AddRefs( smtpServer)); - if (NS_SUCCEEDED( rv) && smtpServer) { - smtpServer->SetHostname( pServer); - if (pUser) - smtpServer->SetUsername( pUser); - - IMPORT_LOG1( "Created new SMTP server: %s\n", pServer); - } - } + nsCOMPtr smtpService(do_GetService(NS_SMTPSERVICE_CONTRACTID, &rv)); + if (NS_SUCCEEDED(rv) && smtpService) { + nsCOMPtr foundServer; + + rv = smtpService->FindServer( pUser, pServer, getter_AddRefs( foundServer)); + if (NS_SUCCEEDED( rv) && foundServer) { + IMPORT_LOG1( "SMTP server already exists: %s\n", pServer); + return; + } + nsCOMPtr smtpServer; + + rv = smtpService->CreateSmtpServer( getter_AddRefs( smtpServer)); + if (NS_SUCCEEDED( rv) && smtpServer) { + smtpServer->SetHostname( pServer); + if (pUser) + smtpServer->SetUsername( pUser); + + IMPORT_LOG1( "Created new SMTP server: %s\n", pServer); + } + } } Index: mozilla/mailnews/import/src/nsImportAddressBooks.cpp =================================================================== RCS file: /cvsroot/mozilla/mailnews/import/src/nsImportAddressBooks.cpp,v retrieving revision 1.54 diff -u -r1.54 mozilla/mailnews/import/src/nsImportAddressBooks.cpp --- mozilla/mailnews/import/src/nsImportAddressBooks.cpp +++ mozilla/mailnews/import/src/nsImportAddressBooks.cpp @@ -81,144 +81,144 @@ { public: - nsImportGenericAddressBooks(); - virtual ~nsImportGenericAddressBooks(); - - NS_DECL_ISUPPORTS + nsImportGenericAddressBooks(); + virtual ~nsImportGenericAddressBooks(); + + NS_DECL_ISUPPORTS - /* nsISupports GetData (in string dataId); */ - NS_IMETHOD GetData(const char *dataId, nsISupports **_retval); + /* nsISupports GetData (in string dataId); */ + NS_IMETHOD GetData(const char *dataId, nsISupports **_retval); - NS_IMETHOD SetData(const char *dataId, nsISupports *pData); + NS_IMETHOD SetData(const char *dataId, nsISupports *pData); - NS_IMETHOD GetStatus( const char *statusKind, PRInt32 *_retval); + NS_IMETHOD GetStatus( const char *statusKind, PRInt32 *_retval); - /* boolean WantsProgress (); */ - NS_IMETHOD WantsProgress(PRBool *_retval); + /* boolean WantsProgress (); */ + NS_IMETHOD WantsProgress(PRBool *_retval); - /* boolean BeginImport (in nsISupportsString successLog, in nsISupportsString errorLog, in boolean isAddrLocHome); */ - NS_IMETHOD BeginImport(nsISupportsString *successLog, nsISupportsString *errorLog, PRBool isAddrLocHome, PRBool *_retval) ; + /* boolean BeginImport (in nsISupportsString successLog, in nsISupportsString errorLog, in boolean isAddrLocHome); */ + NS_IMETHOD BeginImport(nsISupportsString *successLog, nsISupportsString *errorLog, PRBool isAddrLocHome, PRBool *_retval) ; - /* boolean ContinueImport (); */ - NS_IMETHOD ContinueImport(PRBool *_retval); + /* boolean ContinueImport (); */ + NS_IMETHOD ContinueImport(PRBool *_retval); - /* long GetProgress (); */ - NS_IMETHOD GetProgress(PRInt32 *_retval); + /* long GetProgress (); */ + NS_IMETHOD GetProgress(PRInt32 *_retval); - /* void CancelImport (); */ - NS_IMETHOD CancelImport(void); + /* void CancelImport (); */ + NS_IMETHOD CancelImport(void); private: - void GetDefaultLocation( void); - void GetDefaultBooks( void); - void GetDefaultFieldMap( void); + void GetDefaultLocation( void); + void GetDefaultBooks( void); + void GetDefaultFieldMap( void); public: - static void SetLogs( nsString& success, nsString& error, nsISupportsString *pSuccess, nsISupportsString *pError); + static void SetLogs( nsString& success, nsString& error, nsISupportsString *pSuccess, nsISupportsString *pError); static void ReportError(PRUnichar *pName, nsString *pStream, nsIStringBundle *aBundle); private: - nsIImportAddressBooks * m_pInterface; - nsISupportsArray * m_pBooks; - nsCOMPtr m_pLocation; - nsIImportFieldMap * m_pFieldMap; - PRBool m_autoFind; - PRUnichar * m_description; - PRBool m_gotLocation; - PRBool m_found; - PRBool m_userVerify; - nsISupportsString * m_pSuccessLog; - nsISupportsString * m_pErrorLog; - PRUint32 m_totalSize; - PRBool m_doImport; - AddressThreadData * m_pThreadData; - char * m_pDestinationUri; - nsCOMPtr m_stringBundle; + nsIImportAddressBooks * m_pInterface; + nsISupportsArray * m_pBooks; + nsCOMPtr m_pLocation; + nsIImportFieldMap * m_pFieldMap; + PRBool m_autoFind; + PRUnichar * m_description; + PRBool m_gotLocation; + PRBool m_found; + PRBool m_userVerify; + nsISupportsString * m_pSuccessLog; + nsISupportsString * m_pErrorLog; + PRUint32 m_totalSize; + PRBool m_doImport; + AddressThreadData * m_pThreadData; + char * m_pDestinationUri; + nsCOMPtr m_stringBundle; }; class AddressThreadData { public: - PRBool driverAlive; - PRBool threadAlive; - PRBool abort; - PRBool fatalError; - PRUint32 currentTotal; - PRUint32 currentSize; - nsISupportsArray * books; - nsIImportAddressBooks * addressImport; - nsIImportFieldMap * fieldMap; - nsISupportsString * successLog; - nsISupportsString * errorLog; - char * pDestinationUri; - PRBool bAddrLocInput ; - nsIStringBundle* stringBundle; - - AddressThreadData(); - ~AddressThreadData(); - void DriverDelete(); - void ThreadDelete(); - void DriverAbort(); + PRBool driverAlive; + PRBool threadAlive; + PRBool abort; + PRBool fatalError; + PRUint32 currentTotal; + PRUint32 currentSize; + nsISupportsArray * books; + nsIImportAddressBooks * addressImport; + nsIImportFieldMap * fieldMap; + nsISupportsString * successLog; + nsISupportsString * errorLog; + char * pDestinationUri; + PRBool bAddrLocInput ; + nsIStringBundle* stringBundle; + + AddressThreadData(); + ~AddressThreadData(); + void DriverDelete(); + void ThreadDelete(); + void DriverAbort(); }; nsresult NS_NewGenericAddressBooks(nsIImportGeneric** aImportGeneric) { - NS_PRECONDITION(aImportGeneric != nsnull, "null ptr"); - if (! aImportGeneric) - return NS_ERROR_NULL_POINTER; - - nsImportGenericAddressBooks *pGen = new nsImportGenericAddressBooks(); - - if (pGen == nsnull) - return NS_ERROR_OUT_OF_MEMORY; - - NS_ADDREF( pGen); - nsresult rv = pGen->QueryInterface( NS_GET_IID(nsIImportGeneric), (void **)aImportGeneric); - NS_RELEASE( pGen); + NS_PRECONDITION(aImportGeneric != nsnull, "null ptr"); + if (! aImportGeneric) + return NS_ERROR_NULL_POINTER; + + nsImportGenericAddressBooks *pGen = new nsImportGenericAddressBooks(); + + if (pGen == nsnull) + return NS_ERROR_OUT_OF_MEMORY; + + NS_ADDREF( pGen); + nsresult rv = CallQueryInterface(pGen, aImportGeneric); + NS_RELEASE( pGen); - return( rv); + return( rv); } nsImportGenericAddressBooks::nsImportGenericAddressBooks() { - m_pInterface = nsnull; - m_pBooks = nsnull; - m_pSuccessLog = nsnull; - m_pErrorLog = nsnull; - m_totalSize = 0; - m_doImport = PR_FALSE; - m_pThreadData = nsnull; - m_pDestinationUri = nsnull; - m_pFieldMap = nsnull; - - m_autoFind = PR_FALSE; - m_description = nsnull; - m_gotLocation = PR_FALSE; - m_found = PR_FALSE; - m_userVerify = PR_FALSE; + m_pInterface = nsnull; + m_pBooks = nsnull; + m_pSuccessLog = nsnull; + m_pErrorLog = nsnull; + m_totalSize = 0; + m_doImport = PR_FALSE; + m_pThreadData = nsnull; + m_pDestinationUri = nsnull; + m_pFieldMap = nsnull; + + m_autoFind = PR_FALSE; + m_description = nsnull; + m_gotLocation = PR_FALSE; + m_found = PR_FALSE; + m_userVerify = PR_FALSE; - nsImportStringBundle::GetStringBundle(IMPORT_MSGS_URL, getter_AddRefs(m_stringBundle)); + nsImportStringBundle::GetStringBundle(IMPORT_MSGS_URL, getter_AddRefs(m_stringBundle)); } nsImportGenericAddressBooks::~nsImportGenericAddressBooks() { - if (m_pThreadData) { - m_pThreadData->DriverAbort(); - m_pThreadData = nsnull; - } - - if (m_pDestinationUri) - nsCRT::free( m_pDestinationUri); - - if (m_description) - nsCRT::free( m_description); - - NS_IF_RELEASE( m_pFieldMap); - NS_IF_RELEASE( m_pInterface); - NS_IF_RELEASE( m_pBooks); - NS_IF_RELEASE( m_pSuccessLog); - NS_IF_RELEASE( m_pErrorLog); + if (m_pThreadData) { + m_pThreadData->DriverAbort(); + m_pThreadData = nsnull; + } + + if (m_pDestinationUri) + nsCRT::free( m_pDestinationUri); + + if (m_description) + nsCRT::free( m_description); + + NS_IF_RELEASE( m_pFieldMap); + NS_IF_RELEASE( m_pInterface); + NS_IF_RELEASE( m_pBooks); + NS_IF_RELEASE( m_pSuccessLog); + NS_IF_RELEASE( m_pErrorLog); } @@ -228,112 +228,112 @@ NS_IMETHODIMP nsImportGenericAddressBooks::GetData(const char *dataId, nsISupports **_retval) { - NS_PRECONDITION(_retval != nsnull, "null ptr"); - if (!_retval) - return NS_ERROR_NULL_POINTER; - - nsresult rv; - *_retval = nsnull; - if (!nsCRT::strcasecmp( dataId, "addressInterface")) { - *_retval = m_pInterface; - NS_IF_ADDREF( m_pInterface); - } - - if (!nsCRT::strcasecmp( dataId, "addressLocation")) { - if (!m_pLocation) - GetDefaultLocation(); - NS_IF_ADDREF(*_retval = m_pLocation); - } - - if (!nsCRT::strcasecmp( dataId, "addressBooks")) { - if (!m_pLocation) - GetDefaultLocation(); - if (!m_pBooks) - GetDefaultBooks(); - *_retval = m_pBooks; - NS_IF_ADDREF( m_pBooks); - } - - if (!nsCRT::strcasecmp( dataId, "addressDestination")) { - if (m_pDestinationUri) { - nsCOMPtr abString = do_CreateInstance(NS_SUPPORTS_CSTRING_CONTRACTID, &rv); - NS_ENSURE_SUCCESS(rv, rv); - abString->SetData(nsDependentCString(m_pDestinationUri)); - NS_IF_ADDREF( *_retval = abString); - } - } - - if (!nsCRT::strcasecmp( dataId, "fieldMap")) { - if (m_pFieldMap) { - *_retval = m_pFieldMap; - m_pFieldMap->AddRef(); - } - else { - if (m_pInterface && m_pLocation) { - PRBool needsIt = PR_FALSE; - m_pInterface->GetNeedsFieldMap( m_pLocation, &needsIt); - if (needsIt) { - GetDefaultFieldMap(); - if (m_pFieldMap) { - *_retval = m_pFieldMap; - m_pFieldMap->AddRef(); - } - } - } - } - } - - if (!nsCRT::strncasecmp( dataId, "sampleData-", 11)) { - // extra the record number - const char *pNum = dataId + 11; - PRInt32 rNum = 0; - while (*pNum) { - rNum *= 10; - rNum += (*pNum - '0'); - pNum++; - } - IMPORT_LOG1( "Requesting sample data #: %ld\n", (long)rNum); - if (m_pInterface) { - nsCOMPtr data = do_CreateInstance( NS_SUPPORTS_STRING_CONTRACTID, &rv); - if (NS_FAILED( rv)) - return( rv); - PRUnichar * pData = nsnull; - PRBool found = PR_FALSE; - rv = m_pInterface->GetSampleData( rNum, &found, &pData); - if (NS_FAILED( rv)) - return( rv); - if (found) { - data->SetData(nsDependentString(pData)); - *_retval = data; - NS_ADDREF( *_retval); - } - nsCRT::free( pData); - } - } + NS_PRECONDITION(_retval != nsnull, "null ptr"); + if (!_retval) + return NS_ERROR_NULL_POINTER; + + nsresult rv; + *_retval = nsnull; + if (!nsCRT::strcasecmp( dataId, "addressInterface")) { + *_retval = m_pInterface; + NS_IF_ADDREF( m_pInterface); + } + + if (!nsCRT::strcasecmp( dataId, "addressLocation")) { + if (!m_pLocation) + GetDefaultLocation(); + NS_IF_ADDREF(*_retval = m_pLocation); + } + + if (!nsCRT::strcasecmp( dataId, "addressBooks")) { + if (!m_pLocation) + GetDefaultLocation(); + if (!m_pBooks) + GetDefaultBooks(); + *_retval = m_pBooks; + NS_IF_ADDREF( m_pBooks); + } + + if (!nsCRT::strcasecmp( dataId, "addressDestination")) { + if (m_pDestinationUri) { + nsCOMPtr abString = do_CreateInstance(NS_SUPPORTS_CSTRING_CONTRACTID, &rv); + NS_ENSURE_SUCCESS(rv, rv); + abString->SetData(nsDependentCString(m_pDestinationUri)); + NS_IF_ADDREF( *_retval = abString); + } + } - return( NS_OK); + if (!nsCRT::strcasecmp( dataId, "fieldMap")) { + if (m_pFieldMap) { + *_retval = m_pFieldMap; + m_pFieldMap->AddRef(); + } + else { + if (m_pInterface && m_pLocation) { + PRBool needsIt = PR_FALSE; + m_pInterface->GetNeedsFieldMap( m_pLocation, &needsIt); + if (needsIt) { + GetDefaultFieldMap(); + if (m_pFieldMap) { + *_retval = m_pFieldMap; + m_pFieldMap->AddRef(); + } + } + } + } + } + + if (!nsCRT::strncasecmp( dataId, "sampleData-", 11)) { + // extra the record number + const char *pNum = dataId + 11; + PRInt32 rNum = 0; + while (*pNum) { + rNum *= 10; + rNum += (*pNum - '0'); + pNum++; + } + IMPORT_LOG1( "Requesting sample data #: %ld\n", (long)rNum); + if (m_pInterface) { + nsCOMPtr data = do_CreateInstance( NS_SUPPORTS_STRING_CONTRACTID, &rv); + if (NS_FAILED( rv)) + return( rv); + PRUnichar * pData = nsnull; + PRBool found = PR_FALSE; + rv = m_pInterface->GetSampleData( rNum, &found, &pData); + if (NS_FAILED( rv)) + return( rv); + if (found) { + data->SetData(nsDependentString(pData)); + *_retval = data; + NS_ADDREF( *_retval); + } + nsCRT::free( pData); + } + } + + return( NS_OK); } NS_IMETHODIMP nsImportGenericAddressBooks::SetData( const char *dataId, nsISupports *item) { - NS_PRECONDITION(dataId != nsnull, "null ptr"); - if (!dataId) - return NS_ERROR_NULL_POINTER; - - if (!nsCRT::strcasecmp( dataId, "addressInterface")) { - NS_IF_RELEASE( m_pInterface); - if (item) - item->QueryInterface( NS_GET_IID(nsIImportAddressBooks), (void **) &m_pInterface); - } - if (!nsCRT::strcasecmp( dataId, "addressBooks")) { - NS_IF_RELEASE( m_pBooks); - if (item) - item->QueryInterface( NS_GET_IID(nsISupportsArray), (void **) &m_pBooks); - } - - if (!nsCRT::strcasecmp( dataId, "addressLocation")) { - m_pLocation = nsnull; + NS_PRECONDITION(dataId != nsnull, "null ptr"); + if (!dataId) + return NS_ERROR_NULL_POINTER; + + if (!nsCRT::strcasecmp( dataId, "addressInterface")) { + NS_IF_RELEASE( m_pInterface); + if (item) + CallQueryInterface(item, &m_pInterface); + } + if (!nsCRT::strcasecmp( dataId, "addressBooks")) { + NS_IF_RELEASE( m_pBooks); + if (item) + CallQueryInterface(item, &m_pBooks); + } + + if (!nsCRT::strcasecmp( dataId, "addressLocation")) { + m_pLocation = nsnull; if (item) { nsresult rv; @@ -345,365 +345,364 @@ } if (m_pInterface) - m_pInterface->SetSampleLocation(m_pLocation); - } + m_pInterface->SetSampleLocation(m_pLocation); + } + + if (!nsCRT::strcasecmp( dataId, "addressDestination")) { + if (item) { + nsCOMPtr abString(do_QueryInterface(item)); + if (abString) { + if (m_pDestinationUri) + nsCRT::free( m_pDestinationUri); + m_pDestinationUri = nsnull; + nsCAutoString tempUri; + abString->GetData(tempUri); + m_pDestinationUri = ToNewCString(tempUri); + } + } + } - if (!nsCRT::strcasecmp( dataId, "addressDestination")) { - if (item) { - nsCOMPtr abString; - item->QueryInterface( NS_GET_IID(nsISupportsCString), getter_AddRefs( abString)); - if (abString) { - if (m_pDestinationUri) - nsCRT::free( m_pDestinationUri); - m_pDestinationUri = nsnull; - nsCAutoString tempUri; - abString->GetData(tempUri); - m_pDestinationUri = ToNewCString(tempUri); - } - } - } - - if (!nsCRT::strcasecmp( dataId, "fieldMap")) { - NS_IF_RELEASE( m_pFieldMap); - if (item) - item->QueryInterface( NS_GET_IID(nsIImportFieldMap), (void **) &m_pFieldMap); - } - - return( NS_OK); + if (!nsCRT::strcasecmp( dataId, "fieldMap")) { + NS_IF_RELEASE( m_pFieldMap); + if (item) + CallQueryInterface(item, &m_pFieldMap); + } + + return( NS_OK); } NS_IMETHODIMP nsImportGenericAddressBooks::GetStatus( const char *statusKind, PRInt32 *_retval) { - NS_PRECONDITION(statusKind != nsnull, "null ptr"); - NS_PRECONDITION(_retval != nsnull, "null ptr"); - if (!statusKind || !_retval) - return( NS_ERROR_NULL_POINTER); - - *_retval = 0; - - if (!nsCRT::strcasecmp( statusKind, "isInstalled")) { - GetDefaultLocation(); - *_retval = (PRInt32) m_found; - } - - if (!nsCRT::strcasecmp( statusKind, "canUserSetLocation")) { - GetDefaultLocation(); - *_retval = (PRInt32) m_userVerify; - } - - if (!nsCRT::strcasecmp( statusKind, "autoFind")) { - GetDefaultLocation(); - *_retval = (PRInt32) m_autoFind; - } - - if (!nsCRT::strcasecmp( statusKind, "supportsMultiple")) { - PRBool multi = PR_FALSE; - if (m_pInterface) - m_pInterface->GetSupportsMultiple( &multi); - *_retval = (PRInt32) multi; - } - - if (!nsCRT::strcasecmp( statusKind, "needsFieldMap")) { - PRBool needs = PR_FALSE; - if (m_pInterface && m_pLocation) - m_pInterface->GetNeedsFieldMap( m_pLocation, &needs); - *_retval = (PRInt32) needs; - } + NS_PRECONDITION(statusKind != nsnull, "null ptr"); + NS_PRECONDITION(_retval != nsnull, "null ptr"); + if (!statusKind || !_retval) + return( NS_ERROR_NULL_POINTER); + + *_retval = 0; + + if (!nsCRT::strcasecmp( statusKind, "isInstalled")) { + GetDefaultLocation(); + *_retval = (PRInt32) m_found; + } + + if (!nsCRT::strcasecmp( statusKind, "canUserSetLocation")) { + GetDefaultLocation(); + *_retval = (PRInt32) m_userVerify; + } + + if (!nsCRT::strcasecmp( statusKind, "autoFind")) { + GetDefaultLocation(); + *_retval = (PRInt32) m_autoFind; + } + + if (!nsCRT::strcasecmp( statusKind, "supportsMultiple")) { + PRBool multi = PR_FALSE; + if (m_pInterface) + m_pInterface->GetSupportsMultiple( &multi); + *_retval = (PRInt32) multi; + } + + if (!nsCRT::strcasecmp( statusKind, "needsFieldMap")) { + PRBool needs = PR_FALSE; + if (m_pInterface && m_pLocation) + m_pInterface->GetNeedsFieldMap( m_pLocation, &needs); + *_retval = (PRInt32) needs; + } - return( NS_OK); + return( NS_OK); } void nsImportGenericAddressBooks::GetDefaultLocation( void) { - if (!m_pInterface) - return; - - if ((m_pLocation && m_gotLocation) || m_autoFind) - return; - - if (m_description) - nsCRT::free( m_description); - m_description = nsnull; - m_pInterface->GetAutoFind( &m_description, &m_autoFind); - m_gotLocation = PR_TRUE; - if (m_autoFind) { - m_found = PR_TRUE; - m_userVerify = PR_FALSE; - return; - } - - nsIFileSpec * pLoc = nsnull; - m_pInterface->GetDefaultLocation( &pLoc, &m_found, &m_userVerify); - if (!m_pLocation) - m_pLocation = pLoc; - else { - NS_IF_RELEASE( pLoc); - } + if (!m_pInterface) + return; + + if ((m_pLocation && m_gotLocation) || m_autoFind) + return; + + if (m_description) + nsCRT::free( m_description); + m_description = nsnull; + m_pInterface->GetAutoFind( &m_description, &m_autoFind); + m_gotLocation = PR_TRUE; + if (m_autoFind) { + m_found = PR_TRUE; + m_userVerify = PR_FALSE; + return; + } + + nsIFileSpec * pLoc = nsnull; + m_pInterface->GetDefaultLocation( &pLoc, &m_found, &m_userVerify); + if (!m_pLocation) + m_pLocation = pLoc; + else { + NS_IF_RELEASE( pLoc); + } } void nsImportGenericAddressBooks::GetDefaultBooks( void) { - if (!m_pInterface || m_pBooks) - return; - - if (!m_pLocation && !m_autoFind) - return; - - nsresult rv = m_pInterface->FindAddressBooks( m_pLocation, &m_pBooks); - if (NS_FAILED( rv)) { - IMPORT_LOG0( "*** Error: FindAddressBooks failed\n"); - } + if (!m_pInterface || m_pBooks) + return; + + if (!m_pLocation && !m_autoFind) + return; + + nsresult rv = m_pInterface->FindAddressBooks( m_pLocation, &m_pBooks); + if (NS_FAILED( rv)) { + IMPORT_LOG0( "*** Error: FindAddressBooks failed\n"); + } } void nsImportGenericAddressBooks::GetDefaultFieldMap( void) { - if (!m_pInterface || !m_pLocation) - return; - - NS_IF_RELEASE( m_pFieldMap); - - nsresult rv; - nsCOMPtr impSvc(do_GetService(NS_IMPORTSERVICE_CONTRACTID, &rv)); - if (NS_FAILED(rv)) { - IMPORT_LOG0( "*** Unable to get nsIImportService.\n"); - return; - } - - rv = impSvc->CreateNewFieldMap( &m_pFieldMap); - if (NS_FAILED( rv)) - return; - - PRInt32 sz = 0; - rv = m_pFieldMap->GetNumMozFields( &sz); - if (NS_SUCCEEDED( rv)) - rv = m_pFieldMap->DefaultFieldMap( sz); + if (!m_pInterface || !m_pLocation) + return; + + NS_IF_RELEASE( m_pFieldMap); + + nsresult rv; + nsCOMPtr impSvc(do_GetService(NS_IMPORTSERVICE_CONTRACTID, &rv)); + if (NS_FAILED(rv)) { + IMPORT_LOG0( "*** Unable to get nsIImportService.\n"); + return; + } + + rv = impSvc->CreateNewFieldMap( &m_pFieldMap); + if (NS_FAILED( rv)) + return; + + PRInt32 sz = 0; + rv = m_pFieldMap->GetNumMozFields( &sz); + if (NS_SUCCEEDED( rv)) + rv = m_pFieldMap->DefaultFieldMap( sz); if (NS_SUCCEEDED( rv)) rv = m_pInterface->InitFieldMap(m_pFieldMap); - if (NS_FAILED( rv)) { - IMPORT_LOG0( "*** Error: Unable to initialize field map\n"); - NS_IF_RELEASE( m_pFieldMap); - } + if (NS_FAILED( rv)) { + IMPORT_LOG0( "*** Error: Unable to initialize field map\n"); + NS_IF_RELEASE( m_pFieldMap); + } } NS_IMETHODIMP nsImportGenericAddressBooks::WantsProgress(PRBool *_retval) { - NS_PRECONDITION(_retval != nsnull, "null ptr"); - if (!_retval) - return NS_ERROR_NULL_POINTER; - - if (m_pThreadData) { - m_pThreadData->DriverAbort(); - m_pThreadData = nsnull; - } - - GetDefaultLocation(); - GetDefaultBooks(); - - PRUint32 totalSize = 0; - PRBool result = PR_FALSE; - - if (m_pBooks) { - PRUint32 count = 0; - nsresult rv = m_pBooks->Count( &count); - PRUint32 i; - PRBool import; - PRUint32 size; - - for (i = 0; i < count; i++) { - nsCOMPtr book = - do_QueryElementAt(m_pBooks, i); - if (book) { - import = PR_FALSE; - size = 0; - rv = book->GetImport( &import); - if (import) { - rv = book->GetSize( &size); - result = PR_TRUE; - } - totalSize += size; - } - } - - m_totalSize = totalSize; - } - - m_doImport = result; + NS_PRECONDITION(_retval != nsnull, "null ptr"); + if (!_retval) + return NS_ERROR_NULL_POINTER; + + if (m_pThreadData) { + m_pThreadData->DriverAbort(); + m_pThreadData = nsnull; + } + + GetDefaultLocation(); + GetDefaultBooks(); + + PRUint32 totalSize = 0; + PRBool result = PR_FALSE; + + if (m_pBooks) { + PRUint32 count = 0; + nsresult rv = m_pBooks->Count( &count); + PRUint32 i; + PRBool import; + PRUint32 size; + + for (i = 0; i < count; i++) { + nsCOMPtr book = + do_QueryElementAt(m_pBooks, i); + if (book) { + import = PR_FALSE; + size = 0; + rv = book->GetImport( &import); + if (import) { + rv = book->GetSize( &size); + result = PR_TRUE; + } + totalSize += size; + } + } + + m_totalSize = totalSize; + } + + m_doImport = result; - *_retval = result; + *_retval = result; - return( NS_OK); + return( NS_OK); } void nsImportGenericAddressBooks::SetLogs( nsString& success, nsString& error, nsISupportsString *pSuccess, nsISupportsString *pError) { - nsAutoString str; - if (pSuccess) { - pSuccess->GetData(str); - str.Append(success); - pSuccess->SetData(success); - } - if (pError) { - pError->GetData(str); + nsAutoString str; + if (pSuccess) { + pSuccess->GetData(str); + str.Append(success); + pSuccess->SetData(success); + } + if (pError) { + pError->GetData(str); str.Append(error); pError->SetData(error); - } + } } NS_IMETHODIMP nsImportGenericAddressBooks::BeginImport(nsISupportsString *successLog, nsISupportsString *errorLog, PRBool isAddrLocHome, PRBool *_retval) { - NS_PRECONDITION(_retval != nsnull, "null ptr"); - if (!_retval) - return NS_ERROR_NULL_POINTER; - - nsString success; - nsString error; - - if (!m_doImport) { - *_retval = PR_TRUE; + NS_PRECONDITION(_retval != nsnull, "null ptr"); + if (!_retval) + return NS_ERROR_NULL_POINTER; + + nsString success; + nsString error; + + if (!m_doImport) { + *_retval = PR_TRUE; nsImportStringBundle::GetStringByID(IMPORT_NO_ADDRBOOKS, success, m_stringBundle); - SetLogs( success, error, successLog, errorLog); - return( NS_OK); - } - - if (!m_pInterface || !m_pBooks) { + SetLogs( success, error, successLog, errorLog); + return( NS_OK); + } + + if (!m_pInterface || !m_pBooks) { nsImportStringBundle::GetStringByID(IMPORT_ERROR_AB_NOTINITIALIZED, error, m_stringBundle); - SetLogs( success, error, successLog, errorLog); - *_retval = PR_FALSE; - return( NS_OK); - } - - if (m_pThreadData) { - m_pThreadData->DriverAbort(); - m_pThreadData = nsnull; - } - - NS_IF_RELEASE( m_pSuccessLog); - NS_IF_RELEASE( m_pErrorLog); - m_pSuccessLog = successLog; - m_pErrorLog = errorLog; - NS_IF_ADDREF( m_pSuccessLog); - NS_IF_ADDREF( m_pErrorLog); - - - // kick off the thread to do the import!!!! - m_pThreadData = new AddressThreadData(); - m_pThreadData->books = m_pBooks; - NS_ADDREF( m_pBooks); - m_pThreadData->addressImport = m_pInterface; - NS_ADDREF( m_pInterface); - m_pThreadData->fieldMap = m_pFieldMap; - NS_IF_ADDREF( m_pFieldMap); - m_pThreadData->errorLog = m_pErrorLog; - NS_IF_ADDREF( m_pErrorLog); - m_pThreadData->successLog = m_pSuccessLog; - NS_IF_ADDREF( m_pSuccessLog); - if (m_pDestinationUri) - m_pThreadData->pDestinationUri = nsCRT::strdup( m_pDestinationUri); - m_pThreadData->bAddrLocInput = isAddrLocHome ; - - NS_IF_ADDREF(m_pThreadData->stringBundle = m_stringBundle); - - PRThread *pThread = PR_CreateThread( PR_USER_THREAD, &ImportAddressThread, m_pThreadData, - PR_PRIORITY_NORMAL, - PR_LOCAL_THREAD, - PR_UNJOINABLE_THREAD, - 0); - if (!pThread) { - m_pThreadData->ThreadDelete(); - m_pThreadData->DriverDelete(); - m_pThreadData = nsnull; - *_retval = PR_FALSE; + SetLogs( success, error, successLog, errorLog); + *_retval = PR_FALSE; + return( NS_OK); + } + + if (m_pThreadData) { + m_pThreadData->DriverAbort(); + m_pThreadData = nsnull; + } + + NS_IF_RELEASE( m_pSuccessLog); + NS_IF_RELEASE( m_pErrorLog); + m_pSuccessLog = successLog; + m_pErrorLog = errorLog; + NS_IF_ADDREF( m_pSuccessLog); + NS_IF_ADDREF( m_pErrorLog); + + + // kick off the thread to do the import!!!! + m_pThreadData = new AddressThreadData(); + m_pThreadData->books = m_pBooks; + NS_ADDREF( m_pBooks); + m_pThreadData->addressImport = m_pInterface; + NS_ADDREF( m_pInterface); + m_pThreadData->fieldMap = m_pFieldMap; + NS_IF_ADDREF( m_pFieldMap); + m_pThreadData->errorLog = m_pErrorLog; + NS_IF_ADDREF( m_pErrorLog); + m_pThreadData->successLog = m_pSuccessLog; + NS_IF_ADDREF( m_pSuccessLog); + if (m_pDestinationUri) + m_pThreadData->pDestinationUri = nsCRT::strdup( m_pDestinationUri); + m_pThreadData->bAddrLocInput = isAddrLocHome ; + + NS_IF_ADDREF(m_pThreadData->stringBundle = m_stringBundle); + + PRThread *pThread = PR_CreateThread( PR_USER_THREAD, &ImportAddressThread, m_pThreadData, + PR_PRIORITY_NORMAL, + PR_LOCAL_THREAD, + PR_UNJOINABLE_THREAD, + 0); + if (!pThread) { + m_pThreadData->ThreadDelete(); + m_pThreadData->DriverDelete(); + m_pThreadData = nsnull; + *_retval = PR_FALSE; nsImportStringBundle::GetStringByID(IMPORT_ERROR_AB_NOTHREAD, error, m_stringBundle); - SetLogs( success, error, successLog, errorLog); - } - else - *_retval = PR_TRUE; - - return( NS_OK); + SetLogs( success, error, successLog, errorLog); + } + else + *_retval = PR_TRUE; + + return( NS_OK); } NS_IMETHODIMP nsImportGenericAddressBooks::ContinueImport(PRBool *_retval) { - NS_PRECONDITION(_retval != nsnull, "null ptr"); - if (!_retval) - return NS_ERROR_NULL_POINTER; - - *_retval = PR_TRUE; - if (m_pThreadData) { - if (m_pThreadData->fatalError) - *_retval = PR_FALSE; - } + NS_PRECONDITION(_retval != nsnull, "null ptr"); + if (!_retval) + return NS_ERROR_NULL_POINTER; + + *_retval = PR_TRUE; + if (m_pThreadData) { + if (m_pThreadData->fatalError) + *_retval = PR_FALSE; + } - return( NS_OK); + return( NS_OK); } NS_IMETHODIMP nsImportGenericAddressBooks::GetProgress(PRInt32 *_retval) { - // This returns the progress from the the currently - // running import mail or import address book thread. - NS_PRECONDITION(_retval != nsnull, "null ptr"); - if (!_retval) - return NS_ERROR_NULL_POINTER; - - if (!m_pThreadData || !(m_pThreadData->threadAlive)) { - *_retval = 100; - return( NS_OK); - } - - PRUint32 sz = 0; - if (m_pThreadData->currentSize && m_pInterface) { - if (NS_FAILED( m_pInterface->GetImportProgress( &sz))) - sz = 0; - } - - if (m_totalSize) - *_retval = ((m_pThreadData->currentTotal + sz) * 100) / m_totalSize; - else - *_retval = 0; - - // never return less than 5 so it looks like we are doing something! - if (*_retval < 5) - *_retval = 5; - - // as long as the thread is alive don't return completely - // done. - if (*_retval > 99) - *_retval = 99; + // This returns the progress from the the currently + // running import mail or import address book thread. + NS_PRECONDITION(_retval != nsnull, "null ptr"); + if (!_retval) + return NS_ERROR_NULL_POINTER; + + if (!m_pThreadData || !(m_pThreadData->threadAlive)) { + *_retval = 100; + return( NS_OK); + } + + PRUint32 sz = 0; + if (m_pThreadData->currentSize && m_pInterface) { + if (NS_FAILED( m_pInterface->GetImportProgress( &sz))) + sz = 0; + } + + if (m_totalSize) + *_retval = ((m_pThreadData->currentTotal + sz) * 100) / m_totalSize; + else + *_retval = 0; + + // never return less than 5 so it looks like we are doing something! + if (*_retval < 5) + *_retval = 5; + + // as long as the thread is alive don't return completely + // done. + if (*_retval > 99) + *_retval = 99; - return( NS_OK); + return( NS_OK); } NS_IMETHODIMP nsImportGenericAddressBooks::CancelImport(void) { - if (m_pThreadData) { - m_pThreadData->abort = PR_TRUE; - m_pThreadData->DriverAbort(); - m_pThreadData = nsnull; - } + if (m_pThreadData) { + m_pThreadData->abort = PR_TRUE; + m_pThreadData->DriverAbort(); + m_pThreadData = nsnull; + } - return( NS_OK); + return( NS_OK); } AddressThreadData::AddressThreadData() { - fatalError = PR_FALSE; - driverAlive = PR_TRUE; - threadAlive = PR_TRUE; - abort = PR_FALSE; - currentTotal = 0; - currentSize = 0; - books = nsnull; - addressImport = nsnull; - successLog = nsnull; - errorLog = nsnull; - pDestinationUri = nsnull; - fieldMap = nsnull; + fatalError = PR_FALSE; + driverAlive = PR_TRUE; + threadAlive = PR_TRUE; + abort = PR_FALSE; + currentTotal = 0; + currentSize = 0; + books = nsnull; + addressImport = nsnull; + successLog = nsnull; + errorLog = nsnull; + pDestinationUri = nsnull; + fieldMap = nsnull; stringBundle = nsnull; } @@ -722,283 +721,283 @@ void AddressThreadData::DriverDelete( void) { - driverAlive = PR_FALSE; - if (!driverAlive && !threadAlive) - delete this; + driverAlive = PR_FALSE; + if (!driverAlive && !threadAlive) + delete this; } void AddressThreadData::ThreadDelete() { - threadAlive = PR_FALSE; - if (!driverAlive && !threadAlive) - delete this; + threadAlive = PR_FALSE; + if (!driverAlive && !threadAlive) + delete this; } void AddressThreadData::DriverAbort() { - if (abort && !threadAlive) { - // FIXME: Do whatever is necessary to abort what has already been imported! - } - else - abort = PR_TRUE; - DriverDelete(); + if (abort && !threadAlive) { + // FIXME: Do whatever is necessary to abort what has already been imported! + } + else + abort = PR_TRUE; + DriverDelete(); } nsIAddrDatabase *GetAddressBookFromUri( const char *pUri) { - nsIAddrDatabase * pDatabase = nsnull; - if (pUri) { - nsresult rv = NS_OK; - NS_WITH_PROXIED_SERVICE(nsIAddressBook, addressBook, - NS_ADDRESSBOOK_CONTRACTID, - NS_PROXY_TO_MAIN_THREAD, &rv); - if (addressBook) - rv = addressBook->GetAbDatabaseFromURI(pUri, &pDatabase); - } + nsIAddrDatabase * pDatabase = nsnull; + if (pUri) { + nsresult rv = NS_OK; + NS_WITH_PROXIED_SERVICE(nsIAddressBook, addressBook, + NS_ADDRESSBOOK_CONTRACTID, + NS_PROXY_TO_MAIN_THREAD, &rv); + if (addressBook) + rv = addressBook->GetAbDatabaseFromURI(pUri, &pDatabase); + } - return pDatabase; + return pDatabase; } nsIAddrDatabase *GetAddressBook( const PRUnichar *name, PRBool makeNew) { - nsresult rv = NS_OK; + nsresult rv = NS_OK; - if (!makeNew) { - // FIXME: How do I get the list of address books and look for a - // specific name. Major bogosity! - // For now, assume we didn't find anything with that name - } - - IMPORT_LOG0( "In GetAddressBook\n"); + if (!makeNew) { + // FIXME: How do I get the list of address books and look for a + // specific name. Major bogosity! + // For now, assume we didn't find anything with that name + } + + IMPORT_LOG0( "In GetAddressBook\n"); - nsIAddrDatabase * pDatabase = nsnull; + nsIAddrDatabase * pDatabase = nsnull; - /* Get the profile directory */ - nsCOMPtr dbPath; + /* Get the profile directory */ + nsCOMPtr dbPath; - NS_WITH_PROXIED_SERVICE(nsIAddrBookSession, abSession, + NS_WITH_PROXIED_SERVICE(nsIAddrBookSession, abSession, NS_ADDRBOOKSESSION_CONTRACTID, NS_PROXY_TO_MAIN_THREAD, &rv); - - if (NS_SUCCEEDED(rv)) - rv = abSession->GetUserProfileDirectory(getter_AddRefs(dbPath)); - if (NS_SUCCEEDED(rv)) { - // Create a new address book file - we don't care what the file - // name is, as long as it's unique - rv = dbPath->Append(NS_LITERAL_STRING("impab.mab")); - if (NS_SUCCEEDED(rv)) { - rv = dbPath->CreateUnique(nsIFile::NORMAL_FILE_TYPE, 0600); - - if (NS_SUCCEEDED(rv)) { - IMPORT_LOG0( "Getting the address database factory\n"); - - NS_WITH_PROXIED_SERVICE(nsIAddrDatabase, addrDBFactory, - NS_ADDRDATABASE_CONTRACTID, - NS_PROXY_TO_MAIN_THREAD, &rv); - if (NS_SUCCEEDED(rv) && addrDBFactory) { - IMPORT_LOG0( "Opening the new address book\n"); - rv = addrDBFactory->Open( dbPath, PR_TRUE, PR_TRUE, &pDatabase); - } - } + + if (NS_SUCCEEDED(rv)) + rv = abSession->GetUserProfileDirectory(getter_AddRefs(dbPath)); + if (NS_SUCCEEDED(rv)) { + // Create a new address book file - we don't care what the file + // name is, as long as it's unique + rv = dbPath->Append(NS_LITERAL_STRING("impab.mab")); + if (NS_SUCCEEDED(rv)) { + rv = dbPath->CreateUnique(nsIFile::NORMAL_FILE_TYPE, 0600); + + if (NS_SUCCEEDED(rv)) { + IMPORT_LOG0( "Getting the address database factory\n"); + + NS_WITH_PROXIED_SERVICE(nsIAddrDatabase, addrDBFactory, + NS_ADDRDATABASE_CONTRACTID, + NS_PROXY_TO_MAIN_THREAD, &rv); + if (NS_SUCCEEDED(rv) && addrDBFactory) { + IMPORT_LOG0( "Opening the new address book\n"); + rv = addrDBFactory->Open( dbPath, PR_TRUE, PR_TRUE, &pDatabase); } - } - if (NS_FAILED(rv)) { - IMPORT_LOG0( "Failed to get the user profile directory from the address book session\n"); - } - - - if (pDatabase) { - // We made a database, add it to the UI?!?!?!?!?!?! - // This is major bogosity again! Why doesn't the address book - // just handle this properly for me? Uggggg... - - NS_WITH_PROXIED_SERVICE(nsIRDFService, rdfService, kRDFServiceCID, + } + } + } + if (NS_FAILED(rv)) { + IMPORT_LOG0( "Failed to get the user profile directory from the address book session\n"); + } + + + if (pDatabase) { + // We made a database, add it to the UI?!?!?!?!?!?! + // This is major bogosity again! Why doesn't the address book + // just handle this properly for me? Uggggg... + + NS_WITH_PROXIED_SERVICE(nsIRDFService, rdfService, kRDFServiceCID, NS_PROXY_TO_MAIN_THREAD, &rv); - if (NS_SUCCEEDED(rv)) { - nsCOMPtr parentResource; - rv = rdfService->GetResource(NS_LITERAL_CSTRING(kAllDirectoryRoot), + if (NS_SUCCEEDED(rv)) { + nsCOMPtr parentResource; + rv = rdfService->GetResource(NS_LITERAL_CSTRING(kAllDirectoryRoot), getter_AddRefs(parentResource)); - nsCOMPtr parentDir; - /* - * TODO - * This may not be required in the future since the - * primary listeners of the nsIAbDirectory will be - * RDF directory datasource which propagates events to - * RDF Observers. In the future the RDF directory datasource - * will proxy the observers because asynchronous directory - * implementations, such as LDAP, will assert results from - * a thread other than the UI thread. - * - */ - rv = NS_GetProxyForObject( NS_PROXY_TO_MAIN_THREAD, + nsCOMPtr parentDir; + /* + * TODO + * This may not be required in the future since the + * primary listeners of the nsIAbDirectory will be + * RDF directory datasource which propagates events to + * RDF Observers. In the future the RDF directory datasource + * will proxy the observers because asynchronous directory + * implementations, such as LDAP, will assert results from + * a thread other than the UI thread. + * + */ + rv = NS_GetProxyForObject( NS_PROXY_TO_MAIN_THREAD, NS_GET_IID( nsIAbDirectory), parentResource, NS_PROXY_SYNC | NS_PROXY_ALWAYS, getter_AddRefs( parentDir)); - if (parentDir) - { - nsCAutoString URI("moz-abmdbdirectory://"); - nsCAutoString leafName; - rv = dbPath->GetNativeLeafName(leafName); - if (NS_FAILED(rv)) { - IMPORT_LOG0( "*** Error: Unable to get name of database file\n"); - } - else { - URI.Append(leafName); - rv = parentDir->CreateDirectoryByURI(name, URI.get (), PR_FALSE); - if (NS_FAILED(rv)) - IMPORT_LOG0( "*** Error: Unable to create address book directory\n"); - } - } - - if (NS_SUCCEEDED(rv)) - IMPORT_LOG0( "Added new address book to the UI\n"); - else - IMPORT_LOG0( "*** Error: An error occurred while adding the address book to the UI\n"); - } - } - - return( pDatabase); + if (parentDir) + { + nsCAutoString URI("moz-abmdbdirectory://"); + nsCAutoString leafName; + rv = dbPath->GetNativeLeafName(leafName); + if (NS_FAILED(rv)) { + IMPORT_LOG0( "*** Error: Unable to get name of database file\n"); + } + else { + URI.Append(leafName); + rv = parentDir->CreateDirectoryByURI(name, URI.get (), PR_FALSE); + if (NS_FAILED(rv)) + IMPORT_LOG0( "*** Error: Unable to create address book directory\n"); + } + } + + if (NS_SUCCEEDED(rv)) + IMPORT_LOG0( "Added new address book to the UI\n"); + else + IMPORT_LOG0( "*** Error: An error occurred while adding the address book to the UI\n"); + } + } + + return( pDatabase); } void nsImportGenericAddressBooks::ReportError( PRUnichar *pName, nsString *pStream, nsIStringBundle* aBundle) { - if (!pStream) - return; - // load the error string + if (!pStream) + return; + // load the error string PRUnichar *pFmt = nsImportStringBundle::GetStringByID( IMPORT_ERROR_GETABOOK, aBundle); - PRUnichar *pText = nsTextFormatter::smprintf( pFmt, pName); - pStream->Append( pText); - nsTextFormatter::smprintf_free( pText); - nsCRT::free(pFmt); - pStream->AppendWithConversion( NS_LINEBREAK); + PRUnichar *pText = nsTextFormatter::smprintf( pFmt, pName); + pStream->Append( pText); + nsTextFormatter::smprintf_free( pText); + nsCRT::free(pFmt); + pStream->AppendWithConversion( NS_LINEBREAK); } PR_STATIC_CALLBACK( void) ImportAddressThread( void *stuff) { - IMPORT_LOG0( "In Begin ImportAddressThread\n"); + IMPORT_LOG0( "In Begin ImportAddressThread\n"); - AddressThreadData *pData = (AddressThreadData *)stuff; - PRUint32 count = 0; - nsresult rv = pData->books->Count( &count); - - PRUint32 i; - PRBool import; - PRUint32 size; - nsCOMPtr destDB( getter_AddRefs( GetAddressBookFromUri( pData->pDestinationUri))); - nsCOMPtr pDestDB; - - nsString success; - nsString error; - - nsCOMPtr pBundle; - rv = nsImportStringBundle::GetStringBundleProxy(pData->stringBundle, getter_AddRefs(pBundle)); - if (NS_FAILED(rv)) - { - IMPORT_LOG0("*** ImportMailThread: Unable to obtain proxy string service for the import."); - pData->abort = PR_TRUE; - } - - for (i = 0; (i < count) && !(pData->abort); i++) { - nsCOMPtr book = - do_QueryElementAt(pData->books, i); - if (book) { - import = PR_FALSE; - size = 0; - rv = book->GetImport( &import); - if (import) - rv = book->GetSize( &size); - - if (size && import) { - PRUnichar *pName; - book->GetPreferredName( &pName); - if (destDB) { - pDestDB = destDB; - } - else { - pDestDB = GetAddressBook( pName, PR_TRUE); - } - - nsCOMPtr proxyAddrDatabase; - rv = NS_GetProxyForObject(NS_PROXY_TO_MAIN_THREAD, - NS_GET_IID(nsIAddrDatabase), - pDestDB, - NS_PROXY_SYNC | NS_PROXY_ALWAYS, - getter_AddRefs(proxyAddrDatabase)); - if (NS_FAILED(rv)) - return; - - PRBool fatalError = PR_FALSE; - pData->currentSize = size; - if (proxyAddrDatabase) { - PRUnichar *pSuccess = nsnull; - PRUnichar *pError = nsnull; - - /* - if (pData->fieldMap) { - PRInt32 sz = 0; - PRInt32 mapIndex; - PRBool active; - pData->fieldMap->GetMapSize( &sz); - IMPORT_LOG1( "**** Field Map Size: %d\n", (int) sz); - for (PRInt32 i = 0; i < sz; i++) { - pData->fieldMap->GetFieldMap( i, &mapIndex); - pData->fieldMap->GetFieldActive( i, &active); - IMPORT_LOG3( "Field map #%d: index=%d, active=%d\n", (int) i, (int) mapIndex, (int) active); - } - } - */ - - rv = pData->addressImport->ImportAddressBook( book, - proxyAddrDatabase, // destination - pData->fieldMap, // fieldmap - pData->bAddrLocInput, - &pError, - &pSuccess, - &fatalError); - if (pSuccess) { - success.Append( pSuccess); - nsCRT::free( pSuccess); - } - if (pError) { - error.Append( pError); - nsCRT::free( pError); - } - } - else { + AddressThreadData *pData = (AddressThreadData *)stuff; + PRUint32 count = 0; + nsresult rv = pData->books->Count( &count); + + PRUint32 i; + PRBool import; + PRUint32 size; + nsCOMPtr destDB( getter_AddRefs( GetAddressBookFromUri( pData->pDestinationUri))); + nsCOMPtr pDestDB; + + nsString success; + nsString error; + + nsCOMPtr pBundle; + rv = nsImportStringBundle::GetStringBundleProxy(pData->stringBundle, getter_AddRefs(pBundle)); + if (NS_FAILED(rv)) + { + IMPORT_LOG0("*** ImportMailThread: Unable to obtain proxy string service for the import."); + pData->abort = PR_TRUE; + } + + for (i = 0; (i < count) && !(pData->abort); i++) { + nsCOMPtr book = + do_QueryElementAt(pData->books, i); + if (book) { + import = PR_FALSE; + size = 0; + rv = book->GetImport( &import); + if (import) + rv = book->GetSize( &size); + + if (size && import) { + PRUnichar *pName; + book->GetPreferredName( &pName); + if (destDB) { + pDestDB = destDB; + } + else { + pDestDB = GetAddressBook( pName, PR_TRUE); + } + + nsCOMPtr proxyAddrDatabase; + rv = NS_GetProxyForObject(NS_PROXY_TO_MAIN_THREAD, + NS_GET_IID(nsIAddrDatabase), + pDestDB, + NS_PROXY_SYNC | NS_PROXY_ALWAYS, + getter_AddRefs(proxyAddrDatabase)); + if (NS_FAILED(rv)) + return; + + PRBool fatalError = PR_FALSE; + pData->currentSize = size; + if (proxyAddrDatabase) { + PRUnichar *pSuccess = nsnull; + PRUnichar *pError = nsnull; + + /* + if (pData->fieldMap) { + PRInt32 sz = 0; + PRInt32 mapIndex; + PRBool active; + pData->fieldMap->GetMapSize( &sz); + IMPORT_LOG1( "**** Field Map Size: %d\n", (int) sz); + for (PRInt32 i = 0; i < sz; i++) { + pData->fieldMap->GetFieldMap( i, &mapIndex); + pData->fieldMap->GetFieldActive( i, &active); + IMPORT_LOG3( "Field map #%d: index=%d, active=%d\n", (int) i, (int) mapIndex, (int) active); + } + } + */ + + rv = pData->addressImport->ImportAddressBook( book, + proxyAddrDatabase, // destination + pData->fieldMap, // fieldmap + pData->bAddrLocInput, + &pError, + &pSuccess, + &fatalError); + if (pSuccess) { + success.Append( pSuccess); + nsCRT::free( pSuccess); + } + if (pError) { + error.Append( pError); + nsCRT::free( pError); + } + } + else { nsImportGenericAddressBooks::ReportError(pName, &error, pBundle); - } + } + + nsCRT::free( pName); - nsCRT::free( pName); + pData->currentSize = 0; + pData->currentTotal += size; + + if (!proxyAddrDatabase) { + proxyAddrDatabase->Close( PR_TRUE); + } + + if (fatalError) { + pData->fatalError = PR_TRUE; + break; + } + } + } + + if (destDB) { + destDB->Close( PR_TRUE); + } + } + + + nsImportGenericAddressBooks::SetLogs( success, error, pData->successLog, pData->errorLog); - pData->currentSize = 0; - pData->currentTotal += size; - - if (!proxyAddrDatabase) { - proxyAddrDatabase->Close( PR_TRUE); - } - - if (fatalError) { - pData->fatalError = PR_TRUE; - break; - } - } - } - - if (destDB) { - destDB->Close( PR_TRUE); - } - } - - - nsImportGenericAddressBooks::SetLogs( success, error, pData->successLog, pData->errorLog); - - if (pData->abort || pData->fatalError) { - // FIXME: do what is necessary to get rid of what has been imported so far. - // Nothing if we went into an existing address book! Otherwise, delete - // the ones we created? - } + if (pData->abort || pData->fatalError) { + // FIXME: do what is necessary to get rid of what has been imported so far. + // Nothing if we went into an existing address book! Otherwise, delete + // the ones we created? + } - pData->ThreadDelete(); + pData->ThreadDelete(); } Index: mozilla/mailnews/import/src/nsImportMail.cpp =================================================================== RCS file: /cvsroot/mozilla/mailnews/import/src/nsImportMail.cpp,v retrieving revision 1.64 diff -u -r1.64 mozilla/mailnews/import/src/nsImportMail.cpp --- mozilla/mailnews/import/src/nsImportMail.cpp +++ mozilla/mailnews/import/src/nsImportMail.cpp @@ -184,7 +184,7 @@ return NS_ERROR_OUT_OF_MEMORY; NS_ADDREF( pGen); - nsresult rv = pGen->QueryInterface( NS_GET_IID(nsIImportGeneric), (void **)aImportGeneric); + nsresult rv = CallQueryInterface(pGen, aImportGeneric); NS_RELEASE( pGen); return( rv); @@ -304,12 +304,12 @@ if (!nsCRT::strcasecmp( dataId, "mailInterface")) { NS_IF_RELEASE( m_pInterface); if (item) - item->QueryInterface( NS_GET_IID(nsIImportMail), (void **) &m_pInterface); + CallQueryInterface(item, &m_pInterface); } if (!nsCRT::strcasecmp( dataId, "mailBoxes")) { NS_IF_RELEASE( m_pMailboxes); if (item) - item->QueryInterface( NS_GET_IID(nsISupportsArray), (void **) &m_pMailboxes); + CallQueryInterface(item, &m_pMailboxes); } if (!nsCRT::strcasecmp( dataId, "mailLocation")) { @@ -328,14 +328,14 @@ if (!nsCRT::strcasecmp( dataId, "mailDestination")) { NS_IF_RELEASE( m_pDestFolder); if (item) - item->QueryInterface( NS_GET_IID(nsIMsgFolder), (void **) &m_pDestFolder); + CallQueryInterface(item, &m_pDestFolder); m_deleteDestFolder = PR_FALSE; } if (!nsCRT::strcasecmp( dataId, "name")) { nsCOMPtr nameString; if (item) { - item->QueryInterface( NS_GET_IID(nsISupportsString), getter_AddRefs(nameString)); + nameString = do_QueryInterface(item); rv = nameString->GetData(m_pName); } } @@ -343,7 +343,7 @@ if (!nsCRT::strcasecmp( dataId, "migration")) { nsCOMPtr migrationString; if (item) { - item->QueryInterface( NS_GET_IID(nsISupportsPRBool), getter_AddRefs(migrationString)); + migrationString = do_QueryInterface(item); rv = migrationString->GetData(&m_performingMigration); } } @@ -1069,7 +1069,7 @@ nsCOMPtr subFolder; rv = localRootFolder->GetChildNamed(folderName.get(), getter_AddRefs(subFolder)); if (subFolder) { - subFolder->QueryInterface(NS_GET_IID(nsIMsgFolder), (void **) ppFolder); + CallQueryInterface(subFolder, ppFolder); if (*ppFolder) { IMPORT_LOG1("Folder '%s' created successfully\n", NS_ConvertUTF16toUTF8(folderName).get()); return PR_TRUE; Index: mozilla/mailnews/import/text/src/nsTextImport.cpp =================================================================== RCS file: /cvsroot/mozilla/mailnews/import/text/src/nsTextImport.cpp,v retrieving revision 1.38 diff -u -r1.38 mozilla/mailnews/import/text/src/nsTextImport.cpp --- mozilla/mailnews/import/text/src/nsTextImport.cpp +++ mozilla/mailnews/import/text/src/nsTextImport.cpp @@ -408,7 +408,7 @@ IMPORT_LOG0( "*** Error creating address book descriptor for text import\n"); } else { - rv = array->QueryInterface( NS_GET_IID(nsISupportsArray), (void **) ppArray); + rv = CallQueryInterface(array, ppArray); } return( rv); Index: mozilla/mailnews/local/src/nsLocalMailFolder.cpp =================================================================== RCS file: /cvsroot/mozilla/mailnews/local/src/nsLocalMailFolder.cpp,v retrieving revision 1.530 diff -u -r1.530 mozilla/mailnews/local/src/nsLocalMailFolder.cpp --- mozilla/mailnews/local/src/nsLocalMailFolder.cpp +++ mozilla/mailnews/local/src/nsLocalMailFolder.cpp @@ -1019,8 +1019,7 @@ nsCOMPtr parentFolder; nsCOMPtr thisFolder; - rv = QueryInterface(NS_GET_IID(nsIMsgFolder), (void **) - getter_AddRefs(thisFolder)); + thisFolder = QueryInterface(NS_ISUPPORTS_CAST(nsIMsgFolder*, this), &rv); while (!isServer && thisFolder) { @@ -1741,8 +1740,7 @@ messages->Count(&numMessages); for (PRUint32 i = 0; i < numMessages; i++) { - nsCOMPtr message; - messages->QueryElementAt(i, NS_GET_IID(nsIMsgDBHdr),(void **)getter_AddRefs(message)); + nsCOMPtr message(do_QueryElementAt(messages, i)); if(NS_SUCCEEDED(rv) && message) { nsMsgKey key; @@ -1793,8 +1791,7 @@ msgTxn = new nsLocalMoveCopyMsgTxn; if (msgTxn && NS_SUCCEEDED(msgTxn->Init(srcFolder, this, isMove))) - rv = msgTxn->QueryInterface(NS_GET_IID(nsLocalMoveCopyMsgTxn), - getter_AddRefs(mCopyState->m_undoMsgTxn)); + mCopyState->m_undoMsgTxn = do_QueryInterface(msgTxn, &rv); else { delete msgTxn; @@ -2386,8 +2383,7 @@ PRInt32 messageIndex = (mCopyState->m_copyingMultipleMessages) ? mCopyState->m_curCopyIndex - 1 : mCopyState->m_curCopyIndex; NS_ASSERTION(!mCopyState->m_copyingMultipleMessages || mCopyState->m_curCopyIndex >= 0, "mCopyState->m_curCopyIndex invalid"); // by the time we get here, m_curCopyIndex is 1 relative because WriteStartOfNewMessage increments it - mCopyState->m_messages->QueryElementAt(messageIndex, NS_GET_IID(nsIMsgDBHdr), - (void **)getter_AddRefs(mCopyState->m_message)); + mCopyState->m_message = do_QueryElementAt(mCopyState->m_messages, messageIndex); DisplayMoveCopyStatusMsg(); // if we're copying more than one message, StartMessage will handle this. @@ -2577,9 +2573,8 @@ PRBool multipleCopiesFinished = (mCopyState->m_curCopyIndex >= mCopyState->m_totalMsgCount); if (mCopyState->m_undoMsgTxn) - mCopyState->m_undoMsgTxn->QueryInterface(NS_GET_IID(nsLocalMoveCopyMsgTxn), getter_AddRefs(localUndoTxn)); + localUndoTxn = do_QueryInterface(mCopyState->m_undoMsgTxn); - if (mCopyState) { NS_ASSERTION(mCopyState->m_leftOver == 0, "whoops, something wrong with previous copy"); @@ -2819,7 +2814,7 @@ if (mCopyState->m_undoMsgTxn) { - rv = mCopyState->m_undoMsgTxn->QueryInterface(NS_GET_IID(nsLocalMoveCopyMsgTxn), getter_AddRefs(localUndoTxn)); + localUndoTxn = do_QueryInterface(mCopyState->m_undoMsgTxn, &rv); if (localUndoTxn) localUndoTxn->GetMsgWindow(getter_AddRefs(msgWindow)); } @@ -3455,11 +3450,10 @@ if (mCopyState->m_undoMsgTxn) { - nsRefPtr localUndoTxn; - rv = mCopyState->m_undoMsgTxn->QueryInterface(NS_GET_IID(nsLocalMoveCopyMsgTxn), getter_AddRefs(localUndoTxn)); + nsRefPtr localUndoTxn(do_QueryInterface(mCopyState->m_undoMsgTxn, &rv)); if (NS_SUCCEEDED(rv)) localUndoTxn->GetMsgWindow(getter_AddRefs(msgWindow)); - NS_ASSERTION(msgWindow, "no msg window"); + NS_ASSERTION(msgWindow, "no msg window"); } if (!msgWindow) return NS_OK; // not a fatal error. Index: mozilla/mailnews/local/src/nsMailboxProtocol.cpp =================================================================== RCS file: /cvsroot/mozilla/mailnews/local/src/nsMailboxProtocol.cpp,v retrieving revision 1.126 diff -u -r1.126 mozilla/mailnews/local/src/nsMailboxProtocol.cpp --- mozilla/mailnews/local/src/nsMailboxProtocol.cpp +++ mozilla/mailnews/local/src/nsMailboxProtocol.cpp @@ -172,7 +172,7 @@ nsresult rv = NS_OK; if (aURL) { - rv = aURL->QueryInterface(NS_GET_IID(nsIMailboxUrl), (void **) getter_AddRefs(m_runningUrl)); + m_runningUrl = do_QueryInterface(aURL, &rv); if (NS_SUCCEEDED(rv) && m_runningUrl) { nsCOMPtr window; @@ -484,8 +484,7 @@ nsCOMPtr streamConverter = do_GetService("@mozilla.org/streamConverters;1", &rv); NS_ENSURE_SUCCESS(rv, rv); nsCOMPtr conversionListener; - nsCOMPtr channel; - QueryInterface(NS_GET_IID(nsIChannel), getter_AddRefs(channel)); + nsCOMPtr channel(do_QueryInterface(NS_ISUPPORTS_CAST(nsIChannel*, this))); rv = streamConverter->AsyncConvertData("message/rfc822", "*/*", Index: mozilla/mailnews/local/src/nsMailboxService.cpp =================================================================== RCS file: /cvsroot/mozilla/mailnews/local/src/nsMailboxService.cpp,v retrieving revision 1.124 diff -u -r1.124 mozilla/mailnews/local/src/nsMailboxService.cpp --- mozilla/mailnews/local/src/nsMailboxService.cpp +++ mozilla/mailnews/local/src/nsMailboxService.cpp @@ -162,7 +162,7 @@ } } if (aURL) - mailboxurl->QueryInterface(NS_GET_IID(nsIURI), (void **) aURL); + CallQueryInterface(mailboxurl, aURL); return rv; } @@ -270,8 +270,8 @@ rv = RunMailboxUrl(url, aDisplayConsumer); if (aURL && mailboxurl) - mailboxurl->QueryInterface(NS_GET_IID(nsIURI), (void **) aURL); - + CallQueryInterface(mailboxurl, aURL); + return rv; } @@ -386,8 +386,8 @@ } if (aURL) - mailboxurl->QueryInterface(NS_GET_IID(nsIURI), (void **) aURL); - + CallQueryInterface(mailboxurl, aURL); + return rv; } @@ -401,7 +401,7 @@ nsCOMPtr mailboxurl; rv = PrepareMessageUrl(aMessageURI, nsnull, nsIMailboxUrl::ActionFetchMessage, getter_AddRefs(mailboxurl), aMsgWindow); if (NS_SUCCEEDED(rv) && mailboxurl) - rv = mailboxurl->QueryInterface(NS_GET_IID(nsIURI), (void **) aURL); + rv = CallQueryInterface(mailboxurl, aURL); return rv; } @@ -574,7 +574,7 @@ delete protocol; return rv; } - rv = protocol->QueryInterface(NS_GET_IID(nsIChannel), (void **) _retval); + rv = CallQueryInterface(protocol, _retval); } else rv = NS_ERROR_NULL_POINTER; @@ -619,7 +619,7 @@ rv = rdf->GetResource(folderURI, getter_AddRefs(res)); NS_ENSURE_SUCCESS(rv,rv); - rv = res->QueryInterface(NS_GET_IID(nsIMsgFolder), (void **) aFolder); + rv = CallQueryInterface(res, aFolder); NS_ENSURE_SUCCESS(rv,rv); return NS_OK; Index: mozilla/mailnews/local/src/nsPop3IncomingServer.cpp =================================================================== RCS file: /cvsroot/mozilla/mailnews/local/src/nsPop3IncomingServer.cpp,v retrieving revision 1.88 diff -u -r1.88 mozilla/mailnews/local/src/nsPop3IncomingServer.cpp --- mozilla/mailnews/local/src/nsPop3IncomingServer.cpp +++ mozilla/mailnews/local/src/nsPop3IncomingServer.cpp @@ -491,8 +491,7 @@ { nsPop3GetMailChainer *getMailChainer = new nsPop3GetMailChainer; getMailChainer->AddRef(); // this object owns itself and releases when done. - nsCOMPtr supports; - this->QueryInterface(NS_GET_IID(nsISupports), getter_AddRefs(supports)); + nsCOMPtr supports(do_QueryInterface(NS_ISUPPORTS_CAST(nsIPop3IncomingServer*, this))); deferredServers->InsertElementAt(supports, 0); rv = getMailChainer->GetNewMailForServers(deferredServers, aMsgWindow, inbox, aUrlListener); } Index: mozilla/mailnews/local/src/nsPop3Service.cpp =================================================================== RCS file: /cvsroot/mozilla/mailnews/local/src/nsPop3Service.cpp,v retrieving revision 1.111 diff -u -r1.111 mozilla/mailnews/local/src/nsPop3Service.cpp --- mozilla/mailnews/local/src/nsPop3Service.cpp +++ mozilla/mailnews/local/src/nsPop3Service.cpp @@ -195,7 +195,7 @@ pop3Url->SetPop3Sink(pop3Sink); - rv = pop3Url->QueryInterface(NS_GET_IID(nsIURI), (void **) aUrl); + rv = CallQueryInterface(pop3Url, aUrl); NS_ENSURE_SUCCESS(rv,rv); (*aUrl)->SetSpec(nsDependentCString(urlSpec)); @@ -439,7 +439,7 @@ protocol->SetUsername(realUserName.get()); } } - rv = protocol->QueryInterface(NS_GET_IID(nsIChannel), (void **) _retval); + rv = CallQueryInterface(protocol, _retval); } else rv = NS_ERROR_NULL_POINTER; @@ -509,6 +509,9 @@ nsPop3Service::GetServerIID(nsIID* *aServerIID) { *aServerIID = new nsIID(NS_GET_IID(nsIPop3IncomingServer)); + if (!*aServerIID) + return NS_ERROR_OUT_OF_MEMORY; + return NS_OK; } Index: mozilla/mailnews/mime/src/nsMsgHeaderParser.cpp =================================================================== RCS file: /cvsroot/mozilla/mailnews/mime/src/nsMsgHeaderParser.cpp,v retrieving revision 1.59 diff -u -r1.59 mozilla/mailnews/mime/src/nsMsgHeaderParser.cpp --- mozilla/mailnews/mime/src/nsMsgHeaderParser.cpp +++ mozilla/mailnews/mime/src/nsMsgHeaderParser.cpp @@ -404,16 +404,14 @@ { /* note this new macro for assertions...they can take a string describing the assertion */ NS_PRECONDITION(nsnull != aInstancePtrResult, "nsnull ptr"); - if (nsnull != aInstancePtrResult) - { - nsMsgHeaderParser* parser = new nsMsgHeaderParser(); - if (parser) - return parser->QueryInterface(NS_GET_IID(nsIMsgHeaderParser), (void **)aInstancePtrResult); - else - return NS_ERROR_OUT_OF_MEMORY; /* we couldn't allocate the object */ - } - else + if (!aInstancePtrResult) return NS_ERROR_NULL_POINTER; /* aInstancePtrResult was NULL....*/ + + nsMsgHeaderParser* parser = new nsMsgHeaderParser(); + if (!parser) + return NS_ERROR_OUT_OF_MEMORY; /* we couldn't allocate the object */ + + return CallQueryInterface(parser, aInstancePtrResult); } @@ -1044,7 +1042,7 @@ if (preserveIntegrity) { const char * open_quote = nsnull; - const char * comma = nsnull;; + const char * comma = nsnull; const char * at_sign = nsnull; const char * readPos = line + 1; Index: mozilla/mailnews/news/src/nsNNTPProtocol.cpp =================================================================== RCS file: /cvsroot/mozilla/mailnews/news/src/nsNNTPProtocol.cpp,v retrieving revision 1.377 diff -u -r1.377 mozilla/mailnews/news/src/nsNNTPProtocol.cpp --- mozilla/mailnews/news/src/nsNNTPProtocol.cpp +++ mozilla/mailnews/news/src/nsNNTPProtocol.cpp @@ -734,8 +734,7 @@ if (converter && aConsumer) { nsCOMPtr newConsumer; - nsCOMPtr channel; - QueryInterface(NS_GET_IID(nsIChannel), getter_AddRefs(channel)); + nsCOMPtr channel(do_QueryInterface(NS_ISUPPORTS_CAST(nsIChannel *, this))); converter->AsyncConvertData("message/rfc822", "*/*", aConsumer, channel, getter_AddRefs(newConsumer)); if (newConsumer) @@ -5382,7 +5381,7 @@ nsresult rv = NS_ERROR_NULL_POINTER; NS_ENSURE_ARG_POINTER(aFolder); if (m_newsFolder) - rv = m_newsFolder->QueryInterface(NS_GET_IID(nsIMsgFolder), (void **) aFolder); + rv = CallQueryInterface(m_newsFolder, aFolder); return rv; } Index: mozilla/mailnews/news/src/nsNewsFolder.cpp =================================================================== RCS file: /cvsroot/mozilla/mailnews/news/src/nsNewsFolder.cpp,v retrieving revision 1.273 diff -u -r1.273 mozilla/mailnews/news/src/nsNewsFolder.cpp --- mozilla/mailnews/news/src/nsNewsFolder.cpp +++ mozilla/mailnews/news/src/nsNewsFolder.cpp @@ -134,26 +134,7 @@ PR_Free(mGroupPassword); } -NS_IMPL_ADDREF_INHERITED(nsMsgNewsFolder, nsMsgDBFolder) -NS_IMPL_RELEASE_INHERITED(nsMsgNewsFolder, nsMsgDBFolder) - -NS_IMETHODIMP nsMsgNewsFolder::QueryInterface(REFNSIID aIID, void** aInstancePtr) -{ - if (!aInstancePtr) return NS_ERROR_NULL_POINTER; - *aInstancePtr = nsnull; - if (aIID.Equals(NS_GET_IID(nsIMsgNewsFolder))) - { - *aInstancePtr = NS_STATIC_CAST(nsIMsgNewsFolder*, this); - } - - if(*aInstancePtr) - { - AddRef(); - return NS_OK; - } - - return nsMsgDBFolder::QueryInterface(aIID, aInstancePtr); -} +NS_IMPL_ISUPPORTS_INHERITED1(nsMsgNewsFolder, nsIMsgNewsFolder, nsMsgDBFolder) //////////////////////////////////////////////////////////////////////////////// @@ -1651,9 +1632,7 @@ if (!server) return NS_ERROR_NULL_POINTER; - nsCOMPtr nntpServer; - rv = server->QueryInterface(NS_GET_IID(nsINntpIncomingServer), - getter_AddRefs(nntpServer)); + nsCOMPtr nntpServer(do_QueryInterface(server, &rv)); if (NS_FAILED(rv)) return rv; Index: mozilla/mailnews/news/src/nsNntpIncomingServer.cpp =================================================================== RCS file: /cvsroot/mozilla/mailnews/news/src/nsNntpIncomingServer.cpp,v retrieving revision 1.159 diff -u -r1.159 mozilla/mailnews/news/src/nsNntpIncomingServer.cpp --- mozilla/mailnews/news/src/nsNntpIncomingServer.cpp +++ mozilla/mailnews/news/src/nsNntpIncomingServer.cpp @@ -545,7 +545,7 @@ if (!protocolInstance) return NS_ERROR_OUT_OF_MEMORY; - nsresult rv = protocolInstance->QueryInterface(NS_GET_IID(nsINNTPProtocol), (void **) aNntpConnection); + nsresult rv = CallQueryInterface(protocolInstance, aNntpConnection); // take the protocol instance and add it to the connectionCache if (NS_SUCCEEDED(rv) && *aNntpConnection) m_connectionCache->AppendElement(*aNntpConnection); @@ -724,8 +724,7 @@ rv = mGroupsEnumerator->GetNext(aFirstGroupNeedingCounts); if (NS_FAILED(rv)) return rv; if (!*aFirstGroupNeedingCounts) return NS_ERROR_FAILURE; - nsCOMPtr folder; - (*aFirstGroupNeedingCounts)->QueryInterface(NS_GET_IID(nsIMsgFolder), getter_AddRefs(folder)); + nsCOMPtr folder(do_QueryInterface(*aFirstGroupNeedingCounts)); PRUint32 folderFlags; folder->GetFlags(&folderFlags); if (folderFlags & MSG_FOLDER_FLAG_VIRTUAL) @@ -1607,7 +1606,7 @@ NS_ENSURE_SUCCESS(rv,rv); if (!subFolder) return NS_ERROR_FAILURE; - rv = subFolder->QueryInterface(NS_GET_IID(nsIMsgNewsFolder), (void**)result); + rv = CallQueryInterface(subFolder, result); NS_ENSURE_SUCCESS(rv,rv); if (!*result) return NS_ERROR_FAILURE; return NS_OK; Index: mozilla/modules/libjar/nsJARURI.cpp =================================================================== RCS file: /cvsroot/mozilla/modules/libjar/nsJARURI.cpp,v retrieving revision 1.54 diff -u -r1.54 mozilla/modules/libjar/nsJARURI.cpp --- mozilla/modules/libjar/nsJARURI.cpp +++ mozilla/modules/libjar/nsJARURI.cpp @@ -268,18 +268,22 @@ if (!aBaseURL) return NS_ERROR_MALFORMED_URI; - nsRefPtr otherJAR; - aBaseURL->QueryInterface(NS_GET_IID(nsJARURI), getter_AddRefs(otherJAR)); + nsCOMPtr otherJAR(do_QueryInterface(aBaseURL)); NS_ENSURE_TRUE(otherJAR, NS_NOINTERFACE); - mJARFile = otherJAR->mJARFile; + rv = otherJAR->GetJARFile(getter_AddRefs(mJARFile)); + /* we're not checking this! */ + + nsCString JAREntry; + rv = otherJAR->GetJAREntry(JAREntry); + /* we're not checking this! */ nsCOMPtr entry(do_CreateInstance(NS_STANDARDURL_CONTRACTID)); if (!entry) return NS_ERROR_OUT_OF_MEMORY; rv = entry->Init(nsIStandardURL::URLTYPE_NO_AUTHORITY, -1, - aSpec, mCharsetHint.get(), otherJAR->mJAREntry); + aSpec, mCharsetHint.get(), JAREntry); if (NS_FAILED(rv)) return rv; @@ -465,13 +469,17 @@ if (other == nsnull) return NS_OK; // not equal - nsRefPtr otherJAR; - other->QueryInterface(NS_GET_IID(nsJARURI), getter_AddRefs(otherJAR)); - if (!otherJAR) - return NS_OK; // not equal + nsCOMPtr otherJAR(do_QueryInterface(aBaseURL)); + if (!otherJAR) return NS_OK; + + nsCOMPtr jarFile; + rv = otherJAR->GetJARFile(getter_AddRefs(jarFile)); + + nsCString jarEntry; + rv = otherJAR->GetJAREntry(jarEntry); PRBool equal; - rv = mJARFile->Equals(otherJAR->mJARFile, &equal); + rv = mJARFile->Equals(jarFile, &equal); if (NS_FAILED(rv) || !equal) { return rv; // not equal } Index: mozilla/modules/oji/src/lcglue.cpp =================================================================== RCS file: /cvsroot/mozilla/modules/oji/src/lcglue.cpp,v retrieving revision 1.60 diff -u -r1.60 mozilla/modules/oji/src/lcglue.cpp --- mozilla/modules/oji/src/lcglue.cpp +++ mozilla/modules/oji/src/lcglue.cpp @@ -134,7 +134,7 @@ nsIPluginInstancePeer* pluginPeer = NULL; if (pluginInstance->GetPeer(&pluginPeer) == NS_OK) { nsIPluginInstancePeer2* pluginPeer2 = NULL; - if (pluginPeer->QueryInterface(NS_GET_IID(nsIPluginInstancePeer2), (void**) &pluginPeer2) == NS_OK) { + if (NS_SUCCEEDED(CallQueryInterface(pluginPeer, &pluginPeer2))) { pluginPeer2->GetJSContext(&context); NS_RELEASE(pluginPeer2); } @@ -222,7 +222,7 @@ nsIPluginInstancePeer* pluginPeer; if (pluginInstance->GetPeer(&pluginPeer) == NS_OK) { nsIJVMPluginTagInfo* tagInfo; - if (pluginPeer->QueryInterface(NS_GET_IID(nsIJVMPluginTagInfo), (void**) &tagInfo) == NS_OK) { + if (NS_SUCCEEDED(CallQueryInterface(pluginPeer, &tagInfo))) { err = tagInfo->GetMayScript(&mayscript); // PR_ASSERT(err != NS_OK ? mayscript == PR_FALSE : PR_TRUE); NS_RELEASE(tagInfo); @@ -231,8 +231,7 @@ *errp = strdup("JSObject.getWindow() requires mayscript attribute on this Applet"); } else { nsIPluginInstancePeer2* pluginPeer2 = nsnull; - if (pluginPeer->QueryInterface(NS_GET_IID(nsIPluginInstancePeer2), - (void**) &pluginPeer2) == NS_OK) { + if (NS_SUCCEEDED(CallQueryInterface(pluginPeer, &pluginPeer2))) { err = pluginPeer2->GetJSWindow(&window); NS_RELEASE(pluginPeer2); } Index: mozilla/modules/plugin/samples/SanePlugin/nsSanePlugin.cpp =================================================================== RCS file: /cvsroot/mozilla/modules/plugin/samples/SanePlugin/nsSanePlugin.cpp,v retrieving revision 1.16 diff -u -r1.16 mozilla/modules/plugin/samples/SanePlugin/nsSanePlugin.cpp --- mozilla/modules/plugin/samples/SanePlugin/nsSanePlugin.cpp +++ mozilla/modules/plugin/samples/SanePlugin/nsSanePlugin.cpp @@ -204,9 +204,7 @@ if ( NS_FAILED( result ) ) return result; - result = peer->QueryInterface( NS_GET_IID(nsIPluginTagInfo), - ( void ** )&taginfo ); - + result = CallQueryInterface(peer, &tagInfo)); if ( NS_SUCCEEDED( result ) ) { taginfo->GetAttributes( count, names, values ); @@ -1683,7 +1681,7 @@ *aImageParameters = nsnull; - rv = OpenSaneDeviceIF();; + rv = OpenSaneDeviceIF(); if (rv != NS_OK) return rv; Index: mozilla/modules/plugin/samples/backward/badapter.cpp =================================================================== RCS file: /cvsroot/mozilla/modules/plugin/samples/backward/badapter.cpp,v retrieving revision 1.40 diff -u -r1.40 mozilla/modules/plugin/samples/backward/badapter.cpp --- mozilla/modules/plugin/samples/backward/badapter.cpp +++ mozilla/modules/plugin/samples/backward/badapter.cpp @@ -1105,7 +1105,7 @@ } nsIPluginInstance* inst = NULL; - nsresult rslt = pluginInst->QueryInterface(NS_GET_IID(nsIPluginInstance), (void**)&inst); + nsresult rslt = CallQueryInterface(pluginInst, &inst); if (rslt != NS_OK) return rslt; CPluginInstancePeer* instancePeer = NULL; rslt = inst->GetPeer((nsIPluginInstancePeer**)&instancePeer); @@ -1155,7 +1155,7 @@ } nsIPluginInstance* inst = NULL; - nsresult rslt = pluginInst->QueryInterface(NS_GET_IID(nsIPluginInstance), (void**)&inst); + nsresult rslt = CallQueryInterface(pluginInst, &inst); if (rslt != NS_OK) return rslt; CPluginInstancePeer* instancePeer = NULL; rslt = inst->GetPeer((nsIPluginInstancePeer**)&instancePeer); @@ -1331,30 +1331,12 @@ NS_IMPL_ADDREF(CPluginManager) NS_IMPL_RELEASE(CPluginManager) -NS_METHOD -CPluginManager::QueryInterface(const nsIID& iid, void** ptr) -{ - if (NULL == ptr) { - return NS_ERROR_NULL_POINTER; - } - - if (iid.Equals(NS_GET_IID(nsIServiceManager))) { - *ptr = (void*) (nsIServiceManager*)this; - AddRef(); - return NS_OK; - } - if (iid.Equals(NS_GET_IID(nsIAllocator))) { - *ptr = (void*) (nsIAllocator*)this; - AddRef(); - return NS_OK; - } - if (iid.Equals(NS_GET_IID(nsIPluginManager)) || iid.Equals(NS_GET_IID(nsISupports))) { - *ptr = (void*) ((nsIPluginManager*)this); - AddRef(); - return NS_OK; - } - return NS_NOINTERFACE; -} +NS_INTERFACE_MAP_BEGIN(CPluginManager) + NS_INTERFACE_MAP_ENTRY(nsIServiceManager) + NS_INTERFACE_MAP_ENTRY(nsIAllocator) + NS_INTERFACE_MAP_ENTRY(nsIPluginManager) + NS_INTERFACE_MAP_ENTRY(nsISupports) +NS_INTERFACE_MAP_END ////////////////////////////////////////////////////////////////////////////// // @@ -1587,25 +1569,11 @@ NS_IMPL_ADDREF(CPluginInstancePeer) NS_IMPL_RELEASE(CPluginInstancePeer) -NS_METHOD -CPluginInstancePeer::QueryInterface(const nsIID& iid, void** ptr) -{ - if (NULL == ptr) { - return NS_ERROR_NULL_POINTER; - } - - if (iid.Equals(NS_GET_IID(nsIPluginInstancePeer))) { - *ptr = (void*) this; - AddRef(); - return NS_OK; - } - if (iid.Equals(NS_GET_IID(nsIPluginTagInfo)) || iid.Equals(NS_GET_IID(nsISupports))) { - *ptr = (void*) ((nsIPluginTagInfo*)this); - AddRef(); - return NS_OK; - } - return NS_NOINTERFACE; -} +NS_INTERFACE_MAP_BEGIN(CPluginInstancePeer) + NS_INTERFACE_MAP_ENTRY(nsIPluginInstancePeer) + NS_INTERFACE_MAP_ENTRY(nsIPluginTagInfo) + NS_INTERFACE_MAP_ENTRY(nsISupports) +NS_INTERFACE_MAP_END ////////////////////////////////////////////////////////////////////////////// // Index: mozilla/modules/plugin/samples/default/os2/plugin.cpp =================================================================== RCS file: /cvsroot/mozilla/modules/plugin/samples/default/os2/plugin.cpp,v retrieving revision 1.15 diff -u -r1.15 mozilla/modules/plugin/samples/default/os2/plugin.cpp --- mozilla/modules/plugin/samples/default/os2/plugin.cpp +++ mozilla/modules/plugin/samples/default/os2/plugin.cpp @@ -212,7 +212,7 @@ // do a QI on the service manager we get back to ensure it's the one we are expecting if(sm) { - sm->QueryInterface(NS_GET_IID(nsIServiceManager), (void**)&gServiceManager); + CallQueryInterface(sm, &gServiceManager); NS_RELEASE(sm); } Index: mozilla/modules/plugin/samples/default/windows/plugin.cpp =================================================================== RCS file: /cvsroot/mozilla/modules/plugin/samples/default/windows/plugin.cpp,v retrieving revision 1.19 diff -u -r1.19 mozilla/modules/plugin/samples/default/windows/plugin.cpp --- mozilla/modules/plugin/samples/default/windows/plugin.cpp +++ mozilla/modules/plugin/samples/default/windows/plugin.cpp @@ -227,7 +227,7 @@ // do a QI on the service manager we get back to ensure it's the one we are expecting if(sm) { - sm->QueryInterface(NS_GET_IID(nsIServiceManager), (void**)&gServiceManager); + CallQueryInterface(sm, &gServiceManager); NS_RELEASE(sm); } Index: mozilla/modules/plugin/samples/simple/npsimple.cpp =================================================================== RCS file: /cvsroot/mozilla/modules/plugin/samples/simple/npsimple.cpp,v retrieving revision 1.46 diff -u -r1.46 mozilla/modules/plugin/samples/simple/npsimple.cpp --- mozilla/modules/plugin/samples/simple/npsimple.cpp +++ mozilla/modules/plugin/samples/simple/npsimple.cpp @@ -415,10 +415,12 @@ NS_METHOD SimplePluginInstance::GetScriptableInterface(nsIID **aScriptableInterface) { - *aScriptableInterface = (nsIID *)nsMemory::Alloc(sizeof(nsIID)); - NS_ENSURE_TRUE(*aScriptableInterface, NS_ERROR_OUT_OF_MEMORY); + *aScriptableInterface = + (nsIID *)nsMemory::Clone(NS_GET_IID(nsISimplePluginInstance), + sizeof(nsIID)); - **aScriptableInterface = NS_GET_IID(nsISimplePluginInstance); + if (!*aScriptableInterface) + return NS_ERROR_OUT_OF_MEMORY; return NS_OK; } @@ -455,8 +457,7 @@ nsresult rv; nsIServiceManager *svcMgr; - rv = aCompMgr->QueryInterface(NS_GET_IID(nsIServiceManager), - NS_REINTERPRET_CAST(void**, &svcMgr)); + rv = CallQueryInterface(aCompMgr, &svcMgr); if (NS_FAILED(rv)) return rv; @@ -491,8 +492,7 @@ nsresult rv; nsIServiceManager *svcMgr; - rv = aCompMgr->QueryInterface(NS_GET_IID(nsIServiceManager), - NS_REINTERPRET_CAST(void**, &svcMgr)); + rv = CallQueryInterface(aCompMgr, &svcMgr); if (NS_FAILED(rv)) return rv; @@ -568,7 +568,8 @@ result = peer->GetMode(&fMode); if (NS_FAILED(result)) return result; - result = peer->QueryInterface(NS_GET_IID(nsIPluginTagInfo), (void **)&taginfo); + result = CallQueryInterface(peer, &taginfo); + if (NS_SUCCEEDED(result)) { Index: mozilla/modules/plugin/samples/testevents/npevents.cpp =================================================================== RCS file: /cvsroot/mozilla/modules/plugin/samples/testevents/npevents.cpp,v retrieving revision 1.15 diff -u -r1.15 mozilla/modules/plugin/samples/testevents/npevents.cpp --- mozilla/modules/plugin/samples/testevents/npevents.cpp +++ mozilla/modules/plugin/samples/testevents/npevents.cpp @@ -304,8 +304,7 @@ nsresult rv; nsIServiceManager *svcMgr; - rv = aCompMgr->QueryInterface(NS_GET_IID(nsIServiceManager), - NS_REINTERPRET_CAST(void**, &svcMgr)); + rv = CallQueryInterface(aCompMgr, &svcMgr); if (NS_FAILED(rv)) return rv; @@ -340,8 +339,7 @@ nsresult rv; nsIServiceManager *svcMgr; - rv = aCompMgr->QueryInterface(NS_GET_IID(nsIServiceManager), - NS_REINTERPRET_CAST(void**, &svcMgr)); + rv = CallQueryInterface(aCompMgr, &svcMgr); if (NS_FAILED(rv)) return rv; Index: mozilla/modules/plugin/tools/sdk/samples/simple/plugin.cpp =================================================================== RCS file: /cvsroot/mozilla/modules/plugin/tools/sdk/samples/simple/plugin.cpp,v retrieving revision 1.12 diff -u -r1.12 mozilla/modules/plugin/tools/sdk/samples/simple/plugin.cpp --- mozilla/modules/plugin/tools/sdk/samples/simple/plugin.cpp +++ mozilla/modules/plugin/tools/sdk/samples/simple/plugin.cpp @@ -91,7 +91,7 @@ // nsISupports here can still be more appropriate in case something is changed // in the future so we don't need to do casting of any sort. if(sm) { - sm->QueryInterface(NS_GET_IID(nsIServiceManager), (void**)&gServiceManager); + CallQueryInterface(sm, &gServiceManager); NS_RELEASE(sm); } Index: mozilla/netwerk/streamconv/test/Converters.cpp =================================================================== RCS file: /cvsroot/mozilla/netwerk/streamconv/test/Converters.cpp,v retrieving revision 1.24 diff -u -r1.24 mozilla/netwerk/streamconv/test/Converters.cpp --- mozilla/netwerk/streamconv/test/Converters.cpp +++ mozilla/netwerk/streamconv/test/Converters.cpp @@ -145,7 +145,7 @@ if (mClassID.Equals(kTestConverterCID)) { TestConverter *conv = new TestConverter(); if (!conv) return NS_ERROR_OUT_OF_MEMORY; - conv->QueryInterface(NS_GET_IID(nsISupports), (void**)&inst); + CallQueryInterface(conv, &inst); } else { return NS_ERROR_NO_INTERFACE; Index: mozilla/parser/htmlparser/robot/nsDebugRobot.cpp =================================================================== RCS file: /cvsroot/mozilla/parser/htmlparser/robot/nsDebugRobot.cpp,v retrieving revision 1.74 diff -u -r1.74 mozilla/parser/htmlparser/robot/nsDebugRobot.cpp --- mozilla/parser/htmlparser/robot/nsDebugRobot.cpp +++ mozilla/parser/htmlparser/robot/nsDebugRobot.cpp @@ -259,7 +259,7 @@ rv = service->NewURI(uriStr, nsnull, nsnull, &uri); if (NS_FAILED(rv)) return rv; - rv = uri->QueryInterface(NS_GET_IID(nsIURI), (void**)&url); + rv = CallQueryInterface(uri, &url); NS_RELEASE(uri); if (NS_OK != rv) { printf("invalid URL: '"); Index: mozilla/parser/htmlparser/robot/nsRobotSink.cpp =================================================================== RCS file: /cvsroot/mozilla/parser/htmlparser/robot/nsRobotSink.cpp,v retrieving revision 3.64 diff -u -r3.64 mozilla/parser/htmlparser/robot/nsRobotSink.cpp --- mozilla/parser/htmlparser/robot/nsRobotSink.cpp +++ mozilla/parser/htmlparser/robot/nsRobotSink.cpp @@ -293,7 +293,7 @@ nsIURI *uri = nsnull, *baseUri = nsnull; - rv = mDocumentURL->QueryInterface(NS_GET_IID(nsIURI), (void**)&baseUri); + rv = CallQueryInterface(mDocumentURL, &baseUri); if (NS_FAILED(rv)) return; NS_ConvertUTF16toUTF8 uriStr(aLink); @@ -301,7 +301,7 @@ NS_RELEASE(baseUri); if (NS_FAILED(rv)) return; - rv = uri->QueryInterface(NS_GET_IID(nsIURI), (void**)&absurl); + rv = CallQueryInterface(uri, &absurl); NS_RELEASE(uri); if (NS_OK == rv) { Index: mozilla/plugin/oji/MRJ/plugin/Source/BackwardAdapter.cpp =================================================================== RCS file: /cvsroot/mozilla/plugin/oji/MRJ/plugin/Source/BackwardAdapter.cpp,v retrieving revision 1.45 diff -u -r1.45 mozilla/plugin/oji/MRJ/plugin/Source/BackwardAdapter.cpp --- mozilla/plugin/oji/MRJ/plugin/Source/BackwardAdapter.cpp +++ mozilla/plugin/oji/MRJ/plugin/Source/BackwardAdapter.cpp @@ -1128,7 +1128,7 @@ jref pluginClass = NULL; if (thePlugin != NULL) { nsIJRILiveConnectPlugin* jriPlugin = NULL; - if (thePlugin->QueryInterface(NS_GET_IID(nsIJRILiveConnectPlugin), (void**)&jriPlugin) == NS_OK) { + if (NS_SUCCEEDED(CallQueryInterface(thePlugin, &jriPlugin))) { jriPlugin->GetJavaClass(NPN_GetJavaEnv(), &pluginClass); NS_RELEASE(jriPlugin); } @@ -1531,7 +1531,7 @@ } nsIPluginInstance* inst = NULL; - nsresult rslt = pluginInst->QueryInterface(NS_GET_IID(nsIPluginInstance), (void**)&inst); + nsresult rslt = CallQueryInterface(pluginInst, &inst); if (rslt != NS_OK) return rslt; CPluginInstancePeer* instancePeer = NULL; rslt = inst->GetPeer((nsIPluginInstancePeer**)&instancePeer); @@ -1581,7 +1581,7 @@ } nsIPluginInstance* inst = NULL; - nsresult rslt = pluginInst->QueryInterface(NS_GET_IID(nsIPluginInstance), (void**)&inst); + nsresult rslt = CallQueryInterface(pluginInst, &inst); if (rslt != NS_OK) return rslt; CPluginInstancePeer* instancePeer = NULL; rslt = inst->GetPeer((nsIPluginInstancePeer**)&instancePeer); @@ -2015,35 +2015,13 @@ // nsISupports methods //+++++++++++++++++++++++++++++++++++++++++++++++++ -NS_METHOD -CPluginManager::QueryInterface(const nsIID& iid, void** ptr) -{ - if (NULL == ptr) { - return NS_ERROR_NULL_POINTER; - } - - if (iid.Equals(NS_GET_IID(nsIPluginManager)) || iid.Equals(NS_GET_IID(nsIPluginManager2))) { - *ptr = (void*) ((nsIPluginManager2*)this); - AddRef(); - return NS_OK; - } - if (iid.Equals(NS_GET_IID(nsIServiceManager))) { - *ptr = (void*) (nsIServiceManager*)this; - AddRef(); - return NS_OK; - } - if (iid.Equals(NS_GET_IID(nsIMemory))) { - *ptr = (void*) (nsIMemory*)this; - AddRef(); - return NS_OK; - } - if (iid.Equals(NS_GET_IID(nsISupports))) { - *ptr = (void*) this; - AddRef(); - return NS_OK; - } - return NS_NOINTERFACE; -} +NS_INTERFACE_MAP_BEGIN(CPluginManager) + NS_INTERFACE_MAP_ENTRY(nsIPluginManager) + NS_INTERFACE_MAP_ENTRY(nsIPluginManager2) + NS_INTERFACE_MAP_ENTRY(nsIServiceManager) + NS_INTERFACE_MAP_ENTRY(nsIMemory) + NS_INTERFACE_MAP_ENTRY(nsISupports)) +NS_INTERFACE_MAP_END NS_IMPL_ADDREF(CPluginManager) NS_IMPL_RELEASE(CPluginManager) @@ -2329,25 +2307,11 @@ NS_IMPL_ADDREF(CPluginInstancePeer) NS_IMPL_RELEASE(CPluginInstancePeer) -NS_METHOD -CPluginInstancePeer::QueryInterface(const nsIID& iid, void** ptr) -{ - if (NULL == ptr) { - return NS_ERROR_NULL_POINTER; - } - - if (iid.Equals(NS_GET_IID(nsIPluginInstancePeer))) { - *ptr = (void*) this; - AddRef(); - return NS_OK; - } - if (iid.Equals(NS_GET_IID(nsIPluginTagInfo)) || iid.Equals(NS_GET_IID(nsISupports))) { - *ptr = (void*) ((nsIPluginTagInfo*)this); - AddRef(); - return NS_OK; - } - return NS_NOINTERFACE; -} +NS_INTERFACE_MAP_BEGIN(CPluginInstancePeer) + NS_INTERFACE_MAP_ENTRY(nsIPluginInstancePeer) + NS_INTERFACE_MAP_ENTRY(nsIPluginTagInfo) + NS_INTERFACE_MAP_ENTRY(nsISupports) +NS_INTERFACE_MAP_END ////////////////////////////////////////////////////////////////////////////// // Index: mozilla/plugin/oji/MRJ/plugin/Source/EmbeddedFramePluginInstance.cpp =================================================================== RCS file: /cvsroot/mozilla/plugin/oji/MRJ/plugin/Source/EmbeddedFramePluginInstance.cpp,v retrieving revision 1.13 diff -u -r1.13 mozilla/plugin/oji/MRJ/plugin/Source/EmbeddedFramePluginInstance.cpp --- mozilla/plugin/oji/MRJ/plugin/Source/EmbeddedFramePluginInstance.cpp +++ mozilla/plugin/oji/MRJ/plugin/Source/EmbeddedFramePluginInstance.cpp @@ -64,7 +64,7 @@ NS_ADDREF(mPeer); nsIPluginTagInfo* tagInfo = NULL; - if (mPeer->QueryInterface(NS_GET_IID(nsIPluginTagInfo), (void **)&tagInfo) == NS_OK) { + if (NS_SUCCEEDED(CallQueryInterface(mPeer, &tagInfo))) { const char* frameValue = NULL; if (tagInfo->GetAttribute("JAVAFRAME", &frameValue) == NS_OK) { sscanf(frameValue, "%X", &mFrame); Index: mozilla/plugin/oji/MRJ/plugin/Source/LiveConnectNativeMethods.cpp =================================================================== RCS file: /cvsroot/mozilla/plugin/oji/MRJ/plugin/Source/LiveConnectNativeMethods.cpp,v retrieving revision 1.34 diff -u -r1.34 mozilla/plugin/oji/MRJ/plugin/Source/LiveConnectNativeMethods.cpp --- mozilla/plugin/oji/MRJ/plugin/Source/LiveConnectNativeMethods.cpp +++ mozilla/plugin/oji/MRJ/plugin/Source/LiveConnectNativeMethods.cpp @@ -365,7 +365,7 @@ nsIPluginInstancePeer* peer; if (pluginInstance->GetPeer(&peer) == NS_OK) { nsIPluginInstancePeer2* peer2 = NULL; - if (peer->QueryInterface(NS_GET_IID(nsIPluginInstancePeer2), (void **)&peer2) == NS_OK) { + if (NS_SUCCEEDED(CallQueryInterface(peer, &peer2))) { if (peer2->GetJSThread(&threadID) != NS_OK) threadID = 0; NS_RELEASE(peer2); Index: mozilla/plugin/oji/MRJ/plugin/Source/MRJContext.cp =================================================================== RCS file: /cvsroot/mozilla/plugin/oji/MRJ/plugin/Source/MRJContext.cp,v retrieving revision 1.32 diff -u -r1.32 mozilla/plugin/oji/MRJ/plugin/Source/MRJContext.cp --- mozilla/plugin/oji/MRJ/plugin/Source/MRJContext.cp +++ mozilla/plugin/oji/MRJ/plugin/Source/MRJContext.cp @@ -35,11 +35,11 @@ * ***** END LICENSE BLOCK ***** */ /* - MRJContext.cp - - Manages Java content using the MacOS Runtime for Java. - - by Patrick C. Beard. + MRJContext.cp + + Manages Java content using the MacOS Runtime for Java. + + by Patrick C. Beard. */ #include @@ -78,20 +78,20 @@ void LocalPort::Enter() { - ::GetPort(&fOldPort); - if (fPort != fOldPort) - ::SetPort(fPort); - fOldOrigin = topLeft(fPort->portRect); - if (fOldOrigin.h != fOrigin.h || fOldOrigin.v != fOrigin.v) - ::SetOrigin(fOrigin.h, fOrigin.v); + ::GetPort(&fOldPort); + if (fPort != fOldPort) + ::SetPort(fPort); + fOldOrigin = topLeft(fPort->portRect); + if (fOldOrigin.h != fOrigin.h || fOldOrigin.v != fOrigin.v) + ::SetOrigin(fOrigin.h, fOrigin.v); } void LocalPort::Exit() { - if (fOldOrigin.h != fOrigin.h || fOldOrigin.v != fOrigin.v) - ::SetOrigin(fOldOrigin.h, fOldOrigin.v); - if (fOldPort != fPort) - ::SetPort(fOldPort); + if (fOldOrigin.h != fOrigin.h || fOldOrigin.v != fOrigin.v) + ::SetOrigin(fOldOrigin.h, fOldOrigin.v); + if (fOldPort != fPort) + ::SetPort(fOldPort); } static RgnHandle NewEmptyRgn() @@ -102,31 +102,31 @@ } MRJContext::MRJContext(MRJSession* session, MRJPluginInstance* instance) - : mPluginInstance(instance), mSession(session), mSessionRef(session->getSessionRef()), mPeer(NULL), - mLocator(NULL), mContext(NULL), mViewer(NULL), mViewerFrame(NULL), mIsActive(false), - mPluginWindow(NULL), mPluginClipping(NULL), mPluginPort(NULL), - mDocumentBase(NULL), mAppletHTML(NULL), mPage(NULL), mSecurityContext(NULL) -{ - instance->GetPeer(&mPeer); - - // we cache attributes of the window, and periodically notice when they change. - mCachedOrigin.x = mCachedOrigin.y = -1; + : mPluginInstance(instance), mSession(session), mSessionRef(session->getSessionRef()), mPeer(NULL), + mLocator(NULL), mContext(NULL), mViewer(NULL), mViewerFrame(NULL), mIsActive(false), + mPluginWindow(NULL), mPluginClipping(NULL), mPluginPort(NULL), + mDocumentBase(NULL), mAppletHTML(NULL), mPage(NULL), mSecurityContext(NULL) +{ + instance->GetPeer(&mPeer); + + // we cache attributes of the window, and periodically notice when they change. + mCachedOrigin.x = mCachedOrigin.y = -1; ::SetRect((Rect*)&mCachedClipRect, 0, 0, 0, 0); - mPluginClipping =::NewEmptyRgn(); - mPluginPort = getEmptyPort(); + mPluginClipping =::NewEmptyRgn(); + mPluginPort = getEmptyPort(); } MRJContext::~MRJContext() { - if (mLocator != NULL) { - JMDisposeAppletLocator(mLocator); - mLocator = NULL; - } - - if (mViewer != NULL) { - ::JMDisposeAppletViewer(mViewer); - mViewer = NULL; - } + if (mLocator != NULL) { + JMDisposeAppletLocator(mLocator); + mLocator = NULL; + } + + if (mViewer != NULL) { + ::JMDisposeAppletViewer(mViewer); + mViewer = NULL; + } // hack: see if this allows the applet viewer to terminate gracefully. // Re-enable. Else if opened a new window thru Java and then quit browser, @@ -136,84 +136,84 @@ for (int i = 0; i < 100; i++) ::JMIdle(mSessionRef, kDefaultJMTime); - if (mContext != NULL) { - // hack: release any frames that we still see in the AWT context, before tossing it. - releaseFrames(); - - ::JMDisposeAWTContext(mContext); - mContext = NULL; - } - - if (mPeer != NULL) { - mPeer->Release(); - mPeer = NULL; - } - - if (mPage != NULL) { - mPage->Release(); - mPage = NULL; - } - - if (mPluginClipping != NULL) { - ::DisposeRgn(mPluginClipping); - mPluginClipping = NULL; - } - - if (mDocumentBase != NULL) { - delete[] mDocumentBase; - mDocumentBase = NULL; - } - - if (mAppletHTML != NULL) { - delete[] mAppletHTML; - mAppletHTML = NULL; - } - - if (mSecurityContext != NULL) { - mSecurityContext->Release(); - mSecurityContext = NULL; - } + if (mContext != NULL) { + // hack: release any frames that we still see in the AWT context, before tossing it. + releaseFrames(); + + ::JMDisposeAWTContext(mContext); + mContext = NULL; + } + + if (mPeer != NULL) { + mPeer->Release(); + mPeer = NULL; + } + + if (mPage != NULL) { + mPage->Release(); + mPage = NULL; + } + + if (mPluginClipping != NULL) { + ::DisposeRgn(mPluginClipping); + mPluginClipping = NULL; + } + + if (mDocumentBase != NULL) { + delete[] mDocumentBase; + mDocumentBase = NULL; + } + + if (mAppletHTML != NULL) { + delete[] mAppletHTML; + mAppletHTML = NULL; + } + + if (mSecurityContext != NULL) { + mSecurityContext->Release(); + mSecurityContext = NULL; + } } static char* slashify(char* url) { - int len = ::strlen(url); - if (url[len - 1] != '/') { - char* newurl = new char[len + 2]; - ::strcpy(newurl, url); - newurl[len] = '/'; - newurl[len + 1] = '\0'; - delete[] url; - url = newurl; - } - return url; + int len = ::strlen(url); + if (url[len - 1] != '/') { + char* newurl = new char[len + 2]; + ::strcpy(newurl, url); + newurl[len] = '/'; + newurl[len + 1] = '\0'; + delete[] url; + url = newurl; + } + return url; } static bool isAppletAttribute(const char* name) { - // this table must be kept in alphabetical order. - static const char* kAppletAttributes[] = { - "ALIGN", "ALT", "ARCHIVE", - "CODE", "CODEBASE", - "HEIGHT", "HSPACE", - "MAYSCRIPT", "NAME", "OBJECT", - "VSPACE", "WIDTH" - }; - int length = sizeof(kAppletAttributes) / sizeof(char*); - int minIndex = 0, maxIndex = length - 1; - int index = maxIndex / 2; - while (minIndex <= maxIndex) { - int diff = strcasecmp(name, kAppletAttributes[index]); - if (diff < 0) { - maxIndex = (index - 1); - index = (minIndex + maxIndex) / 2; - } else if (diff > 0) { - minIndex = (index + 1); - index = (minIndex + maxIndex) / 2; - } else { + // this table must be kept in alphabetical order. + static const char* kAppletAttributes[] = { + "ALIGN", "ALT", "ARCHIVE", + "CODE", "CODEBASE", + "HEIGHT", "HSPACE", + "MAYSCRIPT", "NAME", "OBJECT", + "VSPACE", "WIDTH" + }; + int length = sizeof(kAppletAttributes) / sizeof(char*); + int minIndex = 0, maxIndex = length - 1; + int index = maxIndex / 2; + while (minIndex <= maxIndex) { + int diff = strcasecmp(name, kAppletAttributes[index]); + if (diff < 0) { + maxIndex = (index - 1); + index = (minIndex + maxIndex) / 2; + } else if (diff > 0) { + minIndex = (index + 1); + index = (minIndex + maxIndex) / 2; + } else { return true; - } - } + } + } return false; } @@ -228,76 +228,76 @@ static void addParameter(string& params, const char* name, const char* value) { - params += "\n"; + params += "\n"; } static void addAttributes(nsIPluginTagInfo* tagInfo, string& attributes) { - PRUint16 count; - const char* const* names; - const char* const* values; + PRUint16 count; + const char* const* names; + const char* const* values; if (tagInfo->GetAttributes(count, names, values) == NS_OK) { - for (PRUint16 i = 0; i < count; ++i) - addAttribute(attributes, names[i], values[i]); + for (PRUint16 i = 0; i < count; ++i) + addAttribute(attributes, names[i], values[i]); } } static void addParameters(nsIPluginTagInfo2* tagInfo2, string& parameters) { - PRUint16 count; - const char* const* names; - const char* const* values; + PRUint16 count; + const char* const* names; + const char* const* values; if (tagInfo2->GetParameters(count, names, values) == NS_OK) { - for (PRUint16 i = 0; i < count; ++i) - addParameter(parameters, names[i], values[i]); + for (PRUint16 i = 0; i < count; ++i) + addParameter(parameters, names[i], values[i]); } } static void addObjectAttributes(nsIPluginTagInfo* tagInfo, string& attributes) { - PRUint16 count; - const char* const* names; - const char* const* values; + PRUint16 count; + const char* const* names; + const char* const* values; const char kClassID[] = "classid"; - const char kJavaPrefix[] = "java:"; - const size_t kJavaPrefixSize = sizeof(kJavaPrefix) - 1; - if (tagInfo->GetAttributes(count, names, values) == NS_OK) { - for (PRUint16 i = 0; i < count; ++i) { - const char* name = names[i]; - const char* value = values[i]; - if (strcasecmp(name, "classid") == 0 && strncmp(value, kJavaPrefix, kJavaPrefixSize) == 0) - addAttribute(attributes, "code", value + kJavaPrefixSize); - else - addAttribute(attributes, name, value); - } - } + const char kJavaPrefix[] = "java:"; + const size_t kJavaPrefixSize = sizeof(kJavaPrefix) - 1; + if (tagInfo->GetAttributes(count, names, values) == NS_OK) { + for (PRUint16 i = 0; i < count; ++i) { + const char* name = names[i]; + const char* value = values[i]; + if (strcasecmp(name, "classid") == 0 && strncmp(value, kJavaPrefix, kJavaPrefixSize) == 0) + addAttribute(attributes, "code", value + kJavaPrefixSize); + else + addAttribute(attributes, name, value); + } + } } static void addEmbedAttributes(nsIPluginTagInfo* tagInfo, string& attributes, string& parameters) { - PRUint16 count; - const char* const* names; - const char* const* values; - const char kJavaPluginAttributePrefix[] = "java_"; - const size_t kJavaPluginAttributePrefixSize = sizeof(kJavaPluginAttributePrefix) - 1; - if (tagInfo->GetAttributes(count, names, values) == NS_OK) { - for (PRUint16 i = 0; i < count; ++i) { - const char* name = names[i]; - const char* value = values[i]; - if (strncmp(name, kJavaPluginAttributePrefix, kJavaPluginAttributePrefixSize) == 0) - name += kJavaPluginAttributePrefixSize; - if (isAppletAttribute(name)) { - addAttribute(attributes, name, value); - } else { - // assume it's a parameter. - addParameter(parameters, name, value); - } - } - } + PRUint16 count; + const char* const* names; + const char* const* values; + const char kJavaPluginAttributePrefix[] = "java_"; + const size_t kJavaPluginAttributePrefixSize = sizeof(kJavaPluginAttributePrefix) - 1; + if (tagInfo->GetAttributes(count, names, values) == NS_OK) { + for (PRUint16 i = 0; i < count; ++i) { + const char* name = names[i]; + const char* value = values[i]; + if (strncmp(name, kJavaPluginAttributePrefix, kJavaPluginAttributePrefixSize) == 0) + name += kJavaPluginAttributePrefixSize; + if (isAppletAttribute(name)) { + addAttribute(attributes, name, value); + } else { + // assume it's a parameter. + addParameter(parameters, name, value); + } + } + } } static char* synthesizeAppletElement(nsIPluginTagInfo* tagInfo) @@ -310,28 +310,28 @@ string attributes(""); string parameters(""); - nsIPluginTagInfo2* tagInfo2 = NULL; - if (tagInfo->QueryInterface(NS_GET_IID(nsIPluginTagInfo2), (void **)&tagInfo2) == NS_OK) { - nsPluginTagType tagType = nsPluginTagType_Unknown; - if (tagInfo2->GetTagType(&tagType) == NS_OK) { - switch (tagType) { - case nsPluginTagType_Applet: - addAttributes(tagInfo2, attributes); - addParameters(tagInfo2, parameters); - break; - case nsPluginTagType_Object: - addObjectAttributes(tagInfo2, attributes); - addParameters(tagInfo2, parameters); + nsIPluginTagInfo2* tagInfo2 = NULL; + if (CallQueryInterface(tagInfo, &tagInfo2))) { + nsPluginTagType tagType = nsPluginTagType_Unknown; + if (tagInfo2->GetTagType(&tagType) == NS_OK) { + switch (tagType) { + case nsPluginTagType_Applet: + addAttributes(tagInfo2, attributes); + addParameters(tagInfo2, parameters); + break; + case nsPluginTagType_Object: + addObjectAttributes(tagInfo2, attributes); + addParameters(tagInfo2, parameters); break; case nsPluginTagType_Embed: addEmbedAttributes(tagInfo2, attributes, parameters); break; - } - } - NS_RELEASE(tagInfo2); - } else { - addEmbedAttributes(tagInfo, attributes, parameters); - } + } + } + NS_RELEASE(tagInfo2); + } else { + addEmbedAttributes(tagInfo, attributes, parameters); + } element += attributes; element += ">\n"; @@ -350,42 +350,42 @@ // use the applet's HTML element to create a locator. this is required // in general, to specify a separate CODEBASE. - nsIPluginTagInfo* tagInfo = NULL; - if (mPeer->QueryInterface(NS_GET_IID(nsIPluginTagInfo), (void **)&tagInfo) == NS_OK) { - nsIPluginTagInfo2* tagInfo2 = NULL; - if (tagInfo->QueryInterface(NS_GET_IID(nsIPluginTagInfo2), (void **)&tagInfo2) == NS_OK) { - nsPluginTagType tagType = nsPluginTagType_Unknown; - if (tagInfo2->GetTagType(&tagType) == NS_OK) { - // get the URL of the HTML document containing the applet, and the - // fragment of HTML that defines this applet itself. - const char* documentBase = NULL; - if (tagInfo2->GetDocumentBase(&documentBase) == NS_OK) - setDocumentBase(documentBase); - const char* appletHTML = NULL; - if (tagInfo2->GetTagText(&appletHTML) == NS_OK) - setAppletHTML(appletHTML, tagType); - else + nsIPluginTagInfo* tagInfo = NULL; + if (NS_SUCCEEDED(CallQueryInterface(mPeer, &tagInfo))) { + nsIPluginTagInfo2* tagInfo2 = NULL; + if (NS_SUCCEEDED(CallQueryInterface(tagInfo, &tagInfo2))) { + nsPluginTagType tagType = nsPluginTagType_Unknown; + if (tagInfo2->GetTagType(&tagType) == NS_OK) { + // get the URL of the HTML document containing the applet, and the + // fragment of HTML that defines this applet itself. + const char* documentBase = NULL; + if (tagInfo2->GetDocumentBase(&documentBase) == NS_OK) + setDocumentBase(documentBase); + const char* appletHTML = NULL; + if (tagInfo2->GetTagText(&appletHTML) == NS_OK) + setAppletHTML(appletHTML, tagType); + else mAppletHTML = synthesizeAppletElement(tagInfo); } // to support applet communication, put applets from the same document, codebase, and mayscript setting // in the same page. - // establish a page context for this applet to run in. - nsIJVMPluginTagInfo* jvmTagInfo = NULL; - if (mPeer->QueryInterface(NS_GET_IID(nsIJVMPluginTagInfo), (void **)&jvmTagInfo) == NS_OK) { - PRUint32 documentID; - const char* codeBase; - const char* archive; - PRBool mayScript; - if (tagInfo2->GetUniqueID(&documentID) != NS_OK) documentID = 0; - if (jvmTagInfo->GetCodeBase(&codeBase) != NS_OK) codeBase = NULL; - if (jvmTagInfo->GetArchive(&archive) != NS_OK) archive = NULL; - if (jvmTagInfo->GetMayScript(&mayScript) != NS_OK) mayScript = PR_FALSE; + // establish a page context for this applet to run in. + nsIJVMPluginTagInfo* jvmTagInfo = NULL; + if (NS_SUCCEEDED(CallQueryInterface(mPeer, &jvmTagInfo))) { + PRUint32 documentID; + const char* codeBase; + const char* archive; + PRBool mayScript; + if (tagInfo2->GetUniqueID(&documentID) != NS_OK) documentID = 0; + if (jvmTagInfo->GetCodeBase(&codeBase) != NS_OK) codeBase = NULL; + if (jvmTagInfo->GetArchive(&archive) != NS_OK) archive = NULL; + if (jvmTagInfo->GetMayScript(&mayScript) != NS_OK) mayScript = PR_FALSE; MRJPageAttributes pageAttributes = { documentID, codeBase, archive, mayScript }; - mPage = findPage(pageAttributes); - NS_RELEASE(jvmTagInfo); - } + mPage = findPage(pageAttributes); + NS_RELEASE(jvmTagInfo); + } NS_RELEASE(tagInfo2); } else { @@ -404,10 +404,10 @@ // "\n" // ""; - static JMAppletLocatorCallbacks callbacks = { - kJMVersion, /* should be set to kJMVersion */ - &fetchCompleted, /* called when the html has been completely fetched */ - }; + static JMAppletLocatorCallbacks callbacks = { + kJMVersion, /* should be set to kJMVersion */ + &fetchCompleted, /* called when the html has been completely fetched */ + }; OSStatus status; JMTextRef urlRef = NULL, htmlRef = NULL; @@ -423,10 +423,10 @@ urlRef, htmlRef, JMClientData(this)); done: - if (urlRef != NULL) - ::JMDisposeTextRef(urlRef); - if (htmlRef != NULL) - ::JMDisposeTextRef(htmlRef); + if (urlRef != NULL) + ::JMDisposeTextRef(urlRef); + if (htmlRef != NULL) + ::JMDisposeTextRef(htmlRef); } } @@ -434,474 +434,474 @@ void MRJContext::processAppletTag() { - // create an applet locator. - OSStatus status = noErr; - JMLocatorInfoBlock info; - info.fVersion = kJMVersion; - info.fBaseURL = NULL; - info.fAppletCode = NULL; - info.fWidth = info.fHeight = 100; - info.fOptionalParameterCount = 0; - info.fParams = NULL; - - struct { - PRUint16 fCount; - const char* const* fNames; - const char* const* fValues; - } attributes = { 0, NULL, NULL }, parameters = { 0, NULL, NULL }; - - MRJPageAttributes pageAttributes = { 0, NULL, NULL, false }; - nsPluginTagType pluginTagType = nsPluginTagType_Embed; - - // obtain the applet's attributes & parameters. - nsIPluginTagInfo* tagInfo = NULL; - if (mPeer->QueryInterface(NS_GET_IID(nsIPluginTagInfo), &tagInfo) == NS_OK) { - tagInfo->GetAttributes(attributes.fCount, attributes.fNames, attributes.fValues); - nsIPluginTagInfo2* tagInfo2 = NULL; - if (tagInfo->QueryInterface(NS_GET_IID(nsIPluginTagInfo2), &tagInfo2) == NS_OK) { - tagInfo2->GetParameters(parameters.fCount, parameters.fNames, parameters.fValues); - tagInfo2->GetTagType(&pluginTagType); - - // get the URL of the HTML document containing the applet. - const char* documentBase = NULL; - if (tagInfo2->GetDocumentBase(&documentBase) == NS_OK && documentBase != NULL) { - // record the document base, in case - setDocumentBase(documentBase); - - // establish a page context for this applet to run in. - nsIJVMPluginTagInfo* jvmTagInfo = NULL; - if (mPeer->QueryInterface(NS_GET_IID(nsIJVMPluginTagInfo), &jvmTagInfo) == NS_OK) { - PRUint32 documentID; - const char* codeBase; - const char* archive; - PRBool mayScript; - if (tagInfo2->GetUniqueID(&documentID) == NS_OK && - jvmTagInfo->GetCodeBase(&codeBase) == NS_OK && - jvmTagInfo->GetArchive(&archive) == NS_OK && - jvmTagInfo->GetMayScript(&mayScript) == NS_OK) { - pageAttributes.documentID = documentID; - pageAttributes.codeBase = codeBase; - pageAttributes.archive = archive; - pageAttributes.mayScript = mayScript; - } - jvmTagInfo->Release(); - } - } - tagInfo2->Release(); - } - tagInfo->Release(); - } - - // compute the URL of the directory containing this applet's HTML page. - char* baseURL = ::strdup(getDocumentBase()); - if (baseURL != NULL) { - // trim the trailing document name. - char* lastSlash = ::strrchr(baseURL, '/'); - if (lastSlash != NULL) - lastSlash[1] = '\0'; - } - - // assume that all arguments might be optional. - int optionalArgIndex = 0; - info.fParams = new JMLIBOptionalParams[attributes.fCount + parameters.fCount]; - if (info.fParams == NULL) - goto done; - - // process APPLET/EMBED tag attributes. - for (int i = 0; i < attributes.fCount; i++) { - const char* name = attributes.fNames[i]; - const char* value = attributes.fValues[i]; - if (name != NULL && value != NULL) { - // if running as an EMBED tag plugin, there may be some attribute - // rewriting going on. Sun's Java plugin uses attributes with the - // "java_" prefix. - if (pluginTagType == nsPluginTagType_Embed) { - static const char kJavaPluginAttributePrefix[] = "java_"; - if (strncmp(name, kJavaPluginAttributePrefix, sizeof(kJavaPluginAttributePrefix) - 1) == 0) - name += (sizeof(kJavaPluginAttributePrefix) - 1); - } - if (strcasecmp(name, "CODEBASE") == 0) { - if (pageAttributes.codeBase == NULL) - pageAttributes.codeBase = value; - } else - if (strcasecmp(name, "CODE") == 0) { - status = ::JMNewTextRef(mSessionRef, &info.fAppletCode, kTextEncodingMacRoman, value, strlen(value)); - } else - if (strcasecmp(name, "CLASSID") == 0) { - // bug 6591: uses classid="java:classname" - value += 5; - status = ::JMNewTextRef(mSessionRef, &info.fAppletCode, kTextEncodingMacRoman, value, strlen(value)); - } else - if (strcasecmp(name, "WIDTH") == 0) { - info.fWidth = ::atoi(value); - } else - if (strcasecmp(name, "HEIGHT") == 0) { - info.fHeight = ::atoi(value); - } else { - // assume it's an optional argument. - JMLIBOptionalParams* param = &info.fParams[optionalArgIndex++]; - status = ::JMNewTextRef(mSessionRef, ¶m->fParamName, kTextEncodingMacRoman, name, strlen(name)); - status = ::JMNewTextRef(mSessionRef, ¶m->fParamValue, kTextEncodingMacRoman, value, strlen(value)); - } - } - } - - // set up the clipping region based on width & height. - ::SetRectRgn(mPluginClipping, 0, 0, info.fWidth, info.fHeight); - - // process parameters. - for (int i = 0; i < parameters.fCount; i++) { - const char* name = parameters.fNames[i]; - const char* value = parameters.fValues[i]; - if (name != NULL && value != NULL) { - // assume it's an optional argument. - JMLIBOptionalParams* param = &info.fParams[optionalArgIndex++]; - status = ::JMNewTextRef(mSessionRef, ¶m->fParamName, kTextEncodingMacRoman, name, strlen(name)); - status = ::JMNewTextRef(mSessionRef, ¶m->fParamValue, kTextEncodingMacRoman, value, strlen(value)); - } - } - info.fOptionalParameterCount = optionalArgIndex; - - // Compute the locator's baseURL field by concatenating the CODEBASE (if any specified). - if (baseURL != NULL) { - if (pageAttributes.codeBase != NULL) { - // if the codebase is an absolute URL, use it, otherwise, concatenate with document's URL. - if (::strchr(pageAttributes.codeBase, ':') != NULL) { - delete[] baseURL; - baseURL = ::strdup(pageAttributes.codeBase); - } else { - if (pageAttributes.codeBase[0] == '/') { - // if codeBase starts with '/', need to prepend the URL's protocol://hostname part. - char* fullURL = new char[::strlen(baseURL) + ::strlen(pageAttributes.codeBase) + 1]; - // search for start of host name. what about file URL's? - const char* hostNameStart = strchr(baseURL, '/'); - while (*hostNameStart == '/') ++hostNameStart; - const char* hostNameEnd = strchr(hostNameStart, '/') + 1; - ::strncpy(fullURL, baseURL, hostNameEnd - baseURL); - fullURL[hostNameEnd - baseURL] = '\0'; - ::strcat(fullURL, pageAttributes.codeBase + 1); - delete[] baseURL; - baseURL = fullURL; - } else { - // assume the codeBase is relative to the document's URL. - int baseLength = ::strlen(baseURL); - int fullLength = baseLength + ::strlen(pageAttributes.codeBase); - char* fullURL = new char[fullLength + 1]; - ::strcpy(fullURL, baseURL); - ::strcat(fullURL + baseLength, pageAttributes.codeBase); - delete[] baseURL; - baseURL = fullURL; - } - } - } - } else if (pageAttributes.codeBase != NULL) { - // the CODEBASE must be an absolute URL in this case. - baseURL = ::strdup(pageAttributes.codeBase); - } - - if (baseURL != NULL) { - // make sure the URL always ends with a slash. - baseURL = ::slashify(baseURL); - status = ::JMNewTextRef(mSessionRef, &info.fBaseURL, kTextEncodingMacRoman, baseURL, ::strlen(baseURL)); - - // baseURL is now the *TRUE* codeBase - pageAttributes.codeBase = baseURL; - mPage = findPage(pageAttributes); - - // keep the codeBase around for later. - // setCodeBase(baseURL); - delete[] baseURL; - - status = ::JMNewAppletLocatorFromInfo(&mLocator, mSessionRef, &info, NULL); - } else { - ::DebugStr("\pNeed a baseURL (CODEBASE)!"); - } + // create an applet locator. + OSStatus status = noErr; + JMLocatorInfoBlock info; + info.fVersion = kJMVersion; + info.fBaseURL = NULL; + info.fAppletCode = NULL; + info.fWidth = info.fHeight = 100; + info.fOptionalParameterCount = 0; + info.fParams = NULL; + + struct { + PRUint16 fCount; + const char* const* fNames; + const char* const* fValues; + } attributes = { 0, NULL, NULL }, parameters = { 0, NULL, NULL }; + + MRJPageAttributes pageAttributes = { 0, NULL, NULL, false }; + nsPluginTagType pluginTagType = nsPluginTagType_Embed; + + // obtain the applet's attributes & parameters. + nsIPluginTagInfo* tagInfo = NULL; + if (NS_SUCCEEDED(CallQueryInterface(mPeer, &tagInfo))) { + tagInfo->GetAttributes(attributes.fCount, attributes.fNames, attributes.fValues); + nsIPluginTagInfo2* tagInfo2 = NULL; + if (NS_SUCCEEDED(CallQueryInterface(tagInfo, &tagInfo2))) { + tagInfo2->GetParameters(parameters.fCount, parameters.fNames, parameters.fValues); + tagInfo2->GetTagType(&pluginTagType); + + // get the URL of the HTML document containing the applet. + const char* documentBase = NULL; + if (tagInfo2->GetDocumentBase(&documentBase) == NS_OK && documentBase != NULL) { + // record the document base, in case + setDocumentBase(documentBase); + + // establish a page context for this applet to run in. + nsIJVMPluginTagInfo* jvmTagInfo = NULL; + if (NS_SUCCEEDED(CallQueryInterface(mPeer, &jvmTagInfo))) { + PRUint32 documentID; + const char* codeBase; + const char* archive; + PRBool mayScript; + if (tagInfo2->GetUniqueID(&documentID) == NS_OK && + jvmTagInfo->GetCodeBase(&codeBase) == NS_OK && + jvmTagInfo->GetArchive(&archive) == NS_OK && + jvmTagInfo->GetMayScript(&mayScript) == NS_OK) { + pageAttributes.documentID = documentID; + pageAttributes.codeBase = codeBase; + pageAttributes.archive = archive; + pageAttributes.mayScript = mayScript; + } + jvmTagInfo->Release(); + } + } + tagInfo2->Release(); + } + tagInfo->Release(); + } + + // compute the URL of the directory containing this applet's HTML page. + char* baseURL = ::strdup(getDocumentBase()); + if (baseURL != NULL) { + // trim the trailing document name. + char* lastSlash = ::strrchr(baseURL, '/'); + if (lastSlash != NULL) + lastSlash[1] = '\0'; + } + + // assume that all arguments might be optional. + int optionalArgIndex = 0; + info.fParams = new JMLIBOptionalParams[attributes.fCount + parameters.fCount]; + if (info.fParams == NULL) + goto done; + + // process APPLET/EMBED tag attributes. + for (int i = 0; i < attributes.fCount; i++) { + const char* name = attributes.fNames[i]; + const char* value = attributes.fValues[i]; + if (name != NULL && value != NULL) { + // if running as an EMBED tag plugin, there may be some attribute + // rewriting going on. Sun's Java plugin uses attributes with the + // "java_" prefix. + if (pluginTagType == nsPluginTagType_Embed) { + static const char kJavaPluginAttributePrefix[] = "java_"; + if (strncmp(name, kJavaPluginAttributePrefix, sizeof(kJavaPluginAttributePrefix) - 1) == 0) + name += (sizeof(kJavaPluginAttributePrefix) - 1); + } + if (strcasecmp(name, "CODEBASE") == 0) { + if (pageAttributes.codeBase == NULL) + pageAttributes.codeBase = value; + } else + if (strcasecmp(name, "CODE") == 0) { + status = ::JMNewTextRef(mSessionRef, &info.fAppletCode, kTextEncodingMacRoman, value, strlen(value)); + } else + if (strcasecmp(name, "CLASSID") == 0) { + // bug 6591: uses classid="java:classname" + value += 5; + status = ::JMNewTextRef(mSessionRef, &info.fAppletCode, kTextEncodingMacRoman, value, strlen(value)); + } else + if (strcasecmp(name, "WIDTH") == 0) { + info.fWidth = ::atoi(value); + } else + if (strcasecmp(name, "HEIGHT") == 0) { + info.fHeight = ::atoi(value); + } else { + // assume it's an optional argument. + JMLIBOptionalParams* param = &info.fParams[optionalArgIndex++]; + status = ::JMNewTextRef(mSessionRef, ¶m->fParamName, kTextEncodingMacRoman, name, strlen(name)); + status = ::JMNewTextRef(mSessionRef, ¶m->fParamValue, kTextEncodingMacRoman, value, strlen(value)); + } + } + } + + // set up the clipping region based on width & height. + ::SetRectRgn(mPluginClipping, 0, 0, info.fWidth, info.fHeight); + + // process parameters. + for (int i = 0; i < parameters.fCount; i++) { + const char* name = parameters.fNames[i]; + const char* value = parameters.fValues[i]; + if (name != NULL && value != NULL) { + // assume it's an optional argument. + JMLIBOptionalParams* param = &info.fParams[optionalArgIndex++]; + status = ::JMNewTextRef(mSessionRef, ¶m->fParamName, kTextEncodingMacRoman, name, strlen(name)); + status = ::JMNewTextRef(mSessionRef, ¶m->fParamValue, kTextEncodingMacRoman, value, strlen(value)); + } + } + info.fOptionalParameterCount = optionalArgIndex; + + // Compute the locator's baseURL field by concatenating the CODEBASE (if any specified). + if (baseURL != NULL) { + if (pageAttributes.codeBase != NULL) { + // if the codebase is an absolute URL, use it, otherwise, concatenate with document's URL. + if (::strchr(pageAttributes.codeBase, ':') != NULL) { + delete[] baseURL; + baseURL = ::strdup(pageAttributes.codeBase); + } else { + if (pageAttributes.codeBase[0] == '/') { + // if codeBase starts with '/', need to prepend the URL's protocol://hostname part. + char* fullURL = new char[::strlen(baseURL) + ::strlen(pageAttributes.codeBase) + 1]; + // search for start of host name. what about file URL's? + const char* hostNameStart = strchr(baseURL, '/'); + while (*hostNameStart == '/') ++hostNameStart; + const char* hostNameEnd = strchr(hostNameStart, '/') + 1; + ::strncpy(fullURL, baseURL, hostNameEnd - baseURL); + fullURL[hostNameEnd - baseURL] = '\0'; + ::strcat(fullURL, pageAttributes.codeBase + 1); + delete[] baseURL; + baseURL = fullURL; + } else { + // assume the codeBase is relative to the document's URL. + int baseLength = ::strlen(baseURL); + int fullLength = baseLength + ::strlen(pageAttributes.codeBase); + char* fullURL = new char[fullLength + 1]; + ::strcpy(fullURL, baseURL); + ::strcat(fullURL + baseLength, pageAttributes.codeBase); + delete[] baseURL; + baseURL = fullURL; + } + } + } + } else if (pageAttributes.codeBase != NULL) { + // the CODEBASE must be an absolute URL in this case. + baseURL = ::strdup(pageAttributes.codeBase); + } + + if (baseURL != NULL) { + // make sure the URL always ends with a slash. + baseURL = ::slashify(baseURL); + status = ::JMNewTextRef(mSessionRef, &info.fBaseURL, kTextEncodingMacRoman, baseURL, ::strlen(baseURL)); + + // baseURL is now the *TRUE* codeBase + pageAttributes.codeBase = baseURL; + mPage = findPage(pageAttributes); + + // keep the codeBase around for later. + // setCodeBase(baseURL); + delete[] baseURL; + + status = ::JMNewAppletLocatorFromInfo(&mLocator, mSessionRef, &info, NULL); + } else { + ::DebugStr("\pNeed a baseURL (CODEBASE)!"); + } done: - if (info.fBaseURL != NULL) - ::JMDisposeTextRef(info.fBaseURL); - if (info.fAppletCode != NULL) - ::JMDisposeTextRef(info.fAppletCode); - if (info.fParams != NULL) { - for (int i = 0; i < optionalArgIndex; i++) { - JMLIBOptionalParams* param = &info.fParams[i]; - ::JMDisposeTextRef(param->fParamName); - ::JMDisposeTextRef(param->fParamValue); - } - delete info.fParams; - } + if (info.fBaseURL != NULL) + ::JMDisposeTextRef(info.fBaseURL); + if (info.fAppletCode != NULL) + ::JMDisposeTextRef(info.fAppletCode); + if (info.fParams != NULL) { + for (int i = 0; i < optionalArgIndex; i++) { + JMLIBOptionalParams* param = &info.fParams[i]; + ::JMDisposeTextRef(param->fParamName); + ::JMDisposeTextRef(param->fParamValue); + } + delete info.fParams; + } } #endif static MRJFrame* getFrame(JMFrameRef ref) { - MRJFrame* frame = NULL; - if (ref != NULL) { - ::JMGetFrameData(ref, (JMClientData*)&frame); - } - - return frame; + MRJFrame* frame = NULL; + if (ref != NULL) { + ::JMGetFrameData(ref, (JMClientData*)&frame); + } + + return frame; } static void frameSetSize(JMFrameRef ref, const Rect* newSize) { - MRJFrame* frame = getFrame(ref); - if (frame != NULL) - frame->setSize(newSize); + MRJFrame* frame = getFrame(ref); + if (frame != NULL) + frame->setSize(newSize); } static void frameInvalRect(JMFrameRef ref, const Rect* invalidRect) { - MRJFrame* frame = getFrame(ref); - if (frame != NULL) - frame->invalRect(invalidRect); + MRJFrame* frame = getFrame(ref); + if (frame != NULL) + frame->invalRect(invalidRect); #if 0 - // do we know for certain that this frame's port is a window? Assume it is. - MRJContext* thisContext = NULL; - OSStatus status = ::JMGetFrameData(frame, (JMClientData*)&thisContext); - if (status == noErr && thisContext != NULL) - ::InvalRect(r); + // do we know for certain that this frame's port is a window? Assume it is. + MRJContext* thisContext = NULL; + OSStatus status = ::JMGetFrameData(frame, (JMClientData*)&thisContext); + if (status == noErr && thisContext != NULL) + ::InvalRect(r); #endif #if 0 - // since this comes in on an arbitrary thread, we can't very well go calling - // back into the browser to do this, it crashes. - MRJContext* thisContext; - OSStatus status = ::JMGetFrameData(frame, (JMClientData*)&thisContext); - if (status == noErr) { - // since this comes in on an arbitrary thread, there's no telling what - // state the world is in. - NPRect invalidRect = { r->top, r->left, r->bottom, r->right }; - ::NPN_InvalidateRect(thisContext->fInstance, &invalidRect); - } + // since this comes in on an arbitrary thread, we can't very well go calling + // back into the browser to do this, it crashes. + MRJContext* thisContext; + OSStatus status = ::JMGetFrameData(frame, (JMClientData*)&thisContext); + if (status == noErr) { + // since this comes in on an arbitrary thread, there's no telling what + // state the world is in. + NPRect invalidRect = { r->top, r->left, r->bottom, r->right }; + ::NPN_InvalidateRect(thisContext->fInstance, &invalidRect); + } #endif } static void frameShowHide(JMFrameRef ref, Boolean visible) { - MRJFrame* frame = getFrame(ref); - if (frame != NULL) - frame->showHide(visible); + MRJFrame* frame = getFrame(ref); + if (frame != NULL) + frame->showHide(visible); } static void frameSetTitle(JMFrameRef ref, JMTextRef titleRef) { - Str255 title; - JMTextToStr255(titleRef, title); - MRJFrame* frame = getFrame(ref); - if (frame != NULL) - frame->setTitle(title); + Str255 title; + JMTextToStr255(titleRef, title); + MRJFrame* frame = getFrame(ref); + if (frame != NULL) + frame->setTitle(title); } static void frameCheckUpdate(JMFrameRef ref) { - MRJFrame* frame = getFrame(ref); - if (frame != NULL) - frame->checkUpdate(); + MRJFrame* frame = getFrame(ref); + if (frame != NULL) + frame->checkUpdate(); } static void frameReorderFrame(JMFrameRef ref, ReorderRequest request) { - MRJFrame* frame = getFrame(ref); - if (frame != NULL) - frame->reorder(request); + MRJFrame* frame = getFrame(ref); + if (frame != NULL) + frame->reorder(request); } static void frameSetResizeable(JMFrameRef ref, Boolean resizeable) { - MRJFrame* frame = getFrame(ref); - if (frame != NULL) - frame->setResizeable(resizeable); + MRJFrame* frame = getFrame(ref); + if (frame != NULL) + frame->setResizeable(resizeable); } static void frameGetFrameInsets(JMFrameRef frame, Rect *insets) { - // MRJFrame* frame = getFrame(ref); - // if (frame != NULL) - // frame->getFrameInsets(insets); - insets->top = insets->left = insets->bottom = insets->right = 0; + // MRJFrame* frame = getFrame(ref); + // if (frame != NULL) + // frame->getFrameInsets(insets); + insets->top = insets->left = insets->bottom = insets->right = 0; } static void frameNextFocus(JMFrameRef frame, Boolean forward) { - // MRJFrame* frame = getFrame(ref); - // if (frame != NULL) - // frame->nextFocus(insets); + // MRJFrame* frame = getFrame(ref); + // if (frame != NULL) + // frame->nextFocus(insets); } static void frameRequestFocus(JMFrameRef frame) { - // MRJFrame* frame = getFrame(ref); - // if (frame != NULL) - // frame->requestFocus(insets); + // MRJFrame* frame = getFrame(ref); + // if (frame != NULL) + // frame->requestFocus(insets); } class AppletViewerFrame : public MRJFrame { public: - AppletViewerFrame(JMFrameRef frameRef, MRJContext* context) : MRJFrame(frameRef), mContext(context) {} - - virtual void invalRect(const Rect* invalidRect); - - virtual void idle(SInt16 modifiers); - virtual void update(); - virtual void click(const EventRecord* event); + AppletViewerFrame(JMFrameRef frameRef, MRJContext* context) : MRJFrame(frameRef), mContext(context) {} + + virtual void invalRect(const Rect* invalidRect); + + virtual void idle(SInt16 modifiers); + virtual void update(); + virtual void click(const EventRecord* event); protected: - virtual GrafPtr getPort(); + virtual GrafPtr getPort(); private: - MRJContext* mContext; + MRJContext* mContext; }; void AppletViewerFrame::invalRect(const Rect* invalidRect) { - ::InvalRect(invalidRect); + ::InvalRect(invalidRect); } void AppletViewerFrame::idle(SInt16 modifiers) { - mContext->idle(modifiers); + mContext->idle(modifiers); } void AppletViewerFrame::update() { - mContext->drawApplet(); + mContext->drawApplet(); } void AppletViewerFrame::click(const EventRecord* event) { - mContext->click(event, this); + mContext->click(event, this); } GrafPtr AppletViewerFrame::getPort() { - return mContext->getPort(); + return mContext->getPort(); } JMFrameCallbacks theFrameCallbacks = { - kJMVersion, /* should be set to kJMVersion */ - &frameSetSize, - &frameInvalRect, - &frameShowHide, - &frameSetTitle, - &frameCheckUpdate, - &frameReorderFrame, - &frameSetResizeable, - &frameGetFrameInsets, - &frameNextFocus, - &frameRequestFocus, + kJMVersion, /* should be set to kJMVersion */ + &frameSetSize, + &frameInvalRect, + &frameShowHide, + &frameSetTitle, + &frameCheckUpdate, + &frameReorderFrame, + &frameSetResizeable, + &frameGetFrameInsets, + &frameNextFocus, + &frameRequestFocus, }; OSStatus MRJContext::requestFrame(JMAWTContextRef contextRef, JMFrameRef frameRef, JMFrameKind kind, - const Rect* initialBounds, Boolean resizeable, JMFrameCallbacks* cb) + const Rect* initialBounds, Boolean resizeable, JMFrameCallbacks* cb) { - // set up the viewer frame's callbacks. - BlockMoveData(&theFrameCallbacks, cb, sizeof(theFrameCallbacks)); - // *cb = callbacks; - - MRJContext* thisContext = NULL; - OSStatus status = ::JMGetAWTContextData(contextRef, (JMClientData*)&thisContext); - return thisContext->createFrame(frameRef, kind, initialBounds, resizeable); + // set up the viewer frame's callbacks. + BlockMoveData(&theFrameCallbacks, cb, sizeof(theFrameCallbacks)); + // *cb = callbacks; + + MRJContext* thisContext = NULL; + OSStatus status = ::JMGetAWTContextData(contextRef, (JMClientData*)&thisContext); + return thisContext->createFrame(frameRef, kind, initialBounds, resizeable); } OSStatus MRJContext::releaseFrame(JMAWTContextRef contextRef, JMFrameRef frameRef) { - MRJContext* thisContext = NULL; - OSStatus status = ::JMGetAWTContextData(contextRef, (JMClientData*)&thisContext); - MRJFrame* thisFrame = NULL; - status = ::JMGetFrameData(frameRef, (JMClientData*)&thisFrame); - if (thisFrame != NULL) { - status = ::JMSetFrameData(frameRef, NULL); - if (thisContext->mViewerFrame == frameRef) { - thisContext->mViewerFrame = NULL; - } - delete thisFrame; - } - return status; + MRJContext* thisContext = NULL; + OSStatus status = ::JMGetAWTContextData(contextRef, (JMClientData*)&thisContext); + MRJFrame* thisFrame = NULL; + status = ::JMGetFrameData(frameRef, (JMClientData*)&thisFrame); + if (thisFrame != NULL) { + status = ::JMSetFrameData(frameRef, NULL); + if (thisContext->mViewerFrame == frameRef) { + thisContext->mViewerFrame = NULL; + } + delete thisFrame; + } + return status; } SInt16 MRJContext::getUniqueMenuID(JMAWTContextRef contextRef, Boolean isSubmenu) { - MRJContext* thisContext = NULL; - OSStatus status = ::JMGetAWTContextData(contextRef, (JMClientData*)&thisContext); - return thisContext->allocateMenuID(isSubmenu); + MRJContext* thisContext = NULL; + OSStatus status = ::JMGetAWTContextData(contextRef, (JMClientData*)&thisContext); + return thisContext->allocateMenuID(isSubmenu); } static Boolean appearanceManagerExists() { - long response = 0; - return (Gestalt(gestaltAppearanceAttr, &response) == noErr && (response & (1 << gestaltAppearanceExists))); + long response = 0; + return (Gestalt(gestaltAppearanceAttr, &response) == noErr && (response & (1 << gestaltAppearanceExists))); } static OSStatus JMTextToStr255(JMTextRef textRef, Str255 str) { - UInt32 length = 0; - OSStatus status = JMGetTextBytes(textRef, kTextEncodingMacRoman, &str[1], sizeof(Str255) - 1, &length); - if (status == noErr) - str[0] = (unsigned char)(status == noErr ? length : 0); - return status; + UInt32 length = 0; + OSStatus status = JMGetTextBytes(textRef, kTextEncodingMacRoman, &str[1], sizeof(Str255) - 1, &length); + if (status == noErr) + str[0] = (unsigned char)(status == noErr ? length : 0); + return status; } static char* JMTextToEncoding(JMTextRef textRef, JMTextEncoding encoding) { - UInt32 length = 0; + UInt32 length = 0; OSStatus status = ::JMGetTextLengthInBytes(textRef, encoding, &length); if (status != noErr) return NULL; char* text = new char[length + 1]; if (text != NULL) { UInt32 actualLength; - status = ::JMGetTextBytes(textRef, encoding, text, length, &actualLength); - if (status != noErr) { - delete text; - return NULL; - } - text[length] = '\0'; + status = ::JMGetTextBytes(textRef, encoding, text, length, &actualLength); + if (status != noErr) { + delete text; + return NULL; + } + text[length] = '\0'; } return text; } void MRJContext::exceptionOccurred(JMAWTContextRef context, JMTextRef exceptionName, JMTextRef exceptionMsg, JMTextRef stackTrace) { - // why not display this using the Appearance Manager's wizzy new alert? - if (appearanceManagerExists()) { - OSStatus status; - Str255 error, explanation; - status = ::JMTextToStr255(exceptionName, error); - status = ::JMTextToStr255(exceptionMsg, explanation); + // why not display this using the Appearance Manager's wizzy new alert? + if (appearanceManagerExists()) { + OSStatus status; + Str255 error, explanation; + status = ::JMTextToStr255(exceptionName, error); + status = ::JMTextToStr255(exceptionMsg, explanation); #if 0 TextEncoding utf8 = CreateTextEncoding(kTextEncodingUnicodeDefault, kTextEncodingDefaultVariant, kUnicodeUTF8Format); - char* where = ::JMTextToEncoding(stackTrace, utf8); + char* where = ::JMTextToEncoding(stackTrace, utf8); if (where != NULL) delete[] where; #endif - - SInt16 itemHit = 0; - OSErr result = ::StandardAlert(kAlertPlainAlert, error, explanation, NULL, &itemHit); - } + + SInt16 itemHit = 0; + OSErr result = ::StandardAlert(kAlertPlainAlert, error, explanation, NULL, &itemHit); + } } Boolean MRJContext::createContext() { - JMAWTContextCallbacks callbacks = { - kJMVersion, /* should be set to kJMVersion */ - &requestFrame, /* a new frame is being created. */ - &releaseFrame, /* an existing frame is being destroyed. */ - &getUniqueMenuID, /* a new menu will be created with this id. */ - &exceptionOccurred, /* just some notification that some recent operation caused an exception. You can't do anything really from here. */ - }; - if (mPage != NULL) - return mPage->createContext(&mContext, &callbacks, this); - else - return (::JMNewAWTContext(&mContext, mSessionRef, &callbacks, this) == noErr); + JMAWTContextCallbacks callbacks = { + kJMVersion, /* should be set to kJMVersion */ + &requestFrame, /* a new frame is being created. */ + &releaseFrame, /* an existing frame is being destroyed. */ + &getUniqueMenuID, /* a new menu will be created with this id. */ + &exceptionOccurred, /* just some notification that some recent operation caused an exception. You can't do anything really from here. */ + }; + if (mPage != NULL) + return mPage->createContext(&mContext, &callbacks, this); + else + return (::JMNewAWTContext(&mContext, mSessionRef, &callbacks, this) == noErr); } JMAWTContextRef MRJContext::getContextRef() { - return mContext; + return mContext; } JMAppletViewerRef MRJContext::getViewerRef() @@ -911,113 +911,113 @@ void MRJContext::showDocument(JMAppletViewerRef viewer, JMTextRef urlString, JMTextRef windowName) { - MRJContext* thisContext; - OSStatus status = ::JMGetAppletViewerData(viewer, (JMClientData*)&thisContext); - if (status == noErr) { - Handle urlHandle = ::JMTextToMacOSCStringHandle(urlString); - Handle windowHandle = ::JMTextToMacOSCStringHandle(windowName); - if (urlHandle != NULL && windowHandle != NULL) { - ::HLock(urlHandle); ::HLock(windowHandle); - const char* url = *urlHandle; - const char* target = *windowHandle; - thisContext->showURL(url, target); - } - if (urlHandle != NULL) - ::DisposeHandle(urlHandle); - if (windowHandle != NULL) - ::DisposeHandle(windowHandle); - } + MRJContext* thisContext; + OSStatus status = ::JMGetAppletViewerData(viewer, (JMClientData*)&thisContext); + if (status == noErr) { + Handle urlHandle = ::JMTextToMacOSCStringHandle(urlString); + Handle windowHandle = ::JMTextToMacOSCStringHandle(windowName); + if (urlHandle != NULL && windowHandle != NULL) { + ::HLock(urlHandle); ::HLock(windowHandle); + const char* url = *urlHandle; + const char* target = *windowHandle; + thisContext->showURL(url, target); + } + if (urlHandle != NULL) + ::DisposeHandle(urlHandle); + if (windowHandle != NULL) + ::DisposeHandle(windowHandle); + } } void MRJContext::setStatusMessage(JMAppletViewerRef viewer, JMTextRef statusMsg) { - MRJContext* thisContext; - OSStatus status = ::JMGetAppletViewerData(viewer, (JMClientData*)&thisContext); - if (status == noErr) { - TextEncoding utf8 = CreateTextEncoding(kTextEncodingUnicodeDefault, kTextEncodingDefaultVariant, kUnicodeUTF8Format); - char* message = JMTextToEncoding(statusMsg, utf8); - if (message) { - thisContext->showStatus(message); - delete[] message; - } - } + MRJContext* thisContext; + OSStatus status = ::JMGetAppletViewerData(viewer, (JMClientData*)&thisContext); + if (status == noErr) { + TextEncoding utf8 = CreateTextEncoding(kTextEncodingUnicodeDefault, kTextEncodingDefaultVariant, kUnicodeUTF8Format); + char* message = JMTextToEncoding(statusMsg, utf8); + if (message) { + thisContext->showStatus(message); + delete[] message; + } + } } /* - FIXME: this code should really be called from a true browser thread, so should put message in a queue, and let - idle time processing handle it. Otherwise, the browser will get very confused. + FIXME: this code should really be called from a true browser thread, so should put message in a queue, and let + idle time processing handle it. Otherwise, the browser will get very confused. */ static nsresult getURL(nsISupports* peer, const char* url, const char* target) { - nsresult result = NS_OK; - if (thePluginManager != NULL) { - result = thePluginManager->GetURL(peer, url, target); - } - return result; + nsresult result = NS_OK; + if (thePluginManager != NULL) { + result = thePluginManager->GetURL(peer, url, target); + } + return result; } void AsyncMessage::send(Boolean async) { - // submit the message, and wait for the message to be executed asynchronously. - mSession->sendMessage(this, async); + // submit the message, and wait for the message to be executed asynchronously. + mSession->sendMessage(this, async); } class GetURLMessage : public AsyncMessage { - MRJPluginInstance* mPluginInstance; - char* mURL; - char* mTarget; + MRJPluginInstance* mPluginInstance; + char* mURL; + char* mTarget; public: - GetURLMessage(MRJPluginInstance* pluginInstance, const char* url, const char* target); - ~GetURLMessage(); + GetURLMessage(MRJPluginInstance* pluginInstance, const char* url, const char* target); + ~GetURLMessage(); - virtual void execute(); + virtual void execute(); }; GetURLMessage::GetURLMessage(MRJPluginInstance* pluginInstance, const char* url, const char* target) - : AsyncMessage(pluginInstance->getSession()), - mPluginInstance(pluginInstance), mURL(::strdup(url)), mTarget(::strdup(target)) + : AsyncMessage(pluginInstance->getSession()), + mPluginInstance(pluginInstance), mURL(::strdup(url)), mTarget(::strdup(target)) { - NS_ADDREF(mPluginInstance); + NS_ADDREF(mPluginInstance); } GetURLMessage::~GetURLMessage() { - if (mURL != NULL) - delete[] mURL; - if (mTarget != NULL) - delete[] mTarget; + if (mURL != NULL) + delete[] mURL; + if (mTarget != NULL) + delete[] mTarget; - NS_RELEASE(mPluginInstance); + NS_RELEASE(mPluginInstance); } void GetURLMessage::execute() { - // get the URL. - nsIPluginInstance* pluginInstance = mPluginInstance; - nsresult result = thePluginManager->GetURL(pluginInstance, mURL, mTarget); - delete this; + // get the URL. + nsIPluginInstance* pluginInstance = mPluginInstance; + nsresult result = thePluginManager->GetURL(pluginInstance, mURL, mTarget); + delete this; } void MRJContext::showURL(const char* url, const char* target) { - if (thePluginManager != NULL) { + if (thePluginManager != NULL) { #if 0 - GetURLMessage* message = new GetURLMessage(mPluginInstance, url, target); - message->send(true); + GetURLMessage* message = new GetURLMessage(mPluginInstance, url, target); + message->send(true); #else - nsIPluginInstance* pluginInstance = mPluginInstance; - thePluginManager->GetURL(pluginInstance, url, target); + nsIPluginInstance* pluginInstance = mPluginInstance; + thePluginManager->GetURL(pluginInstance, url, target); #endif - } + } } void MRJContext::showStatus(const char* message) { - ensureValidPort(); - - if (mPeer != NULL) - mPeer->ShowStatus(message); + ensureValidPort(); + + if (mPeer != NULL) + mPeer->ShowStatus(message); } static SInt16 nextMenuId = 20000; @@ -1025,168 +1025,168 @@ SInt16 MRJContext::allocateMenuID(Boolean isSubmenu) { - // FIXME: can use more centralized approach to managing menu IDs which can be shared across all contexts. - if (thePluginManager2 != NULL) { - PRInt16 menuID = -1; - nsIEventHandler* eventHandler = mPluginInstance; - thePluginManager2->AllocateMenuID(eventHandler, isSubmenu, &menuID); - return menuID; - } else - return (isSubmenu ? nextMenuPopupId++ : nextMenuId++); + // FIXME: can use more centralized approach to managing menu IDs which can be shared across all contexts. + if (thePluginManager2 != NULL) { + PRInt16 menuID = -1; + nsIEventHandler* eventHandler = mPluginInstance; + thePluginManager2->AllocateMenuID(eventHandler, isSubmenu, &menuID); + return menuID; + } else + return (isSubmenu ? nextMenuPopupId++ : nextMenuId++); } OSStatus MRJContext::createFrame(JMFrameRef frameRef, JMFrameKind kind, const Rect* initialBounds, Boolean resizeable) { - OSStatus status = memFullErr; - MRJFrame* frame = NULL; - - // The first frame created will always be for the applet viewer. - if (mViewerFrame == NULL) { - // bind this newly created frame to this context, and vice versa. - mViewerFrame = frameRef; - frame = new AppletViewerFrame(frameRef, this); - - // make sure the frame's clipping is up-to-date. - synchronizeClipping(); - } else if (thePluginManager2 != NULL) { - // Can only do this safely if we are using the new API. - frame = new TopLevelFrame(mPluginInstance, frameRef, kind, initialBounds, resizeable); - } else { - // Try to create a frame that lives in a newly created browser window. - frame = new EmbeddedFrame(mPluginInstance, frameRef, kind, initialBounds, resizeable); - } - - if (frame != NULL) - status = ::JMSetFrameData(frameRef, frame); - - return status; + OSStatus status = memFullErr; + MRJFrame* frame = NULL; + + // The first frame created will always be for the applet viewer. + if (mViewerFrame == NULL) { + // bind this newly created frame to this context, and vice versa. + mViewerFrame = frameRef; + frame = new AppletViewerFrame(frameRef, this); + + // make sure the frame's clipping is up-to-date. + synchronizeClipping(); + } else if (thePluginManager2 != NULL) { + // Can only do this safely if we are using the new API. + frame = new TopLevelFrame(mPluginInstance, frameRef, kind, initialBounds, resizeable); + } else { + // Try to create a frame that lives in a newly created browser window. + frame = new EmbeddedFrame(mPluginInstance, frameRef, kind, initialBounds, resizeable); + } + + if (frame != NULL) + status = ::JMSetFrameData(frameRef, frame); + + return status; } Boolean MRJContext::appletLoaded() { - return (mViewer != NULL); + return (mViewer != NULL); } void MRJContext::setProxyInfoForURL(char * url, JMProxyType proxyType) { - /* - * We then call 'nsIPluginManager2::FindProxyForURL' which will return - * proxy information which we can parse and set via JMSetProxyInfo. - */ - char* proxy = NULL; - nsresult rv = thePluginManager2->FindProxyForURL(url, &proxy); - if (NS_SUCCEEDED(rv) && proxy != NULL) { - /* See if a proxy was specified */ - if (strcmp("DIRECT", proxy) != 0) { - JMProxyInfo proxyInfo; - proxyInfo.useProxy = true; - char* space = strchr(proxy, ' '); - if (space != NULL) { - char* host = space + 1; - char* colon = ::strchr(host, ':'); - int length = (colon - host); - if (length < sizeof(proxyInfo.proxyHost)) { - strncpy(proxyInfo.proxyHost, host, length); - proxyInfo.proxyPort = atoi(colon + 1); - ::JMSetProxyInfo(mSessionRef, proxyType, &proxyInfo); + /* + * We then call 'nsIPluginManager2::FindProxyForURL' which will return + * proxy information which we can parse and set via JMSetProxyInfo. + */ + char* proxy = NULL; + nsresult rv = thePluginManager2->FindProxyForURL(url, &proxy); + if (NS_SUCCEEDED(rv) && proxy != NULL) { + /* See if a proxy was specified */ + if (strcmp("DIRECT", proxy) != 0) { + JMProxyInfo proxyInfo; + proxyInfo.useProxy = true; + char* space = strchr(proxy, ' '); + if (space != NULL) { + char* host = space + 1; + char* colon = ::strchr(host, ':'); + int length = (colon - host); + if (length < sizeof(proxyInfo.proxyHost)) { + strncpy(proxyInfo.proxyHost, host, length); + proxyInfo.proxyPort = atoi(colon + 1); + ::JMSetProxyInfo(mSessionRef, proxyType, &proxyInfo); } } - } - - delete[] proxy; - } + } + + delete[] proxy; + } } Boolean MRJContext::loadApplet() { - static JMAppletSecurity security = { - kJMVersion, /* should be set to kJMVersion */ - eAppletHostAccess, /* can this applet access network resources */ - eLocalAppletAccess, /* can this applet access network resources */ - true, /* restrict access to system packages (com.apple.*, sun.*, netscape.*) also found in the property "mrj.security.system.access" */ - true, /* restrict classes from loading system packages (com.apple.*, sun.*, netscape.*) also found in the property "mrj.security.system.define" */ - true, /* restrict access to application packages found in the property "mrj.security.application.access" */ - true, /* restrict access to application packages found in the property "mrj.security.application.access" */ - }; - static JMAppletViewerCallbacks callbacks = { - kJMVersion, /* should be set to kJMVersion */ - &showDocument, /* go to a url, optionally in a new window */ - &setStatusMessage, /* applet changed status message */ - }; - OSStatus status; - - /* Added by Mark: */ - /* - * Set proxy info - * It is only set if the new enhanced Plugin Manager exists. - */ - if (thePluginManager2 != NULL) { - /* Sample URL's to use for getting the HTTP proxy and FTP proxy */ - setProxyInfoForURL("http://www.mozilla.org/", eHTTPProxy); - setProxyInfoForURL("ftp://ftp.mozilla.org/", eFTPProxy); - } - /* End set proxy info code */ - - status = ::JMNewAppletViewer(&mViewer, mContext, mLocator, 0, - &security, &callbacks, this); - if (status == noErr) { - status = ::JMSetAppletViewerData(mViewer, JMClientData(this)); - status = ::JMReloadApplet(mViewer); - } - - if (status == noErr) { - // for grins, force the applet to load right away, so we can report any error we might encounter eagerly. - // jobject appletObject = getApplet(); - } - - return (status == noErr); + static JMAppletSecurity security = { + kJMVersion, /* should be set to kJMVersion */ + eAppletHostAccess, /* can this applet access network resources */ + eLocalAppletAccess, /* can this applet access network resources */ + true, /* restrict access to system packages (com.apple.*, sun.*, netscape.*) also found in the property "mrj.security.system.access" */ + true, /* restrict classes from loading system packages (com.apple.*, sun.*, netscape.*) also found in the property "mrj.security.system.define" */ + true, /* restrict access to application packages found in the property "mrj.security.application.access" */ + true, /* restrict access to application packages found in the property "mrj.security.application.access" */ + }; + static JMAppletViewerCallbacks callbacks = { + kJMVersion, /* should be set to kJMVersion */ + &showDocument, /* go to a url, optionally in a new window */ + &setStatusMessage, /* applet changed status message */ + }; + OSStatus status; + + /* Added by Mark: */ + /* + * Set proxy info + * It is only set if the new enhanced Plugin Manager exists. + */ + if (thePluginManager2 != NULL) { + /* Sample URL's to use for getting the HTTP proxy and FTP proxy */ + setProxyInfoForURL("http://www.mozilla.org/", eHTTPProxy); + setProxyInfoForURL("ftp://ftp.mozilla.org/", eFTPProxy); + } + /* End set proxy info code */ + + status = ::JMNewAppletViewer(&mViewer, mContext, mLocator, 0, + &security, &callbacks, this); + if (status == noErr) { + status = ::JMSetAppletViewerData(mViewer, JMClientData(this)); + status = ::JMReloadApplet(mViewer); + } + + if (status == noErr) { + // for grins, force the applet to load right away, so we can report any error we might encounter eagerly. + // jobject appletObject = getApplet(); + } + + return (status == noErr); } void MRJContext::suspendApplet() { - if (mViewer != NULL) - ::JMSuspendApplet(mViewer); + if (mViewer != NULL) + ::JMSuspendApplet(mViewer); } void MRJContext::resumeApplet() { - if (mViewer != NULL) - ::JMResumeApplet(mViewer); + if (mViewer != NULL) + ::JMResumeApplet(mViewer); } jobject MRJContext::getApplet() { - if (appletLoaded() && &::JMGetAppletJNIObject != NULL) { - JNIEnv* env = ::JMGetCurrentEnv(mSessionRef); - jobject appletObject = ::JMGetAppletJNIObject(mViewer, env); - if (appletObject == NULL) { - // Give MRJ some time to try to comply. 100 calls to JMIdle should be enough. - // 10 seconds should be enough. Could ask the user... - UInt32 deadline = ::TickCount() + 600; - while (appletObject == NULL && ::TickCount() < deadline) { - mSession->idle(kDefaultJMTime); - appletObject = ::JMGetAppletJNIObject(mViewer, env); - } - if (appletObject == NULL) { - // assume the applet's hosed. - ::JMDisposeAppletViewer(mViewer); - mViewer = NULL; - // Let the user know the applet failed to load. - if (appearanceManagerExists()) { - SInt16 itemHit = 0; - Str255 appletURL = { "\pUnknown APPLET URL" }; - if (mDocumentBase != NULL) { - appletURL[0] = ::strlen(mDocumentBase); - ::BlockMoveData(mDocumentBase, appletURL + 1, mDocumentBase[0]); - } - ::StandardAlert(kAlertPlainAlert, "\pApplet failed to load from URL:", appletURL, NULL, &itemHit); - } - } - } - return appletObject; - } - return NULL; + if (appletLoaded() && &::JMGetAppletJNIObject != NULL) { + JNIEnv* env = ::JMGetCurrentEnv(mSessionRef); + jobject appletObject = ::JMGetAppletJNIObject(mViewer, env); + if (appletObject == NULL) { + // Give MRJ some time to try to comply. 100 calls to JMIdle should be enough. + // 10 seconds should be enough. Could ask the user... + UInt32 deadline = ::TickCount() + 600; + while (appletObject == NULL && ::TickCount() < deadline) { + mSession->idle(kDefaultJMTime); + appletObject = ::JMGetAppletJNIObject(mViewer, env); + } + if (appletObject == NULL) { + // assume the applet's hosed. + ::JMDisposeAppletViewer(mViewer); + mViewer = NULL; + // Let the user know the applet failed to load. + if (appearanceManagerExists()) { + SInt16 itemHit = 0; + Str255 appletURL = { "\pUnknown APPLET URL" }; + if (mDocumentBase != NULL) { + appletURL[0] = ::strlen(mDocumentBase); + ::BlockMoveData(mDocumentBase, appletURL + 1, mDocumentBase[0]); + } + ::StandardAlert(kAlertPlainAlert, "\pApplet failed to load from URL:", appletURL, NULL, &itemHit); + } + } + } + return appletObject; + } + return NULL; } /** @@ -1197,161 +1197,161 @@ void MRJContext::drawApplet() { - // We assume the proper coordinate system for the frame has - // already been set up. - if (appletLoaded()) { + // We assume the proper coordinate system for the frame has + // already been set up. + if (appletLoaded()) { #if DEBUG_CLIPPING - nsPluginPort* npPort = (nsPluginPort*) mCache.window; - GrafPtr framePort = GrafPtr(npPort->port); - RgnHandle oldClip = NewRgn(); - if (oldClip != NULL) { - CopyRgn(framePort->clipRgn, oldClip); - SetClip(mPluginClipping); - InvertRgn(mPluginClipping); - SetClip(oldClip); - DisposeRgn(oldClip); - } + nsPluginPort* npPort = (nsPluginPort*) mCache.window; + GrafPtr framePort = GrafPtr(npPort->port); + RgnHandle oldClip = NewRgn(); + if (oldClip != NULL) { + CopyRgn(framePort->clipRgn, oldClip); + SetClip(mPluginClipping); + InvertRgn(mPluginClipping); + SetClip(oldClip); + DisposeRgn(oldClip); + } #endif - // ::JMFrameUpdate(mViewerFrame, framePort->visRgn); - // OSStatus status = ::JMFrameUpdate(mViewerFrame, framePort->clipRgn); - OSStatus status = ::JMFrameUpdate(mViewerFrame, mPluginClipping); - } + // ::JMFrameUpdate(mViewerFrame, framePort->visRgn); + // OSStatus status = ::JMFrameUpdate(mViewerFrame, framePort->clipRgn); + OSStatus status = ::JMFrameUpdate(mViewerFrame, mPluginClipping); + } } void MRJContext::printApplet(nsPluginWindow* printingWindow) { - jobject frameObject = NULL; - jclass utilsClass = NULL; - OSStatus status = noErr; - JNIEnv* env = ::JMGetCurrentEnv(mSessionRef); - - // put the printing port into window coordinates: (0, 0) in upper left corner. - GrafPtr printingPort = GrafPtr(printingWindow->window->port); - LocalPort localPort(printingPort); - localPort.Enter(); - ::ClipRect((Rect*)&printingWindow->clipRect); - - do { - // try to use the printing API, if that fails, fall back on netscape.oji.AWTUtils.printContainer(). - if (&::JMDrawFrameInPort != NULL) { - Point frameOrigin = { printingWindow->y, printingWindow->x }; - status = ::JMDrawFrameInPort(mViewerFrame, printingPort, frameOrigin, printingPort->clipRgn, false); - if (status == noErr) break; - } - - // get the frame object to print. - frameObject = ::JMGetAWTFrameJNIObject(mViewerFrame, env); - if (frameObject == NULL) break; - - // call the print methods of the applet viewer's frame. - jclass utilsClass = env->FindClass("netscape/oji/AWTUtils"); - if (utilsClass == NULL) break; - jmethodID printContainerMethod = env->GetStaticMethodID(utilsClass, "printContainer", "(Ljava/awt/Container;IIILjava/lang/Object;)V"); - if (printContainerMethod == NULL) break; - - // create a monitor to synchronize with. - MRJMonitor notifier(mSession); - - // start the asynchronous print call. - jvalue args[5]; - args[0].l = frameObject; - args[1].i = jint(printingPort); - args[2].i = jint(printingWindow->x); - args[3].i = jint(printingWindow->y); - args[4].l = notifier.getObject(); - OSStatus status = ::JMExecJNIStaticMethodInContext(mContext, env, utilsClass, printContainerMethod, 5, args); - - // now, wait for the print method to complete. - if (status == noErr) - notifier.wait(); - } while (0); - - // restore the origin & port. - localPort.Exit(); - - if (frameObject != NULL) - env->DeleteLocalRef(frameObject); - if (utilsClass != NULL) - env->DeleteLocalRef(utilsClass); + jobject frameObject = NULL; + jclass utilsClass = NULL; + OSStatus status = noErr; + JNIEnv* env = ::JMGetCurrentEnv(mSessionRef); + + // put the printing port into window coordinates: (0, 0) in upper left corner. + GrafPtr printingPort = GrafPtr(printingWindow->window->port); + LocalPort localPort(printingPort); + localPort.Enter(); + ::ClipRect((Rect*)&printingWindow->clipRect); + + do { + // try to use the printing API, if that fails, fall back on netscape.oji.AWTUtils.printContainer(). + if (&::JMDrawFrameInPort != NULL) { + Point frameOrigin = { printingWindow->y, printingWindow->x }; + status = ::JMDrawFrameInPort(mViewerFrame, printingPort, frameOrigin, printingPort->clipRgn, false); + if (status == noErr) break; + } + + // get the frame object to print. + frameObject = ::JMGetAWTFrameJNIObject(mViewerFrame, env); + if (frameObject == NULL) break; + + // call the print methods of the applet viewer's frame. + jclass utilsClass = env->FindClass("netscape/oji/AWTUtils"); + if (utilsClass == NULL) break; + jmethodID printContainerMethod = env->GetStaticMethodID(utilsClass, "printContainer", "(Ljava/awt/Container;IIILjava/lang/Object;)V"); + if (printContainerMethod == NULL) break; + + // create a monitor to synchronize with. + MRJMonitor notifier(mSession); + + // start the asynchronous print call. + jvalue args[5]; + args[0].l = frameObject; + args[1].i = jint(printingPort); + args[2].i = jint(printingWindow->x); + args[3].i = jint(printingWindow->y); + args[4].l = notifier.getObject(); + OSStatus status = ::JMExecJNIStaticMethodInContext(mContext, env, utilsClass, printContainerMethod, 5, args); + + // now, wait for the print method to complete. + if (status == noErr) + notifier.wait(); + } while (0); + + // restore the origin & port. + localPort.Exit(); + + if (frameObject != NULL) + env->DeleteLocalRef(frameObject); + if (utilsClass != NULL) + env->DeleteLocalRef(utilsClass); } void MRJContext::activate(Boolean active) { - if (mViewerFrame != NULL) { - ::JMFrameActivate(mViewerFrame, active); - mIsActive = active; - } else { - mIsActive = false; - } + if (mViewerFrame != NULL) { + ::JMFrameActivate(mViewerFrame, active); + mIsActive = active; + } else { + mIsActive = false; + } } void MRJContext::resume(Boolean inFront) { // printf("mrjcontext::resume\n"); - if (mViewerFrame != NULL) { - ::JMFrameResume(mViewerFrame, inFront); - } + if (mViewerFrame != NULL) { + ::JMFrameResume(mViewerFrame, inFront); + } } void MRJContext::click(const EventRecord* event, MRJFrame* appletFrame) { - // inspectWindow(); + // inspectWindow(); // printf("mrjcontext::click\n"); - nsPluginPort* npPort = mPluginWindow->window; - - // make the plugin's port current, and move its origin to (0, 0). - LocalPort port(GrafPtr(npPort->port)); - port.Enter(); - - // will we always be called in the right coordinate system? - Point localWhere = event->where; - ::GlobalToLocal(&localWhere); - nsPluginRect& clipRect = mCachedClipRect; - Rect bounds = { clipRect.top, clipRect.left, clipRect.bottom, clipRect.right }; - if (PtInRect(localWhere, &bounds)) { - localToFrame(&localWhere); - appletFrame->click(event, localWhere); - } - - // restore the plugin port's origin, and restore the current port. - port.Exit(); + nsPluginPort* npPort = mPluginWindow->window; + + // make the plugin's port current, and move its origin to (0, 0). + LocalPort port(GrafPtr(npPort->port)); + port.Enter(); + + // will we always be called in the right coordinate system? + Point localWhere = event->where; + ::GlobalToLocal(&localWhere); + nsPluginRect& clipRect = mCachedClipRect; + Rect bounds = { clipRect.top, clipRect.left, clipRect.bottom, clipRect.right }; + if (PtInRect(localWhere, &bounds)) { + localToFrame(&localWhere); + appletFrame->click(event, localWhere); + } + + // restore the plugin port's origin, and restore the current port. + port.Exit(); } void MRJContext::keyPress(long message, short modifiers) { - if (mViewerFrame != NULL) { - ::JMFrameKey(mViewerFrame, message & charCodeMask, - (message & keyCodeMask) >> 8, modifiers); - } + if (mViewerFrame != NULL) { + ::JMFrameKey(mViewerFrame, message & charCodeMask, + (message & keyCodeMask) >> 8, modifiers); + } } void MRJContext::keyRelease(long message, short modifiers) { - if (mViewerFrame != NULL) { - ::JMFrameKeyRelease(mViewerFrame, message & charCodeMask, - (message & keyCodeMask) >> 8, modifiers); - } + if (mViewerFrame != NULL) { + ::JMFrameKeyRelease(mViewerFrame, message & charCodeMask, + (message & keyCodeMask) >> 8, modifiers); + } } void MRJContext::idle(short modifiers) { - // inspectWindow(); + // inspectWindow(); // printf("mrjcontext::idle\n"); - // Put the port in to proper window coordinates. - nsPluginPort* npPort = mPluginWindow->window; - LocalPort port(GrafPtr(npPort->port)); - port.Enter(); - - Point pt; - ::GetMouse(&pt); - localToFrame(&pt); - ::JMFrameMouseOver(mViewerFrame, pt, modifiers); - - port.Exit(); + // Put the port in to proper window coordinates. + nsPluginPort* npPort = mPluginWindow->window; + LocalPort port(GrafPtr(npPort->port)); + port.Enter(); + + Point pt; + ::GetMouse(&pt); + localToFrame(&pt); + ::JMFrameMouseOver(mViewerFrame, pt, modifiers); + + port.Exit(); } // interim routine for compatibility between OLD plugin interface and new. @@ -1362,55 +1362,55 @@ void MRJContext::setWindow(nsPluginWindow* pluginWindow) { - // don't do anything if the AWTContext hasn't been created yet. - if (mContext != NULL) { - if (pluginWindow != NULL) { - mPluginWindow = pluginWindow; - - // establish the GrafPort the plugin will draw in. - mPluginPort = pluginWindow->window->port; - - if (! appletLoaded()) - loadApplet(); - } else { - // tell MRJ the window has gone away. - mPluginWindow = NULL; - - // use a single, 0x0, empty port for all future drawing. - mPluginPort = getEmptyPort(); - } - synchronizeClipping(); + // don't do anything if the AWTContext hasn't been created yet. + if (mContext != NULL) { + if (pluginWindow != NULL) { + mPluginWindow = pluginWindow; + + // establish the GrafPort the plugin will draw in. + mPluginPort = pluginWindow->window->port; + + if (! appletLoaded()) + loadApplet(); + } else { + // tell MRJ the window has gone away. + mPluginWindow = NULL; + + // use a single, 0x0, empty port for all future drawing. + mPluginPort = getEmptyPort(); + } + synchronizeClipping(); } } static Boolean equalRect(const nsPluginRect* r1, const nsPluginRect* r2) { - SInt32* r1p = (SInt32*)r1; - SInt32* r2p = (SInt32*)r2; - return (r1p[0] == r2p[0] && r1p[1] == r2p[1]); + SInt32* r1p = (SInt32*)r1; + SInt32* r2p = (SInt32*)r2; + return (r1p[0] == r2p[0] && r1p[1] == r2p[1]); } Boolean MRJContext::inspectWindow() { - // don't bother looking, if the applet viewer frame doesn't exist yet. - if (mViewerFrame == NULL) - return false; - - Boolean recomputeClipping = false; - - if (mPluginWindow != NULL) { - // Check for origin or clipping changes. - nsPluginPort* npPort = mPluginWindow->window; - if (mCachedOrigin.x != npPort->portx || mCachedOrigin.y != npPort->porty || !equalRect(&mCachedClipRect, &mPluginWindow->clipRect)) { - // transfer over values to the window cache. - recomputeClipping = true; - } - } - - if (recomputeClipping) - synchronizeClipping(); - - return recomputeClipping; + // don't bother looking, if the applet viewer frame doesn't exist yet. + if (mViewerFrame == NULL) + return false; + + Boolean recomputeClipping = false; + + if (mPluginWindow != NULL) { + // Check for origin or clipping changes. + nsPluginPort* npPort = mPluginWindow->window; + if (mCachedOrigin.x != npPort->portx || mCachedOrigin.y != npPort->porty || !equalRect(&mCachedClipRect, &mPluginWindow->clipRect)) { + // transfer over values to the window cache. + recomputeClipping = true; + } + } + + if (recomputeClipping) + synchronizeClipping(); + + return recomputeClipping; } /** @@ -1422,160 +1422,160 @@ */ void MRJContext::synchronizeClipping() { - // this is called on update events to make sure the clipping region is in sync with the browser's. - if (mPluginWindow != NULL) { - // plugin clipping is intersection of clipRgn and the clipRect. + // this is called on update events to make sure the clipping region is in sync with the browser's. + if (mPluginWindow != NULL) { + // plugin clipping is intersection of clipRgn and the clipRect. nsPluginRect clipRect = mPluginWindow->clipRect; nsPluginPort* pluginPort = mPluginWindow->window; clipRect.left += pluginPort->portx, clipRect.right += pluginPort->portx; clipRect.top += pluginPort->porty, clipRect.bottom += pluginPort->porty; - ::SetRectRgn(mPluginClipping, clipRect.left, clipRect.top, clipRect.right, clipRect.bottom); - } else { - ::SetEmptyRgn(mPluginClipping); - } + ::SetRectRgn(mPluginClipping, clipRect.left, clipRect.top, clipRect.right, clipRect.bottom); + } else { + ::SetEmptyRgn(mPluginClipping); + } synchronizeVisibility(); } MRJFrame* MRJContext::findFrame(WindowRef window) { - MRJFrame* frame = NULL; + MRJFrame* frame = NULL; - // synchronizeVisibility(); - - // locates the frame corresponding to this window. - if (window == NULL || (CGrafPtr(window) == mPluginPort) && mViewerFrame != NULL) { - frame = getFrame(mViewerFrame); - } else { - // Scan the available frames for this context, and see if any of them correspond to this window. - UInt32 frameCount; - OSStatus status = ::JMCountAWTContextFrames(mContext, &frameCount); - if (status == noErr) { - for (UInt32 frameIndex = 1; frameIndex < frameCount; frameIndex++) { - JMFrameRef frameRef; - status = ::JMGetAWTContextFrame(mContext, frameIndex, &frameRef); - frame = getFrame(frameRef); - TopLevelFrame* tlFrame = dynamic_cast(frame); - if (tlFrame != NULL && tlFrame->getWindow() == window) - break; - } - } - } - - return frame; + // synchronizeVisibility(); + + // locates the frame corresponding to this window. + if (window == NULL || (CGrafPtr(window) == mPluginPort) && mViewerFrame != NULL) { + frame = getFrame(mViewerFrame); + } else { + // Scan the available frames for this context, and see if any of them correspond to this window. + UInt32 frameCount; + OSStatus status = ::JMCountAWTContextFrames(mContext, &frameCount); + if (status == noErr) { + for (UInt32 frameIndex = 1; frameIndex < frameCount; frameIndex++) { + JMFrameRef frameRef; + status = ::JMGetAWTContextFrame(mContext, frameIndex, &frameRef); + frame = getFrame(frameRef); + TopLevelFrame* tlFrame = dynamic_cast(frame); + if (tlFrame != NULL && tlFrame->getWindow() == window) + break; + } + } + } + + return frame; } GrafPtr MRJContext::getPort() { #if 0 - if (mPluginWindow != NULL) { - nsPluginPort* npPort = mPluginWindow->window; - return GrafPtr(npPort->port); - } - return NULL; + if (mPluginWindow != NULL) { + nsPluginPort* npPort = mPluginWindow->window; + return GrafPtr(npPort->port); + } + return NULL; #endif - return GrafPtr(mPluginPort); + return GrafPtr(mPluginPort); } void MRJContext::localToFrame(Point* pt) { - if (mPluginWindow != NULL) { - // transform mouse to frame coordinates. - nsPluginPort* npPort = mPluginWindow->window; - pt->v += npPort->porty; - pt->h += npPort->portx; - } + if (mPluginWindow != NULL) { + // transform mouse to frame coordinates. + nsPluginPort* npPort = mPluginWindow->window; + pt->v += npPort->porty; + pt->h += npPort->portx; + } } void MRJContext::ensureValidPort() { - if (mPluginWindow != NULL) { - nsPluginPort* npPort = mPluginWindow->window; - if (npPort == NULL) - mPluginPort = getEmptyPort(); - ::SetPort(GrafPtr(mPluginPort)); - } + if (mPluginWindow != NULL) { + nsPluginPort* npPort = mPluginWindow->window; + if (npPort == NULL) + mPluginPort = getEmptyPort(); + ::SetPort(GrafPtr(mPluginPort)); + } } static void blinkRgn(RgnHandle rgn) { - ::InvertRgn(rgn); - UInt32 ticks = ::TickCount(); - while (::TickCount() - ticks < 10) ; - ::InvertRgn(rgn); + ::InvertRgn(rgn); + UInt32 ticks = ::TickCount(); + while (::TickCount() - ticks < 10) ; + ::InvertRgn(rgn); } void MRJContext::synchronizeVisibility() { - // always update the cached information. - if (mViewerFrame != NULL) { - if (mPluginWindow != NULL) { + // always update the cached information. + if (mViewerFrame != NULL) { + if (mPluginWindow != NULL) { nsPluginRect oldClipRect = mCachedClipRect; nsPluginPort* pluginPort = mPluginWindow->window; - mCachedOrigin.x = pluginPort->portx; - mCachedOrigin.y = pluginPort->porty; - mCachedClipRect = mPluginWindow->clipRect; - - // compute the frame's origin and clipping. - - // JManager wants the origin expressed in window coordinates. - // npWindow refers to the entire mozilla view port whereas the nport - // refers to the actual rendered html window. - Point frameOrigin = { -pluginPort->porty, -pluginPort->portx }; - GrafPtr framePort = (GrafPtr)mPluginPort; - OSStatus status = ::JMSetFrameVisibility(mViewerFrame, framePort, - frameOrigin, mPluginClipping); + mCachedOrigin.x = pluginPort->portx; + mCachedOrigin.y = pluginPort->porty; + mCachedClipRect = mPluginWindow->clipRect; + + // compute the frame's origin and clipping. + + // JManager wants the origin expressed in window coordinates. + // npWindow refers to the entire mozilla view port whereas the nport + // refers to the actual rendered html window. + Point frameOrigin = { -pluginPort->porty, -pluginPort->portx }; + GrafPtr framePort = (GrafPtr)mPluginPort; + OSStatus status = ::JMSetFrameVisibility(mViewerFrame, framePort, + frameOrigin, mPluginClipping); // Invalidate the old clip rectangle, so that any bogus drawing that may // occurred at the old location, will be corrected. - LocalPort port(framePort); + LocalPort port(framePort); port.Enter(); - ::InvalRect((Rect*)&oldClipRect); - ::InvalRect((Rect*)&mCachedClipRect); - port.Exit(); + ::InvalRect((Rect*)&oldClipRect); + ::InvalRect((Rect*)&mCachedClipRect); + port.Exit(); } else { Point frameOrigin = { 0, 0 }; - OSStatus status = ::JMSetFrameVisibility(mViewerFrame, GrafPtr(mPluginPort), - frameOrigin, mPluginClipping); + OSStatus status = ::JMSetFrameVisibility(mViewerFrame, GrafPtr(mPluginPort), + frameOrigin, mPluginClipping); } } } void MRJContext::showFrames() { - UInt32 frameCount; - OSStatus status = ::JMCountAWTContextFrames(mContext, &frameCount); - if (status == noErr) { - for (UInt32 frameIndex = 0; frameIndex < frameCount; frameIndex++) { - JMFrameRef frameRef; - status = ::JMGetAWTContextFrame(mContext, frameIndex, &frameRef); - if (status == noErr) { - ::JMFrameShowHide(frameRef, true); -// MRJFrame* frame = getFrame(frameRef); -// if (frame != NULL) -// frame->focusEvent(false); - } - } - } + UInt32 frameCount; + OSStatus status = ::JMCountAWTContextFrames(mContext, &frameCount); + if (status == noErr) { + for (UInt32 frameIndex = 0; frameIndex < frameCount; frameIndex++) { + JMFrameRef frameRef; + status = ::JMGetAWTContextFrame(mContext, frameIndex, &frameRef); + if (status == noErr) { + ::JMFrameShowHide(frameRef, true); +// MRJFrame* frame = getFrame(frameRef); +// if (frame != NULL) +// frame->focusEvent(false); + } + } + } } void MRJContext::hideFrames() { - UInt32 frameCount; - OSStatus status = ::JMCountAWTContextFrames(mContext, &frameCount); - if (status == noErr) { - for (UInt32 frameIndex = 0; frameIndex < frameCount; frameIndex++) { - JMFrameRef frameRef; - status = ::JMGetAWTContextFrame(mContext, frameIndex, &frameRef); - if (status == noErr) { - // make sure the frame doesn't have the focus. - MRJFrame* frame = getFrame(frameRef); - if (frame != NULL) - frame->focusEvent(false); - ::JMFrameShowHide(frameRef, false); - } - } - } + UInt32 frameCount; + OSStatus status = ::JMCountAWTContextFrames(mContext, &frameCount); + if (status == noErr) { + for (UInt32 frameIndex = 0; frameIndex < frameCount; frameIndex++) { + JMFrameRef frameRef; + status = ::JMGetAWTContextFrame(mContext, frameIndex, &frameRef); + if (status == noErr) { + // make sure the frame doesn't have the focus. + MRJFrame* frame = getFrame(frameRef); + if (frame != NULL) + frame->focusEvent(false); + ::JMFrameShowHide(frameRef, false); + } + } + } } /** @@ -1585,93 +1585,93 @@ */ void MRJContext::releaseFrames() { - UInt32 frameCount; - OSStatus status = ::JMCountAWTContextFrames(mContext, &frameCount); - if (status == noErr) { - for (UInt32 frameIndex = 0; frameIndex < frameCount; frameIndex++) { - JMFrameRef frameRef = NULL; - status = ::JMGetAWTContextFrame(mContext, frameIndex, &frameRef); - if (status == noErr) { - frameShowHide(frameRef, false); - releaseFrame(mContext, frameRef); - } - } - } + UInt32 frameCount; + OSStatus status = ::JMCountAWTContextFrames(mContext, &frameCount); + if (status == noErr) { + for (UInt32 frameIndex = 0; frameIndex < frameCount; frameIndex++) { + JMFrameRef frameRef = NULL; + status = ::JMGetAWTContextFrame(mContext, frameIndex, &frameRef); + if (status == noErr) { + frameShowHide(frameRef, false); + releaseFrame(mContext, frameRef); + } + } + } } void MRJContext::setDocumentBase(const char* documentBase) { - if (mDocumentBase != NULL) - mDocumentBase = NULL; - mDocumentBase = ::strdup(documentBase); + if (mDocumentBase != NULL) + mDocumentBase = NULL; + mDocumentBase = ::strdup(documentBase); } const char* MRJContext::getDocumentBase() { - return mDocumentBase; + return mDocumentBase; } void MRJContext::setAppletHTML(const char* appletHTML, nsPluginTagType tagType) { - if (mAppletHTML != NULL) - delete[] mAppletHTML; - + if (mAppletHTML != NULL) + delete[] mAppletHTML; + switch (tagType) { case nsPluginTagType_Applet: - mAppletHTML = ::strdup(appletHTML); - break; - - case nsPluginTagType_Object: - { - // If the HTML isn't an element, but is an element, then - // transform it so MRJ can deal with it gracefully. it sure would be - // nice if some DOM code would deal with this for us. This code - // is fragile, because it assumes the case of the classid attribute. + mAppletHTML = ::strdup(appletHTML); + break; + + case nsPluginTagType_Object: + { + // If the HTML isn't an element, but is an element, then + // transform it so MRJ can deal with it gracefully. it sure would be + // nice if some DOM code would deal with this for us. This code + // is fragile, because it assumes the case of the classid attribute. // edit the element, converting to , // classid="java:JitterText.class" to code="JitterText.class", // and to . - string element(appletHTML); - - const char kAppletTag[] = "applet"; - const size_t kAppleTagSize = sizeof(kAppletTag) - 1; - string::size_type startTag = element.find(""); - if (endTag != string::npos) { - element.replace(endTag + 2, kAppleTagSize, kAppletTag); - } - - const char kClassIDAttribute[] = "classid=\"java:"; - const char kCodeAttribute[] = "code=\""; - size_t kClassIDAttributeSize = sizeof(kClassIDAttribute) - 1; - string::size_type classID = element.find(kClassIDAttribute); - if (classID != string::npos) { - element.replace(classID, kClassIDAttributeSize, kCodeAttribute); - } - - mAppletHTML = ::strdup(element.c_str()); - } - break; + string element(appletHTML); + + const char kAppletTag[] = "applet"; + const size_t kAppleTagSize = sizeof(kAppletTag) - 1; + string::size_type startTag = element.find(""); + if (endTag != string::npos) { + element.replace(endTag + 2, kAppleTagSize, kAppletTag); + } + + const char kClassIDAttribute[] = "classid=\"java:"; + const char kCodeAttribute[] = "code=\""; + size_t kClassIDAttributeSize = sizeof(kClassIDAttribute) - 1; + string::size_type classID = element.find(kClassIDAttribute); + if (classID != string::npos) { + element.replace(classID, kClassIDAttributeSize, kCodeAttribute); + } + + mAppletHTML = ::strdup(element.c_str()); + } + break; case nsPluginTagType_Embed: { - nsIPluginTagInfo* tagInfo = NULL; - if (mPeer->QueryInterface(NS_GET_IID(nsIPluginTagInfo), (void **)&tagInfo) == NS_OK) { - // just synthesize an element out of whole cloth. - mAppletHTML = synthesizeAppletElement(tagInfo); - NS_RELEASE(tagInfo); - } - } - break; + nsIPluginTagInfo* tagInfo = NULL; + if (NS_SUCCEEDED(CallQueryInterface(mPeer, &tagInfo))) { + // just synthesize an element out of whole cloth. + mAppletHTML = synthesizeAppletElement(tagInfo); + NS_RELEASE(tagInfo); + } + } + break; } } const char* MRJContext::getAppletHTML() { - return mAppletHTML; + return mAppletHTML; } void MRJContext::setSecurityContext(MRJSecurityContext* context) @@ -1688,42 +1688,42 @@ MRJPage* MRJContext::findPage(const MRJPageAttributes& attributes) { - MRJPage* page = MRJPage::getFirstPage(); - while (page != NULL) { - if (attributes.documentID == page->getDocumentID() && - ::strcasecmp(attributes.codeBase, page->getCodeBase()) == 0 && - ::strcasecmp(attributes.archive, page->getArchive()) == 0 && - attributes.mayScript == page->getMayScript()) { - page->AddRef(); - return page; - } - page = page->getNextPage(); - } - - // create a unique page for this URL. - page = new MRJPage(mSession, attributes); - page->AddRef(); - return page; + MRJPage* page = MRJPage::getFirstPage(); + while (page != NULL) { + if (attributes.documentID == page->getDocumentID() && + ::strcasecmp(attributes.codeBase, page->getCodeBase()) == 0 && + ::strcasecmp(attributes.archive, page->getArchive()) == 0 && + attributes.mayScript == page->getMayScript()) { + page->AddRef(); + return page; + } + page = page->getNextPage(); + } + + // create a unique page for this URL. + page = new MRJPage(mSession, attributes); + page->AddRef(); + return page; } struct EmptyPort : public CGrafPort { - EmptyPort() { - GrafPtr oldPort; - ::GetPort(&oldPort); - ::OpenCPort(this); - ::PortSize(0, 0); - ::SetEmptyRgn(this->visRgn); - ::SetEmptyRgn(this->clipRgn); - ::SetPort(oldPort); - } - - ~EmptyPort() { - ::CloseCPort(this); - } + EmptyPort() { + GrafPtr oldPort; + ::GetPort(&oldPort); + ::OpenCPort(this); + ::PortSize(0, 0); + ::SetEmptyRgn(this->visRgn); + ::SetEmptyRgn(this->clipRgn); + ::SetPort(oldPort); + } + + ~EmptyPort() { + ::CloseCPort(this); + } }; CGrafPtr MRJContext::getEmptyPort() { - static EmptyPort emptyPort; - return &emptyPort; + static EmptyPort emptyPort; + return &emptyPort; } Index: mozilla/plugin/oji/MRJ/plugin/Source/MRJPlugin.cpp =================================================================== RCS file: /cvsroot/mozilla/plugin/oji/MRJ/plugin/Source/MRJPlugin.cpp,v retrieving revision 1.42 diff -u -r1.42 mozilla/plugin/oji/MRJ/plugin/Source/MRJPlugin.cpp --- mozilla/plugin/oji/MRJ/plugin/Source/MRJPlugin.cpp +++ mozilla/plugin/oji/MRJ/plugin/Source/MRJPlugin.cpp @@ -114,8 +114,8 @@ nsresult NSGetFactory(nsISupports* serviceManager, const nsCID &aClass, const char *aClassName, const char *aContractID, nsIFactory **aFactory) { if (theServiceManager == NULL && theServiceManagerObsolete == NULL) { - if (NS_FAILED(serviceManager->QueryInterface(NS_GET_IID(nsIServiceManager), (void**)&theServiceManager))) - if (NS_FAILED(serviceManager->QueryInterface(NS_GET_IID(nsIServiceManagerObsolete), (void**)&theServiceManagerObsolete))) + if (NS_FAILED(CallQueryInterface(serviceManager, &theServiceManager))) + if (NS_FAILED(CallQueryInterface(serviceManager, &theServiceManagerObsolete))) return NS_ERROR_FAILURE; // Our global operator new wants to use nsIMalloc to do all of its allocation. @@ -296,7 +296,7 @@ // see if the enhanced plugin manager exists. if (thePluginManager2 == NULL) { - if (thePluginManager->QueryInterface(NS_GET_IID(nsIPluginManager2), (void**)&thePluginManager2) != NS_OK) + if (NS_FAILED(CallQueryInterface(thePluginManager, &thePluginManager2))) thePluginManager2 = NULL; } @@ -306,7 +306,7 @@ // try to get a Thread manager. if (mManager != NULL) { - if (mManager->QueryInterface(NS_GET_IID(nsIThreadManager), (void**)&mThreadManager) != NS_OK) + if (NS_FAILED(CallQueryInterface(mManager, &mThreadManager))) mThreadManager = NULL; if (mThreadManager != NULL) @@ -646,7 +646,7 @@ static bool hasTagInfo(nsISupports* supports) { nsIJVMPluginTagInfo* tagInfo; - if (supports->QueryInterface(NS_GET_IID(nsIJVMPluginTagInfo), (void **)&tagInfo) == NS_OK) { + if (NS_SUCCEEDED(CallQueryInterface(supports, &tagInfo))) NS_RELEASE(tagInfo); return true; } Index: mozilla/plugin/oji/MRJCarbon/plugin/Source/EmbeddedFramePluginInstance.cpp =================================================================== RCS file: /cvsroot/mozilla/plugin/oji/MRJCarbon/plugin/Source/EmbeddedFramePluginInstance.cpp,v retrieving revision 1.7 diff -u -r1.7 mozilla/plugin/oji/MRJCarbon/plugin/Source/EmbeddedFramePluginInstance.cpp --- mozilla/plugin/oji/MRJCarbon/plugin/Source/EmbeddedFramePluginInstance.cpp +++ mozilla/plugin/oji/MRJCarbon/plugin/Source/EmbeddedFramePluginInstance.cpp @@ -65,7 +65,7 @@ NS_ADDREF(mPeer); nsIPluginTagInfo* tagInfo = NULL; - if (mPeer->QueryInterface(NS_GET_IID(nsIPluginTagInfo), (void**)&tagInfo) == NS_OK) { + if (NS_SUCCEEDED(CallQueryInterface(mPeer, &tagInfo))) { const char* frameValue = NULL; if (tagInfo->GetAttribute("JAVAFRAME", &frameValue) == NS_OK) { sscanf(frameValue, "%X", &mFrame); Index: mozilla/plugin/oji/MRJCarbon/plugin/Source/LiveConnectNativeMethods.cpp =================================================================== RCS file: /cvsroot/mozilla/plugin/oji/MRJCarbon/plugin/Source/LiveConnectNativeMethods.cpp,v retrieving revision 1.12 diff -u -r1.12 mozilla/plugin/oji/MRJCarbon/plugin/Source/LiveConnectNativeMethods.cpp --- mozilla/plugin/oji/MRJCarbon/plugin/Source/LiveConnectNativeMethods.cpp +++ mozilla/plugin/oji/MRJCarbon/plugin/Source/LiveConnectNativeMethods.cpp @@ -391,7 +391,7 @@ nsIPluginInstancePeer* peer; if (pluginInstance->GetPeer(&peer) == NS_OK) { nsIPluginInstancePeer2* peer2 = NULL; - if (peer->QueryInterface(NS_GET_IID(nsIPluginInstancePeer2), (void**)&peer2) == NS_OK) { + if (NS_SUCCEEDED(CallQueryInterface(peer, &peer2))) { if (peer2->GetJSThread(&threadID) != NS_OK) threadID = 0; NS_RELEASE(peer2); Index: mozilla/plugin/oji/MRJCarbon/plugin/Source/MRJContext.cp =================================================================== RCS file: /cvsroot/mozilla/plugin/oji/MRJCarbon/plugin/Source/MRJContext.cp,v retrieving revision 1.22 diff -u -r1.22 mozilla/plugin/oji/MRJCarbon/plugin/Source/MRJContext.cp --- mozilla/plugin/oji/MRJCarbon/plugin/Source/MRJContext.cp +++ mozilla/plugin/oji/MRJCarbon/plugin/Source/MRJContext.cp @@ -393,7 +393,7 @@ string parameters(""); nsIPluginTagInfo2* tagInfo2 = NULL; - if (tagInfo->QueryInterface(NS_GET_IID(nsIPluginTagInfo2), (void**)&tagInfo2) == NS_OK) { + if (NS_SUCCEEDED(CallQueryInterface(tagInfo, &tagInfo2))) { nsPluginTagType tagType = nsPluginTagType_Unknown; if (tagInfo2->GetTagType(&tagType) == NS_OK) { switch (tagType) { @@ -494,9 +494,9 @@ // in general, to specify a separate CODEBASE. nsIPluginTagInfo* tagInfo = NULL; - if (mPeer->QueryInterface(NS_GET_IID(nsIPluginTagInfo), (void**)&tagInfo) == NS_OK) { + if (NS_SUCCEEDED(CallQueryInterface(mPeer, &tagInfo))) { nsIPluginTagInfo2* tagInfo2 = NULL; - if (tagInfo->QueryInterface(NS_GET_IID(nsIPluginTagInfo2), (void**)&tagInfo2) == NS_OK) { + if (NS_SUCCEEDED(CallQueryInterface(tagInfo, &tagInfo2))) { nsPluginTagType tagType = nsPluginTagType_Unknown; if (tagInfo2->GetTagType(&tagType) == NS_OK) { // get the URL of the HTML document containing the applet, and the @@ -516,7 +516,7 @@ // establish a page context for this applet to run in. nsIJVMPluginTagInfo* jvmTagInfo = NULL; - if (mPeer->QueryInterface(NS_GET_IID(nsIJVMPluginTagInfo), (void**)&jvmTagInfo) == NS_OK) { + if (NS_SUCCEEDED(CallQueryInterface(mPeer, &jvmTagInfo))) { PRUint32 documentID; const char* codeBase; const char* archive; @@ -1063,7 +1063,7 @@ // gather all attributes and parameters. cfref attributes, parameters; nsIPluginTagInfo2* tagInfo2 = NULL; - if (mPeer->QueryInterface(NS_GET_IID(nsIPluginTagInfo2), (void**)&tagInfo2) == NS_OK) { + if (NS_SUCCEEDED(CallQueryInterface(mPeer, &tagInfo2))) { attributes = getAttributes(tagInfo2); fixAttributes(attributes, tagInfo2, mPluginWindow); parameters = getParameters(tagInfo2); @@ -1186,7 +1186,7 @@ { const char* value = NULL; nsIPluginTagInfo* tagInfo = NULL; - if (NS_SUCCEEDED(peer->QueryInterface(NS_GET_IID(nsIPluginTagInfo), (void**)&tagInfo))) { + if (NS_SUCCEEDED(CallQueryInterface(peer, &tagInfo))) { tagInfo->GetAttribute(name, &value); NS_RELEASE(tagInfo); } @@ -1905,7 +1905,7 @@ case nsPluginTagType_Embed: { nsIPluginTagInfo* tagInfo = NULL; - if (mPeer->QueryInterface(NS_GET_IID(nsIPluginTagInfo), (void**)&tagInfo) == NS_OK) { + if (NS_SUCCEEDED(CallQueryInterface(mPeer, &tagInfo))) { // just synthesize an element out of whole cloth. mAppletHTML = synthesizeAppletElement(tagInfo); NS_RELEASE(tagInfo); Index: mozilla/plugin/oji/MRJCarbon/plugin/Source/MRJPlugin.cpp =================================================================== RCS file: /cvsroot/mozilla/plugin/oji/MRJCarbon/plugin/Source/MRJPlugin.cpp,v retrieving revision 1.17 diff -u -r1.17 mozilla/plugin/oji/MRJCarbon/plugin/Source/MRJPlugin.cpp --- mozilla/plugin/oji/MRJCarbon/plugin/Source/MRJPlugin.cpp +++ mozilla/plugin/oji/MRJCarbon/plugin/Source/MRJPlugin.cpp @@ -130,8 +130,8 @@ return NS_ERROR_FAILURE; if (theServiceManager == NULL && theServiceManagerObsolete == NULL) { - if (NS_FAILED(serviceManager->QueryInterface(NS_GET_IID(nsIServiceManager), (void**)&theServiceManager))) - if (NS_FAILED(serviceManager->QueryInterface(NS_GET_IID(nsIServiceManagerObsolete), (void**)&theServiceManagerObsolete))) + if (NS_FAILED(CallQueryInterface(serviceManager, &theServiceManager))) + if (NS_FAILED(CallQueryInterface(serviceManager, &theServiceManagerObsolete))) return NS_ERROR_FAILURE; // Our global operator new wants to use nsIMalloc to do all of its allocation. @@ -350,7 +350,7 @@ // see if the enhanced plugin manager exists. if (thePluginManager2 == NULL) { - if (thePluginManager->QueryInterface(NS_GET_IID(nsIPluginManager2), (void**)&thePluginManager2) != NS_OK) + if (NS_FAILED(CallQueryInterface(thePluginManager, &thePluginManager2))) thePluginManager2 = NULL; } @@ -360,7 +360,7 @@ // try to get a Thread manager. if (mManager != NULL) { - if (mManager->QueryInterface(NS_GET_IID(nsIThreadManager), (void**)&mThreadManager) != NS_OK) + if (NS_FAILED(CallQueryInterface(mManager, &mThreadManager))) mThreadManager = NULL; if (mThreadManager != NULL) @@ -701,7 +701,7 @@ static bool hasTagInfo(nsISupports* supports) { nsIJVMPluginTagInfo* tagInfo; - if (supports->QueryInterface(NS_GET_IID(nsIJVMPluginTagInfo), (void**)&tagInfo) == NS_OK) { + if (NS_SUCCEEDED(CallQueryInterface(supports, &tagInfo))) { NS_RELEASE(tagInfo); return true; } Index: mozilla/rdf/base/src/nsCompositeDataSource.cpp =================================================================== RCS file: /cvsroot/mozilla/rdf/base/src/nsCompositeDataSource.cpp,v retrieving revision 1.71 diff -u -r1.71 mozilla/rdf/base/src/nsCompositeDataSource.cpp --- mozilla/rdf/base/src/nsCompositeDataSource.cpp +++ mozilla/rdf/base/src/nsCompositeDataSource.cpp @@ -269,7 +269,7 @@ rv = mCurrent->GetNext(getter_AddRefs(result)); if (NS_FAILED(rv)) return rv; - rv = result->QueryInterface(NS_GET_IID(nsIRDFNode), (void**) &mResult); + rv = CallQueryInterface(result, &mResult); if (NS_FAILED(rv)) return rv; if (mAllowNegativeAssertions == PR_TRUE) @@ -693,30 +693,11 @@ } } -NS_IMETHODIMP -CompositeDataSourceImpl::QueryInterface(REFNSIID iid, void** result) -{ - if (! result) - return NS_ERROR_NULL_POINTER; - - if (iid.Equals(NS_GET_IID(nsIRDFCompositeDataSource)) || - iid.Equals(NS_GET_IID(nsIRDFDataSource)) || - iid.Equals(kISupportsIID)) { - *result = NS_STATIC_CAST(nsIRDFCompositeDataSource*, this); - NS_ADDREF(this); - return NS_OK; - } - else if (iid.Equals(NS_GET_IID(nsIRDFObserver))) { - *result = NS_STATIC_CAST(nsIRDFObserver*, this); - NS_ADDREF(this); - return NS_OK; - } - else { - *result = nsnull; - return NS_NOINTERFACE; - } -} - +NS_INTERFACE_MAP_BEGIN(CompositeDataSourceImpl + NS_INTERFACE_MAP_ENTRY_AMBIGUOUS(nsISupports, nsIRDFCompositeDataSource) + NS_INTERFACE_MAP_ENTRY(nsIRDFDataSource) + NS_INTERFACE_MAP_ENTRY(nsIRDFObserver) +NS_INTERFACE_MAP_END //---------------------------------------------------------------------- Index: mozilla/rdf/base/src/nsRDFContainer.cpp =================================================================== RCS file: /cvsroot/mozilla/rdf/base/src/nsRDFContainer.cpp,v retrieving revision 1.41 diff -u -r1.41 mozilla/rdf/base/src/nsRDFContainer.cpp --- mozilla/rdf/base/src/nsRDFContainer.cpp +++ mozilla/rdf/base/src/nsRDFContainer.cpp @@ -206,8 +206,7 @@ if (rv == NS_RDF_NO_VALUE) return NS_ERROR_UNEXPECTED; - nsCOMPtr nextValLiteral; - rv = nextValNode->QueryInterface(NS_GET_IID(nsIRDFLiteral), getter_AddRefs(nextValLiteral)); + nsCOMPtr nextValLiteral(do_QueryInterface(nextValNode, &rv)); if (NS_FAILED(rv)) return rv; const PRUnichar *s; @@ -701,8 +700,7 @@ if (rv == NS_RDF_NO_VALUE) return NS_ERROR_UNEXPECTED; - nsCOMPtr nextValLiteral; - rv = nextValNode->QueryInterface(NS_GET_IID(nsIRDFLiteral), getter_AddRefs(nextValLiteral)); + nsCOMPtr nextValLiteral(do_QueryInterface(nextValNode, &rv)); if (NS_FAILED(rv)) return rv; const PRUnichar* s; Index: mozilla/rdf/base/src/nsRDFContainerUtils.cpp =================================================================== RCS file: /cvsroot/mozilla/rdf/base/src/nsRDFContainerUtils.cpp,v retrieving revision 1.33 diff -u -r1.33 mozilla/rdf/base/src/nsRDFContainerUtils.cpp --- mozilla/rdf/base/src/nsRDFContainerUtils.cpp +++ mozilla/rdf/base/src/nsRDFContainerUtils.cpp @@ -257,8 +257,7 @@ if (rv == NS_RDF_NO_VALUE) return NS_OK; - nsCOMPtr nextValLiteral; - rv = nextValNode->QueryInterface(NS_GET_IID(nsIRDFLiteral), getter_AddRefs(nextValLiteral)); + nsCOMPtr nextValLiteral(do_QueryInterface(nextValNode, &rv)); if (NS_FAILED(rv)) return rv; if (nextValLiteral.get() != kOne) Index: mozilla/rdf/datasource/src/nsFileSystemDataSource.cpp =================================================================== RCS file: /cvsroot/mozilla/rdf/datasource/src/nsFileSystemDataSource.cpp,v retrieving revision 1.146 diff -u -r1.146 mozilla/rdf/datasource/src/nsFileSystemDataSource.cpp --- mozilla/rdf/datasource/src/nsFileSystemDataSource.cpp +++ mozilla/rdf/datasource/src/nsFileSystemDataSource.cpp @@ -349,7 +349,7 @@ if (NS_FAILED(rv)) return(rv); if (!name) rv = NS_RDF_NO_VALUE; if (rv == NS_RDF_NO_VALUE) return(rv); - return name->QueryInterface(NS_GET_IID(nsIRDFNode), (void**) target); + return CallQueryInterface(name, target); } else if (property == mNC_URL) { @@ -359,7 +359,7 @@ if (!url) rv = NS_RDF_NO_VALUE; if (rv == NS_RDF_NO_VALUE) return(rv); - return url->QueryInterface(NS_GET_IID(nsIRDFNode), (void**) target); + return CallQueryInterface(url, target); } else if (property == mNC_Icon) { @@ -379,7 +379,7 @@ rv = mRDFService->GetLiteral(urlStr.get(), getter_AddRefs(url)); if (NS_FAILED(rv) || !url) return(NS_RDF_NO_VALUE); - return url->QueryInterface(NS_GET_IID(nsIRDFNode), (void**) target); + return CallQueryInterface(url, target); } else if (property == mNC_Length) { @@ -389,7 +389,7 @@ if (!fileSize) rv = NS_RDF_NO_VALUE; if (rv == NS_RDF_NO_VALUE) return(rv); - return fileSize->QueryInterface(NS_GET_IID(nsIRDFNode), (void**) target); + return CallQueryInterface(fileSize, target); } else if (property == mNC_IsDirectory) { @@ -405,7 +405,7 @@ if (!lastMod) rv = NS_RDF_NO_VALUE; if (rv == NS_RDF_NO_VALUE) return(rv); - return lastMod->QueryInterface(NS_GET_IID(nsIRDFNode), (void**) target); + return CallQueryInterface(lastMod, target); } else if (property == mRDF_type) { @@ -441,14 +441,14 @@ NS_ConvertUTF8toUTF16 url(type); nsCOMPtr literal; mRDFService->GetLiteral(url.get(), getter_AddRefs(literal)); - rv = literal->QueryInterface(NS_GET_IID(nsIRDFNode), (void**) target); + rv = CallQueryInterface(literal, target); return(rv); } else if (property == mNC_pulse) { nsCOMPtr pulseLiteral; mRDFService->GetLiteral(NS_LITERAL_STRING("12").get(), getter_AddRefs(pulseLiteral)); - rv = pulseLiteral->QueryInterface(NS_GET_IID(nsIRDFNode), (void**) target); + rv = CallQueryInterface(pulseLiteral, target); return(rv); } else if (property == mNC_Child) @@ -468,7 +468,7 @@ rv = children->GetNext(getter_AddRefs(isupports)); if (NS_FAILED(rv)) return(rv); - return isupports->QueryInterface(NS_GET_IID(nsIRDFNode), (void**) target); + return CallQueryInterface(isupports, target); } } #ifdef USE_NC_EXTENSION @@ -478,7 +478,7 @@ rv = GetExtension(source, getter_AddRefs(extension)); if (!extension) rv = NS_RDF_NO_VALUE; if (rv == NS_RDF_NO_VALUE) return(rv); - return extension->QueryInterface(NS_GET_IID(nsIRDFNode), (void**) target); + return CallQueryInterface(extension, target); } #endif } Index: mozilla/rdf/util/src/nsRDFResource.cpp =================================================================== RCS file: /cvsroot/mozilla/rdf/util/src/nsRDFResource.cpp,v retrieving revision 1.44 diff -u -r1.44 mozilla/rdf/util/src/nsRDFResource.cpp --- mozilla/rdf/util/src/nsRDFResource.cpp +++ mozilla/rdf/util/src/nsRDFResource.cpp @@ -88,20 +88,17 @@ return NS_ERROR_NULL_POINTER; nsresult rv; - nsIRDFResource* resource; - rv = aNode->QueryInterface(NS_GET_IID(nsIRDFResource), (void**)&resource); - if (NS_SUCCEEDED(rv)) { - *aResult = (NS_STATIC_CAST(nsIRDFResource*, this) == resource); - NS_RELEASE(resource); - return NS_OK; - } - else if (rv == NS_NOINTERFACE) { - *aResult = PR_FALSE; - return NS_OK; - } - else { + nsCOMPtr resource(do_QueryInterface(aNode, &rv)); + if (NS_FAILED(rv)) { + if (rv == NS_NOINTERFACE) { + *aResult = PR_FALSE; + return NS_OK; + } return rv; } + + *aResult = SameCOMIdentity(this, resource); + return NS_OK; } //////////////////////////////////////////////////////////////////////////////// Index: mozilla/security/manager/pki/src/nsNSSDialogHelper.cpp =================================================================== RCS file: /cvsroot/mozilla/security/manager/pki/src/nsNSSDialogHelper.cpp,v retrieving revision 1.2 diff -u -r1.2 mozilla/security/manager/pki/src/nsNSSDialogHelper.cpp --- mozilla/security/manager/pki/src/nsNSSDialogHelper.cpp +++ mozilla/security/manager/pki/src/nsNSSDialogHelper.cpp @@ -66,7 +66,7 @@ nsCOMPtr active; windowWatcher->GetActiveWindow(getter_AddRefs(active)); if (active) { - active->QueryInterface(NS_GET_IID(nsIDOMWindowInternal), getter_AddRefs(activeParent)); + activeParent = do_QueryInterface(active); parent = activeParent; } } Index: mozilla/security/manager/ssl/src/nsCertPicker.cpp =================================================================== RCS file: /cvsroot/mozilla/security/manager/ssl/src/nsCertPicker.cpp,v retrieving revision 1.11 diff -u -r1.11 mozilla/security/manager/ssl/src/nsCertPicker.cpp --- mozilla/security/manager/ssl/src/nsCertPicker.cpp +++ mozilla/security/manager/ssl/src/nsCertPicker.cpp @@ -208,7 +208,7 @@ } nsIX509Cert *x509 = 0; - nsresult rv = cert->QueryInterface(NS_GET_IID(nsIX509Cert), (void**)&x509); + nsresult rv = CallQueryInterface(cert, &x509); if (NS_FAILED(rv)) { break; } Index: mozilla/security/manager/ssl/src/nsNSSCertificateDB.cpp =================================================================== RCS file: /cvsroot/mozilla/security/manager/ssl/src/nsNSSCertificateDB.cpp,v retrieving revision 1.24 diff -u -r1.24 mozilla/security/manager/ssl/src/nsNSSCertificateDB.cpp --- mozilla/security/manager/ssl/src/nsNSSCertificateDB.cpp +++ mozilla/security/manager/ssl/src/nsNSSCertificateDB.cpp @@ -1504,7 +1504,7 @@ rv = NS_ERROR_OUT_OF_MEMORY; } else { - nsresult rv = nsNSS->QueryInterface(NS_GET_IID(nsIX509Cert), (void**)_retval); + nsresult rv = CallQueryInterface(nsNSS, _retval); if (NS_SUCCEEDED(rv) && *_retval) { NS_ADDREF(*_retval); Index: mozilla/security/manager/ssl/src/nsNSSComponent.cpp =================================================================== RCS file: /cvsroot/mozilla/security/manager/ssl/src/nsNSSComponent.cpp,v retrieving revision 1.140 diff -u -r1.140 mozilla/security/manager/ssl/src/nsNSSComponent.cpp --- mozilla/security/manager/ssl/src/nsNSSComponent.cpp +++ mozilla/security/manager/ssl/src/nsNSSComponent.cpp @@ -2653,8 +2653,7 @@ if (type != PSMContentDownloader::UNKNOWN_TYPE) { downLoader = new PSMContentDownloader(type); if (downLoader) { - downLoader->QueryInterface(NS_GET_IID(nsIStreamListener), - (void **)aContentHandler); + CallQueryInterface(downLoader, aContentHandler); return NS_OK; } } Index: mozilla/security/manager/ssl/src/nsNSSIOLayer.cpp =================================================================== RCS file: /cvsroot/mozilla/security/manager/ssl/src/nsNSSIOLayer.cpp,v retrieving revision 1.121 diff -u -r1.121 mozilla/security/manager/ssl/src/nsNSSIOLayer.cpp --- mozilla/security/manager/ssl/src/nsNSSIOLayer.cpp +++ mozilla/security/manager/ssl/src/nsNSSIOLayer.cpp @@ -2655,7 +2655,7 @@ nsNSSShutDownList::trackSSLSocketCreate(); PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("[%p] Socket set up\n", (void*)sslSock)); - infoObject->QueryInterface(NS_GET_IID(nsISupports), (void**) (info)); + CallQueryInterface(infoObject, info); // We are going use a clear connection first // if (forSTARTTLS || proxyHost) { Index: mozilla/toolkit/components/downloads/src/nsDownloadManager.cpp =================================================================== RCS file: /cvsroot/mozilla/toolkit/components/downloads/src/nsDownloadManager.cpp,v retrieving revision 1.69 diff -u -r1.69 mozilla/toolkit/components/downloads/src/nsDownloadManager.cpp --- mozilla/toolkit/components/downloads/src/nsDownloadManager.cpp +++ mozilla/toolkit/components/downloads/src/nsDownloadManager.cpp @@ -550,7 +550,7 @@ if (!internalDownload) return NS_ERROR_OUT_OF_MEMORY; - internalDownload->QueryInterface(NS_GET_IID(nsIDownload), (void**) aDownload); + CallQueryInterface(internalDownload, aDownload); if (!aDownload) return NS_ERROR_FAILURE; Index: mozilla/toolkit/components/downloads/src/old.cpp =================================================================== RCS file: /cvsroot/mozilla/toolkit/components/downloads/src/old.cpp,v retrieving revision 1.2 diff -u -r1.2 mozilla/toolkit/components/downloads/src/old.cpp --- mozilla/toolkit/components/downloads/src/old.cpp +++ mozilla/toolkit/components/downloads/src/old.cpp @@ -19,7 +19,7 @@ nsCOMPtr download; nsDownload* internalDownload = NS_STATIC_CAST(nsDownload*, mCurrDownloads.Get(&key)); - internalDownload->QueryInterface(NS_GET_IID(nsIDownload), (void**) getter_AddRefs(download)); + nsCOMPtr download(do_QueryInterface(internalDownload)); if (!download) return NS_ERROR_FAILURE; Index: mozilla/toolkit/components/places/src/nsNavHistoryResult.cpp =================================================================== RCS file: /cvsroot/mozilla/toolkit/components/places/src/nsNavHistoryResult.cpp,v retrieving revision 1.78 diff -u -r1.78 mozilla/toolkit/components/places/src/nsNavHistoryResult.cpp --- mozilla/toolkit/components/places/src/nsNavHistoryResult.cpp +++ mozilla/toolkit/components/places/src/nsNavHistoryResult.cpp @@ -3513,8 +3513,7 @@ *aRoot = nsnull; return NS_ERROR_FAILURE; } - return mRootNode->QueryInterface(NS_GET_IID(nsINavHistoryQueryResultNode), - NS_REINTERPRET_CAST(void**, aRoot)); + return CallQueryInterface(mRootNode, aRoot); } @@ -4220,7 +4219,7 @@ return NS_ERROR_UNEXPECTED; } - nsRefPtr parent; + nsRefPtr parent; //XXX EVIL aParent->QueryInterface(NS_GET_IID(nsNavHistoryContainerResultNode), getter_AddRefs(parent)); if (! parent) { Index: mozilla/widget/src/os2/nsWindow.cpp =================================================================== RCS file: /cvsroot/mozilla/widget/src/os2/nsWindow.cpp,v retrieving revision 1.206 diff -u -r1.206 mozilla/widget/src/os2/nsWindow.cpp --- mozilla/widget/src/os2/nsWindow.cpp +++ mozilla/widget/src/os2/nsWindow.cpp @@ -3231,7 +3231,7 @@ { nsIRenderingContextOS2 *winrc; - if (NS_OK == event.renderingContext->QueryInterface(NS_GET_IID(nsIRenderingContextOS2), (void **)&winrc)) + if (NS_SUCCEEDED(CallQueryInterface(event.renderingContext, &winrc))) { nsIDrawingSurface* surf; Index: mozilla/widget/src/windows/nsImageClipboard.cpp =================================================================== RCS file: /cvsroot/mozilla/widget/src/windows/nsImageClipboard.cpp,v retrieving revision 1.9 diff -u -r1.9 mozilla/widget/src/windows/nsImageClipboard.cpp --- mozilla/widget/src/windows/nsImageClipboard.cpp +++ mozilla/widget/src/windows/nsImageClipboard.cpp @@ -351,7 +351,7 @@ rv = encoder->InitFromData(rgbData, 0, width, height, 3 * width /* RGB * # pixels in a row */, imgIEncoder::INPUT_FORMAT_RGB, NS_LITERAL_STRING("transparency=none")); if (NS_SUCCEEDED(rv)) - encoder->QueryInterface(NS_GET_IID(nsIInputStream), (void **) aInputStream); + CallQueryInterface(encoder, aInputStream); } } delete [] rgbData; Index: mozilla/widget/src/windows/nsPrintSettingsWin.cpp =================================================================== RCS file: /cvsroot/mozilla/widget/src/windows/nsPrintSettingsWin.cpp,v retrieving revision 1.8 diff -u -r1.8 mozilla/widget/src/windows/nsPrintSettingsWin.cpp --- mozilla/widget/src/windows/nsPrintSettingsWin.cpp +++ mozilla/widget/src/windows/nsPrintSettingsWin.cpp @@ -151,7 +151,9 @@ nsPrintSettingsWin::_Clone(nsIPrintSettings **_retval) { nsPrintSettingsWin* printSettings = new nsPrintSettingsWin(*this); - return printSettings->QueryInterface(NS_GET_IID(nsIPrintSettings), (void**)_retval); // ref counts + if (!printSettings) + return NS_ERROR_OUT_OF_MEMORY; + return CallQueryInterface(printSettings, _retval); } //------------------------------------------- Index: mozilla/widget/src/xpwidgets/nsPrintSettingsImpl.cpp =================================================================== RCS file: /cvsroot/mozilla/widget/src/xpwidgets/nsPrintSettingsImpl.cpp,v retrieving revision 1.25 diff -u -r1.25 mozilla/widget/src/xpwidgets/nsPrintSettingsImpl.cpp --- mozilla/widget/src/xpwidgets/nsPrintSettingsImpl.cpp +++ mozilla/widget/src/xpwidgets/nsPrintSettingsImpl.cpp @@ -925,7 +925,9 @@ nsPrintSettings::_Clone(nsIPrintSettings **_retval) { nsPrintSettings* printSettings = new nsPrintSettings(*this); - return printSettings->QueryInterface(NS_GET_IID(nsIPrintSettings), (void**)_retval); // ref counts + if (!printSettings) + return NS_ERROR_OUT_OF_MEMORY; + return CallQueryInterface(printSettings, _retval); } /* nsIPrintSettings clone (); */ Index: mozilla/xpcom/components/nsComponentManager.cpp =================================================================== RCS file: /cvsroot/mozilla/xpcom/components/nsComponentManager.cpp,v retrieving revision 1.281 diff -u -r1.281 mozilla/xpcom/components/nsComponentManager.cpp --- mozilla/xpcom/components/nsComponentManager.cpp +++ mozilla/xpcom/components/nsComponentManager.cpp @@ -2395,7 +2395,7 @@ if (!file) return NS_ERROR_FAILURE; rv = file->InitWithNativePath(Substring(aLocation, 4)); - file->QueryInterface(NS_GET_IID(nsILocalFile), (void**)aSpec); + CallQueryInterface(file, aSpec); return rv; } Index: mozilla/xpcom/io/nsDirectoryService.cpp =================================================================== RCS file: /cvsroot/mozilla/xpcom/io/nsDirectoryService.cpp,v retrieving revision 1.92 diff -u -r1.92 mozilla/xpcom/io/nsDirectoryService.cpp --- mozilla/xpcom/io/nsDirectoryService.cpp +++ mozilla/xpcom/io/nsDirectoryService.cpp @@ -1186,7 +1186,7 @@ NS_RELEASE(inAtom); if (localFile && NS_SUCCEEDED(rv)) - return localFile->QueryInterface(NS_GET_IID(nsIFile), (void**)_retval); + return CallQueryInterface(localFile, _retval); #ifdef DEBUG_dougt printf("Failed to find directory for key: %s\n", prop); #endif Index: mozilla/xpcom/obsolete/nsFileSpecImpl.cpp =================================================================== RCS file: /cvsroot/mozilla/xpcom/obsolete/nsFileSpecImpl.cpp,v retrieving revision 1.7 diff -u -r1.7 mozilla/xpcom/obsolete/nsFileSpecImpl.cpp --- mozilla/xpcom/obsolete/nsFileSpecImpl.cpp +++ mozilla/xpcom/obsolete/nsFileSpecImpl.cpp @@ -92,7 +92,7 @@ nsFileSpecImpl* it = new nsFileSpecImpl(inSpec); if (!it) return NS_ERROR_OUT_OF_MEMORY; - return it->QueryInterface(NS_GET_IID(nsIFileSpec), (void **) result); + return CallQueryInterface(it, result); } // nsFileSpecImpl::MakeInterface #define FILESPEC(ifilespec) ((nsFileSpecImpl*)ifilespec)->mFileSpec Index: mozilla/xpcom/obsolete/nsIFileStream.cpp =================================================================== RCS file: /cvsroot/mozilla/xpcom/obsolete/nsIFileStream.cpp,v retrieving revision 1.6 diff -u -r1.6 mozilla/xpcom/obsolete/nsIFileStream.cpp --- mozilla/xpcom/obsolete/nsIFileStream.cpp +++ mozilla/xpcom/obsolete/nsIFileStream.cpp @@ -628,7 +628,7 @@ *aResult = nsnull; if (NS_SUCCEEDED(rv)) { - if (NS_SUCCEEDED(supports->QueryInterface(NS_GET_IID(nsIInputStream), (void**)&inStr))) { + if (NS_SUCCEEDED(CallQueryInterface(supports, &inStr))) { *aResult = inStr; } NS_RELEASE(supports); @@ -661,7 +661,7 @@ *aResult = nsnull; if (NS_SUCCEEDED(rv)) { - if (NS_SUCCEEDED(supports->QueryInterface(NS_GET_IID(nsIOutputStream), (void**)&outStr))) { + if (NS_SUCCEEDED(CallQueryInterface(supports, &outStr))) { *aResult = outStr; } NS_RELEASE(supports); @@ -680,7 +680,7 @@ *aResult = nsnull; if (NS_SUCCEEDED(rv)) { - if (NS_SUCCEEDED(supports->QueryInterface(NS_GET_IID(nsIOutputStream), (void**)&outStr))) { + if (NS_SUCCEEDED(CallQueryInterface(supports, &outStr))) { *aResult = outStr; } } Index: mozilla/xpcom/obsolete/component/nsFileSpecImpl.cpp =================================================================== RCS file: /cvsroot/mozilla/xpcom/obsolete/component/nsFileSpecImpl.cpp,v retrieving revision 1.2 diff -u -r1.2 mozilla/xpcom/obsolete/component/nsFileSpecImpl.cpp --- mozilla/xpcom/obsolete/component/nsFileSpecImpl.cpp +++ mozilla/xpcom/obsolete/component/nsFileSpecImpl.cpp @@ -91,7 +91,7 @@ nsFileSpecImpl* it = new nsFileSpecImpl(inSpec); if (!it) return NS_ERROR_OUT_OF_MEMORY; - return it->QueryInterface(NS_GET_IID(nsIFileSpec), (void **) result); + return CallQueryInterface(it, result); } // nsFileSpecImpl::MakeInterface #define FILESPEC(ifilespec) ((nsFileSpecImpl*)ifilespec)->mFileSpec Index: mozilla/xpcom/tools/registry/regxpcom.cpp =================================================================== RCS file: /cvsroot/mozilla/xpcom/tools/registry/regxpcom.cpp,v retrieving revision 1.34 diff -u -r1.34 mozilla/xpcom/tools/registry/regxpcom.cpp --- mozilla/xpcom/tools/registry/regxpcom.cpp +++ mozilla/xpcom/tools/registry/regxpcom.cpp @@ -103,7 +103,7 @@ rv = NS_NewNativeLocalFile(nsEmbedCString(fileLocation), PR_TRUE, getter_AddRefs(localFile)); if (NS_FAILED(rv)) return rv; - return localFile->QueryInterface(NS_GET_IID(nsIFile), (void**)_retval); + return CallQueryInterface(localFile, _retval); } int startup_xpcom() Index: mozilla/xpfe/appshell/src/nsWindowMediator.cpp =================================================================== RCS file: /cvsroot/mozilla/xpfe/appshell/src/nsWindowMediator.cpp,v retrieving revision 1.67 diff -u -r1.67 mozilla/xpfe/appshell/src/nsWindowMediator.cpp --- mozilla/xpfe/appshell/src/nsWindowMediator.cpp +++ mozilla/xpfe/appshell/src/nsWindowMediator.cpp @@ -238,10 +238,10 @@ nsAutoLock lock(mListLock); nsAppShellWindowEnumerator *enumerator = new nsASDOMWindowEarlyToLateEnumerator(inType, *this); - if (enumerator) - return enumerator->QueryInterface(NS_GET_IID(nsISimpleEnumerator) , (void**)outEnumerator); + if (!enumerator) + return NS_ERROR_OUT_OF_MEMORY; - return NS_ERROR_OUT_OF_MEMORY; + return CallQueryInterface(enumerator, outEnumerator); } @@ -254,10 +254,10 @@ nsAutoLock lock(mListLock); nsAppShellWindowEnumerator *enumerator = new nsASXULWindowEarlyToLateEnumerator(inType, *this); - if (enumerator) - return enumerator->QueryInterface( NS_GET_IID(nsISimpleEnumerator) , (void**)outEnumerator); + if (!enumerator) + return NS_ERROR_OUT_OF_MEMORY; - return NS_ERROR_OUT_OF_MEMORY; + return CallQueryInterface(enumerator, outEnumerator); } @@ -276,10 +276,11 @@ enumerator = new nsASDOMWindowFrontToBackEnumerator(aWindowType, *this); else enumerator = new nsASDOMWindowBackToFrontEnumerator(aWindowType, *this); - if (enumerator) - return enumerator->QueryInterface(NS_GET_IID(nsISimpleEnumerator), (void**) _retval); - return NS_ERROR_OUT_OF_MEMORY; + if (!enumerator) + return NS_ERROR_OUT_OF_MEMORY; + + return CallQueryInterface(enumerator, _retval); } @@ -298,10 +299,11 @@ enumerator = new nsASXULWindowFrontToBackEnumerator(aWindowType, *this); else enumerator = new nsASXULWindowBackToFrontEnumerator(aWindowType, *this); - if (enumerator) - return enumerator->QueryInterface(NS_GET_IID(nsISimpleEnumerator), (void**) _retval); - return NS_ERROR_OUT_OF_MEMORY; + if (!enumerator) + return NS_ERROR_OUT_OF_MEMORY; + + return CallQueryInterface(enumerator, _retval); } Index: mozilla/xpfe/components/bookmarks/src/nsBookmarksService.cpp =================================================================== RCS file: /cvsroot/mozilla/xpfe/components/bookmarks/src/nsBookmarksService.cpp,v retrieving revision 1.345 diff -u -r1.345 mozilla/xpfe/components/bookmarks/src/nsBookmarksService.cpp --- mozilla/xpfe/components/bookmarks/src/nsBookmarksService.cpp +++ mozilla/xpfe/components/bookmarks/src/nsBookmarksService.cpp @@ -1298,7 +1298,7 @@ nsCOMPtr result; rv = gRDF->GetUnicodeResource(url, getter_AddRefs(result)); if (NS_FAILED(rv)) return rv; - return result->QueryInterface(NS_GET_IID(nsIRDFNode), (void**) aResult); + return CallQueryInterface(result, aResult); } nsresult @@ -1334,7 +1334,7 @@ nsCOMPtr result; rv = gRDF->GetLiteral(aValue.get(), getter_AddRefs(result)); if (NS_FAILED(rv)) return rv; - return result->QueryInterface(NS_GET_IID(nsIRDFNode), (void**) aResult); + return CallQueryInterface(result, aResult); } nsresult @@ -1363,7 +1363,7 @@ NS_ERROR("unable to get date literal for time"); return rv; } - return result->QueryInterface(NS_GET_IID(nsIRDFNode), (void**) aResult); + return CallQueryInterface(result, aResult); } nsresult @@ -5790,7 +5790,7 @@ aResult.Truncate(); rv = NS_OK; } - else if (NS_SUCCEEDED(rv = aNode->QueryInterface(NS_GET_IID(nsIRDFResource), (void**) &resource))) + else if (NS_SUCCEEDED(rv = CallQueryInterface(aNode, &resource)) { const char *p = nsnull; if (NS_SUCCEEDED(rv = resource->GetValueConst( &p )) && (p)) @@ -5799,7 +5799,7 @@ } NS_RELEASE(resource); } - else if (NS_SUCCEEDED(rv = aNode->QueryInterface(NS_GET_IID(nsIRDFDate), (void**) &dateLiteral))) + else if (NS_SUCCEEDED(rv = CallQueryInterface(aNode, &dateLiteral)) { PRInt64 theDate, million; if (NS_SUCCEEDED(rv = dateLiteral->GetValue( &theDate ))) @@ -5813,7 +5813,7 @@ } NS_RELEASE(dateLiteral); } - else if (NS_SUCCEEDED(rv = aNode->QueryInterface(NS_GET_IID(nsIRDFInt), (void**) &intLiteral))) + else if (NS_SUCCEEDED(rv = CallQueryInterface(aNode, &intLiteral))) { PRInt32 theInt; aResult.Truncate(); @@ -5823,7 +5823,7 @@ } NS_RELEASE(intLiteral); } - else if (NS_SUCCEEDED(rv = aNode->QueryInterface(NS_GET_IID(nsIRDFLiteral), (void**) &literal))) + else if (NS_SUCCEEDED(rv = CallQueryInterface(aNode, &literal))) { const PRUnichar *p = nsnull; if (NS_SUCCEEDED(rv = literal->GetValueConst( &p )) && (p)) Index: mozilla/xpfe/components/winhooks/nsWindowsHooks.cpp =================================================================== RCS file: /cvsroot/mozilla/xpfe/components/winhooks/nsWindowsHooks.cpp,v retrieving revision 1.66 diff -u -r1.66 mozilla/xpfe/components/winhooks/nsWindowsHooks.cpp --- mozilla/xpfe/components/winhooks/nsWindowsHooks.cpp +++ mozilla/xpfe/components/winhooks/nsWindowsHooks.cpp @@ -238,7 +238,7 @@ if ( NS_SUCCEEDED( rv ) ) { // QI to proper interface. - rv = prefs->QueryInterface( NS_GET_IID( nsIWindowsHooksSettings ), (void**)_retval ); + rv = CallQueryInterface( prefs, _retval ); // Release (to undo our Get...). NS_RELEASE( prefs ); } Index: mozilla/xpinstall/src/nsJSInstallTriggerGlobal.cpp =================================================================== RCS file: /cvsroot/mozilla/xpinstall/src/nsJSInstallTriggerGlobal.cpp,v retrieving revision 1.58 diff -u -r1.58 mozilla/xpinstall/src/nsJSInstallTriggerGlobal.cpp --- mozilla/xpinstall/src/nsJSInstallTriggerGlobal.cpp +++ mozilla/xpinstall/src/nsJSInstallTriggerGlobal.cpp @@ -103,8 +103,7 @@ if (nsnull != nativeThis) { // get the js object nsIScriptObjectOwner *owner = nsnull; - if (NS_OK == nativeThis->QueryInterface(NS_GET_IID(nsIScriptObjectOwner), - (void**)&owner)) { + if (NS_SUCCEEDED(CallQueryInterface(nativeThis, &owner))) { owner->SetScriptObject(nsnull); NS_RELEASE(owner); } @@ -126,10 +125,9 @@ result = CallCreateInstance(kInstallTrigger_CID, &nativeThis); if (NS_FAILED(result)) return JS_FALSE; - result = nativeThis->QueryInterface(NS_GET_IID(nsIScriptObjectOwner), - (void **)&owner); + result = CallQueryInterface(nativeThis, &owner); - if (NS_OK != result) + if (NS_FAILED(result)) { NS_RELEASE(nativeThis); return JS_FALSE; Index: mozilla/xpinstall/src/nsJSInstallVersion.cpp =================================================================== RCS file: /cvsroot/mozilla/xpinstall/src/nsJSInstallVersion.cpp,v retrieving revision 1.28 diff -u -r1.28 mozilla/xpinstall/src/nsJSInstallVersion.cpp --- mozilla/xpinstall/src/nsJSInstallVersion.cpp +++ mozilla/xpinstall/src/nsJSInstallVersion.cpp @@ -278,8 +278,7 @@ if (nsnull != nativeThis) { // get the js object nsIScriptObjectOwner *owner = nsnull; - if (NS_OK == nativeThis->QueryInterface(NS_GET_IID(nsIScriptObjectOwner), - (void**)&owner)) { + if (NS_SUCCEEDED(CallQueryInterface(nativeThis, &owner))) { owner->SetScriptObject(nsnull); NS_RELEASE(owner); } @@ -562,8 +561,7 @@ if (NS_FAILED(result)) return JS_FALSE; - result = nativeThis->QueryInterface(NS_GET_IID(nsIScriptObjectOwner), - (void **)&owner); + result = CallQueryInterface(nativeThis, &owner); if (NS_FAILED(result)) { NS_RELEASE(nativeThis); return JS_FALSE; @@ -668,8 +666,7 @@ if (nsnull == aParent) { parent = nsnull; } - else if (NS_OK == aParent->QueryInterface(NS_GET_IID(nsIScriptObjectOwner), - (void**)&owner)) { + else if (NS_SUCCEDED(CallQueryInterface(aParent, &owner))) { if (NS_OK != owner->GetScriptObject(aContext, (void **)&parent)) { NS_RELEASE(owner); return NS_ERROR_FAILURE; @@ -684,21 +681,20 @@ return NS_ERROR_FAILURE; } - result = aSupports->QueryInterface(NS_GET_IID(nsIDOMInstallVersion), (void **)&installVersion); - if (NS_OK != result) { + result = CallQueryInterface(aSupports, &installVersion); + if (NS_FAILED(result)) { return result; } // create a js object for this class *aReturn = JS_NewObject(jscontext, &InstallVersionClass, proto, parent); - if (nsnull != *aReturn) { - // connect the native object to the js object - JS_SetPrivate(jscontext, (JSObject *)*aReturn, installVersion); - } - else { + if (!*aReturn) { NS_RELEASE(installVersion); - return NS_ERROR_FAILURE; + return NS_ERROR_FAILURE; } + + // connect the native object to the js object + JS_SetPrivate(jscontext, (JSObject *)*aReturn, installVersion); return NS_OK; } Index: mozilla/xpinstall/stub/xpistub.cpp =================================================================== RCS file: /cvsroot/mozilla/xpinstall/stub/xpistub.cpp,v retrieving revision 1.53 diff -u -r1.53 mozilla/xpinstall/stub/xpistub.cpp --- mozilla/xpinstall/stub/xpistub.cpp +++ mozilla/xpinstall/stub/xpistub.cpp @@ -191,14 +191,11 @@ getter_AddRefs(iDirSpec)); } - if (hook && iDirSpec) - { - rv = hook->StubInitialize( iDirSpec, aLogName ); - if (NS_FAILED(rv)) return rv; - } - else + if (!hook || !iDirSpec) return NS_ERROR_NULL_POINTER; + rv = hook->StubInitialize( iDirSpec, aLogName ); + if (NS_FAILED(rv)) return rv; //-------------------------------------------------------------------- // Save the install wizard's callbacks as a nsIXPINotifer for later @@ -211,7 +208,7 @@ } else { - rv = stub->QueryInterface(NS_GET_IID(nsIXPIListener), (void**)&gListener); + rv = CallQueryInterface(stub, &gListener); } return rv; }