Bug 1577835 - Reformat mailnews/ code with eslint and Prettier. r=mkmelin

# ignore-this-changeset

These changes were achieved by:

1. Using eslint to add curly brackets to control
statements that did not have them (if, else, etc.),
thanks to the eslint rule: "curly": ["error", "all"]

Done by running |mach eslint mailnews/ --fix|

2. Reformatting the code using Prettier.

Done by deleting the mailnews/ line from
the .prettierignore file and running:
|mach eslint mailnews/ --fix|
This commit is contained in:
Paul Morris 2019-08-30 22:10:02 -04:00
Родитель c41c4bcb5f
Коммит 8057711ec3
581 изменённых файлов: 45026 добавлений и 26817 удалений

Просмотреть файл

@ -10,6 +10,5 @@
# Ignore .eslintrc.js for now.
.eslintrc.js
# Ignore all top-level directories that contain JS files (for now).
mailnews/**
# Ignore SeaMonkey files.
suite/**

Просмотреть файл

@ -2,11 +2,13 @@
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
var {MailServices} = ChromeUtils.import("resource:///modules/MailServices.jsm");
var {
fixIterator,
} = ChromeUtils.import("resource:///modules/iteratorUtils.jsm");
var {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm");
var { MailServices } = ChromeUtils.import(
"resource:///modules/MailServices.jsm"
);
var { fixIterator } = ChromeUtils.import(
"resource:///modules/iteratorUtils.jsm"
);
var { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm");
var gOkButton;
var gNameInput;
@ -25,8 +27,11 @@ function abNameOnLoad() {
gNameInput = document.getElementById("name");
// look in arguments[0] for parameters to see if we have a directory or not
if ("arguments" in window && window.arguments[0] &&
"selectedDirectory" in window.arguments[0]) {
if (
"arguments" in window &&
window.arguments[0] &&
"selectedDirectory" in window.arguments[0]
) {
gDirectory = window.arguments[0].selectedDirectory;
gNameInput.value = gDirectory.dirName;
}
@ -37,15 +42,19 @@ function abNameOnLoad() {
if (gDirectory) {
let oldListName = gDirectory.dirName;
document.title = bundle.getFormattedString("addressBookTitleEdit", [oldListName]);
document.title = bundle.getFormattedString("addressBookTitleEdit", [
oldListName,
]);
} else {
document.title = bundle.getString("addressBookTitleNew");
}
if (gDirectory &&
(gDirectory.URI == kCollectedAddressbookURI ||
gDirectory.URI == kPersonalAddressbookURI ||
gDirectory.URI == kAllDirectoryRoot + "?")) {
if (
gDirectory &&
(gDirectory.URI == kCollectedAddressbookURI ||
gDirectory.URI == kPersonalAddressbookURI ||
gDirectory.URI == kAllDirectoryRoot + "?")
) {
// Address book name is not editable, therefore disable the field and
// only have an ok button that doesn't do anything.
gNameInput.readOnly = true;
@ -61,14 +70,17 @@ function abNameOKButton(event) {
var newName = gNameInput.value.trim();
// Do not allow an already existing name.
for (let ab of fixIterator(MailServices.ab.directories,
Ci.nsIAbDirectory)) {
if ((ab.dirName.toLowerCase() == newName.toLowerCase()) &&
(!gDirectory || (ab.URI != gDirectory.URI))) {
const kAlertTitle = document.getElementById("bundle_addressBook")
.getString("duplicateNameTitle");
const kAlertText = document.getElementById("bundle_addressBook")
.getFormattedString("duplicateNameText", [ab.dirName]);
for (let ab of fixIterator(MailServices.ab.directories, Ci.nsIAbDirectory)) {
if (
ab.dirName.toLowerCase() == newName.toLowerCase() &&
(!gDirectory || ab.URI != gDirectory.URI)
) {
const kAlertTitle = document
.getElementById("bundle_addressBook")
.getString("duplicateNameTitle");
const kAlertText = document
.getElementById("bundle_addressBook")
.getFormattedString("duplicateNameText", [ab.dirName]);
Services.prompt.alert(window, kAlertTitle, kAlertText);
event.preventDefault();
return;
@ -77,11 +89,15 @@ function abNameOKButton(event) {
// Either create a new directory or update an existing one depending on what
// we were given when we started.
if (gDirectory)
if (gDirectory) {
gDirectory.dirName = newName;
else
MailServices.ab.newAddressBook(newName, "",
Services.prefs.getIntPref("mail.addr_book.newDirType", kPABDirectory));
} else {
MailServices.ab.newAddressBook(
newName,
"",
Services.prefs.getIntPref("mail.addr_book.newDirType", kPABDirectory)
);
}
}
function abNameDoOkEnabling() {

Просмотреть файл

@ -8,8 +8,12 @@
/* import-globals-from ../../../mail/components/compose/content/addressingWidgetOverlay.js */
/* import-globals-from abResultsPane.js */
var {PluralForm} = ChromeUtils.import("resource://gre/modules/PluralForm.jsm");
var {MailServices} = ChromeUtils.import("resource:///modules/MailServices.jsm");
var { PluralForm } = ChromeUtils.import(
"resource://gre/modules/PluralForm.jsm"
);
var { MailServices } = ChromeUtils.import(
"resource:///modules/MailServices.jsm"
);
// Returns the load context for the current window
function getLoadContext() {
@ -24,15 +28,27 @@ var abFlavorDataProvider = {
var primitive = {};
aTransferable.getTransferData("text/vcard", primitive, {});
var vCard = primitive.value.QueryInterface(Ci.nsISupportsString).data;
aTransferable.getTransferData("application/x-moz-file-promise-dest-filename", primitive, {});
aTransferable.getTransferData(
"application/x-moz-file-promise-dest-filename",
primitive,
{}
);
var leafName = primitive.value.QueryInterface(Ci.nsISupportsString).data;
aTransferable.getTransferData("application/x-moz-file-promise-dir", primitive, {});
aTransferable.getTransferData(
"application/x-moz-file-promise-dir",
primitive,
{}
);
var localFile = primitive.value.QueryInterface(Ci.nsIFile).clone();
localFile.append(leafName);
var ofStream = Cc["@mozilla.org/network/file-output-stream;1"].createInstance(Ci.nsIFileOutputStream);
var ofStream = Cc[
"@mozilla.org/network/file-output-stream;1"
].createInstance(Ci.nsIFileOutputStream);
ofStream.init(localFile, -1, -1, 0);
var converter = Cc["@mozilla.org/intl/converter-output-stream;1"].createInstance(Ci.nsIConverterOutputStream);
var converter = Cc[
"@mozilla.org/intl/converter-output-stream;1"
].createInstance(Ci.nsIConverterOutputStream);
converter.init(ofStream, null);
converter.writeString(vCard);
converter.close();
@ -46,8 +62,9 @@ var abResultsPaneObserver = {
onDragStart(aEvent, aXferData, aDragAction) {
var selectedRows = GetSelectedRows();
if (!selectedRows)
if (!selectedRows) {
return;
}
var selectedAddresses = GetSelectedAddresses();
@ -59,13 +76,16 @@ var abResultsPaneObserver = {
let srcDirectory = getSelectedDirectory();
// The default allowable actions are copy, move and link, so we need
// to restrict them here.
if (!srcDirectory.readOnly)
if (!srcDirectory.readOnly) {
// Only allow copy & move from read-write directories.
aDragAction.action = Ci.nsIDragService.DRAGDROP_ACTION_COPY |
Ci.nsIDragService.DRAGDROP_ACTION_MOVE;
else
// Only allow copy from read-only directories.
aDragAction.action =
Ci.nsIDragService.DRAGDROP_ACTION_COPY |
Ci.nsIDragService.DRAGDROP_ACTION_MOVE;
}
// Only allow copy from read-only directories.
else {
aDragAction.action = Ci.nsIDragService.DRAGDROP_ACTION_COPY;
}
var card = GetSelectedCard();
if (card && card.displayName) {
@ -73,33 +93,42 @@ var abResultsPaneObserver = {
// A card implementation may throw NS_ERROR_NOT_IMPLEMENTED.
// Don't break drag-and-drop if that happens.
let vCard = card.translateTo("vcard");
aXferData.data.addDataForFlavour("text/vcard", decodeURIComponent(vCard));
aXferData.data.addDataForFlavour("application/x-moz-file-promise-dest-filename", card.displayName + ".vcf");
aXferData.data.addDataForFlavour("application/x-moz-file-promise-url", "data:text/vcard," + vCard);
aXferData.data.addDataForFlavour("application/x-moz-file-promise", abFlavorDataProvider);
aXferData.data.addDataForFlavour(
"text/vcard",
decodeURIComponent(vCard)
);
aXferData.data.addDataForFlavour(
"application/x-moz-file-promise-dest-filename",
card.displayName + ".vcf"
);
aXferData.data.addDataForFlavour(
"application/x-moz-file-promise-url",
"data:text/vcard," + vCard
);
aXferData.data.addDataForFlavour(
"application/x-moz-file-promise",
abFlavorDataProvider
);
} catch (ex) {
Cu.reportError(ex);
}
}
},
onDrop(aEvent, aXferData, aDragSession) {
},
onDrop(aEvent, aXferData, aDragSession) {},
onDragExit(aEvent, aDragSession) {
},
onDragExit(aEvent, aDragSession) {},
onDragOver(aEvent, aFlavour, aDragSession) {
},
onDragOver(aEvent, aFlavour, aDragSession) {},
getSupportedFlavours() {
return null;
},
};
var dragService = Cc["@mozilla.org/widget/dragservice;1"]
.getService(Ci.nsIDragService);
var dragService = Cc["@mozilla.org/widget/dragservice;1"].getService(
Ci.nsIDragService
);
var abDirTreeObserver = {
/**
@ -128,8 +157,9 @@ var abDirTreeObserver = {
* read only directory item -> anywhere = COPY only
*/
canDrop(index, orientation, dataTransfer) {
if (orientation != Ci.nsITreeView.DROP_ON)
if (orientation != Ci.nsITreeView.DROP_ON) {
return false;
}
if (!dataTransfer.types.includes("moz/abcard")) {
return false;
}
@ -139,28 +169,33 @@ var abDirTreeObserver = {
let srcURI = getSelectedDirectoryURI();
// We cannot allow copy/move to "All Address Books".
if (targetURI == kAllDirectoryRoot + "?")
if (targetURI == kAllDirectoryRoot + "?") {
return false;
}
// The same place case
if (targetURI == srcURI)
if (targetURI == srcURI) {
return false;
}
// determine if we dragging from a mailing list on a directory x to the parent (directory x).
// if so, don't allow the drop
if (srcURI.startsWith(targetURI))
if (srcURI.startsWith(targetURI)) {
return false;
}
// check if we can write to the target directory
// e.g. LDAP is readonly currently
var targetDirectory = GetDirectoryFromURI(targetURI);
if (targetDirectory.readOnly)
if (targetDirectory.readOnly) {
return false;
}
var dragSession = dragService.getCurrentSession();
if (!dragSession)
if (!dragSession) {
return false;
}
// XXX Due to bug 373125/bug 349044 we can't specify a default action,
// so we default to move and this means that the user would have to press
@ -174,8 +209,10 @@ var abDirTreeObserver = {
var srcDirectory = GetDirectoryFromURI(srcURI);
// Only allow copy from read-only directories.
if (srcDirectory.readOnly &&
dragSession.dragAction != Ci.nsIDragService.DRAGDROP_ACTION_COPY) {
if (
srcDirectory.readOnly &&
dragSession.dragAction != Ci.nsIDragService.DRAGDROP_ACTION_COPY
) {
return false;
}
@ -186,7 +223,10 @@ var abDirTreeObserver = {
var draggingMailList = false;
// The data contains the a string of "selected rows", eg.: "1,2".
var rows = dataTransfer.getData("moz/abcard").split(",").map(j => parseInt(j, 10));
var rows = dataTransfer
.getData("moz/abcard")
.split(",")
.map(j => parseInt(j, 10));
for (var j = 0; j < rows.length; j++) {
if (gAbView.getCardFromRow(rows[j]).isMailList) {
@ -197,9 +237,11 @@ var abDirTreeObserver = {
// The rest of the cases - allow cards for copy or move, but only allow
// move of mailing lists if we're not going into another mailing list.
if (draggingMailList &&
(targetDirectory.isMailList ||
dragSession.dragAction == Ci.nsIDragService.DRAGDROP_ACTION_COPY)) {
if (
draggingMailList &&
(targetDirectory.isMailList ||
dragSession.dragAction == Ci.nsIDragService.DRAGDROP_ACTION_COPY)
) {
return false;
}
@ -214,8 +256,9 @@ var abDirTreeObserver = {
*/
onDrop(index, orientation, dataTransfer) {
var dragSession = dragService.getCurrentSession();
if (!dragSession)
if (!dragSession) {
return;
}
if (!dataTransfer.types.includes("moz/abcard")) {
return;
}
@ -224,7 +267,10 @@ var abDirTreeObserver = {
let srcURI = getSelectedDirectoryURI();
// The data contains the a string of "selected rows", eg.: "1,2".
var rows = dataTransfer.getData("moz/abcard").split(",").map(j => parseInt(j, 10));
var rows = dataTransfer
.getData("moz/abcard")
.split(",")
.map(j => parseInt(j, 10));
var numrows = rows.length;
var result;
@ -251,14 +297,20 @@ var abDirTreeObserver = {
// if so, we don't have to copy the card
if (needToCopyCard) {
var targetParentURI = GetParentDirectoryFromMailingListURI(targetURI);
if (targetParentURI && (targetParentURI == GetParentDirectoryFromMailingListURI(srcURI)))
if (
targetParentURI &&
targetParentURI == GetParentDirectoryFromMailingListURI(srcURI)
) {
needToCopyCard = false;
}
}
var directory = GetDirectoryFromURI(targetURI);
// Only move if we are not transferring to a mail list
var actionIsMoving = (dragSession.dragAction & dragSession.DRAGDROP_ACTION_MOVE) && !directory.isMailList;
var actionIsMoving =
dragSession.dragAction & dragSession.DRAGDROP_ACTION_MOVE &&
!directory.isMailList;
let cardsToCopy = [];
for (let j = 0; j < numrows; j++) {
@ -272,8 +324,11 @@ var abDirTreeObserver = {
}
} else {
let srcDirectory = null;
if (srcURI == (kAllDirectoryRoot + "?") && actionIsMoving) {
let dirId = card.directoryId.substring(0, card.directoryId.indexOf("&"));
if (srcURI == kAllDirectoryRoot + "?" && actionIsMoving) {
let dirId = card.directoryId.substring(
0,
card.directoryId.indexOf("&")
);
srcDirectory = MailServices.ab.getDirectoryFromId(dirId);
}
@ -281,9 +336,9 @@ var abDirTreeObserver = {
// This is true only if srcURI is "All ABs" and action is moving.
if (srcDirectory) {
let cardArray =
Cc["@mozilla.org/array;1"]
.createInstance(Ci.nsIMutableArray);
let cardArray = Cc["@mozilla.org/array;1"].createInstance(
Ci.nsIMutableArray
);
cardArray.appendElement(card);
srcDirectory.deleteCards(cardArray);
}
@ -294,17 +349,21 @@ var abDirTreeObserver = {
// If we are moving, but not moving to a directory, then delete the
// selected cards and display the appropriate text
if (actionIsMoving && srcURI != (kAllDirectoryRoot + "?")) {
if (actionIsMoving && srcURI != kAllDirectoryRoot + "?") {
// If we have moved the cards, then delete them as well.
gAbView.deleteSelectedCards();
}
if (actionIsMoving) {
cardsTransferredText = PluralForm.get(numrows,
gAddressBookBundle.getFormattedString("contactsMoved", [numrows]));
cardsTransferredText = PluralForm.get(
numrows,
gAddressBookBundle.getFormattedString("contactsMoved", [numrows])
);
} else {
cardsTransferredText = PluralForm.get(numrows,
gAddressBookBundle.getFormattedString("contactsCopied", [numrows]));
cardsTransferredText = PluralForm.get(
numrows,
gAddressBookBundle.getFormattedString("contactsCopied", [numrows])
);
}
if (srcURI == kAllDirectoryRoot + "?") {
@ -314,36 +373,31 @@ var abDirTreeObserver = {
document.getElementById("statusText").label = cardsTransferredText;
},
onToggleOpenState() {
},
onToggleOpenState() {},
onCycleHeader(colID, elt) {
},
onCycleHeader(colID, elt) {},
onCycleCell(row, colID) {
},
onCycleCell(row, colID) {},
onSelectionChanged() {
},
onSelectionChanged() {},
onPerformAction(action) {
},
onPerformAction(action) {},
onPerformActionOnRow(action, row) {
},
onPerformActionOnRow(action, row) {},
onPerformActionOnCell(action, row, colID) {
},
onPerformActionOnCell(action, row, colID) {},
};
function DragAddressOverTargetControl(event) {
var dragSession = gDragService.getCurrentSession();
if (!dragSession.isDataFlavorSupported("text/x-moz-address"))
return;
if (!dragSession.isDataFlavorSupported("text/x-moz-address")) {
return;
}
var trans = Cc["@mozilla.org/widget/transferable;1"]
.createInstance(Ci.nsITransferable);
var trans = Cc["@mozilla.org/widget/transferable;1"].createInstance(
Ci.nsITransferable
);
trans.init(getLoadContext());
trans.addDataFlavor("text/x-moz-address");
@ -367,7 +421,9 @@ function DragAddressOverTargetControl(event) {
function DropAddressOverTargetControl(event) {
var dragSession = gDragService.getCurrentSession();
var trans = Cc["@mozilla.org/widget/transferable;1"].createInstance(Ci.nsITransferable);
var trans = Cc["@mozilla.org/widget/transferable;1"].createInstance(
Ci.nsITransferable
);
trans.addDataFlavor("text/x-moz-address");
for (var i = 0; i < dragSession.numDropItems; ++i) {
@ -383,15 +439,18 @@ function DropAddressOverTargetControl(event) {
continue;
}
if (dataObj)
if (dataObj) {
dataObj = dataObj.value.QueryInterface(Ci.nsISupportsString);
if (!dataObj)
}
if (!dataObj) {
continue;
}
// pull the address out of the data object
var address = dataObj.data.substring(0, len.value);
if (!address)
if (!address) {
continue;
}
DropRecipient(address);
}

Просмотреть файл

@ -5,9 +5,13 @@
/* import-globals-from ../../../mail/components/addrbook/content/abCommon.js */
/* import-globals-from ../../../mail/components/compose/content/addressingWidgetOverlay.js */
var {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm");
var {MailServices} = ChromeUtils.import("resource:///modules/MailServices.jsm");
var {AppConstants} = ChromeUtils.import("resource://gre/modules/AppConstants.jsm");
var { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm");
var { MailServices } = ChromeUtils.import(
"resource:///modules/MailServices.jsm"
);
var { AppConstants } = ChromeUtils.import(
"resource://gre/modules/AppConstants.jsm"
);
top.MAX_RECIPIENTS = 1;
var inputElementType = "";
@ -19,10 +23,10 @@ var gLoadListeners = [];
var gSaveListeners = [];
try {
var gDragService = Cc["@mozilla.org/widget/dragservice;1"]
.getService(Ci.nsIDragService);
} catch (e) {
}
var gDragService = Cc["@mozilla.org/widget/dragservice;1"].getService(
Ci.nsIDragService
);
} catch (e) {}
// Returns the load context for the current window
function getLoadContext() {
@ -31,9 +35,11 @@ function getLoadContext() {
function mailingListExists(listname) {
if (MailServices.ab.mailListNameExists(listname)) {
Services.prompt.alert(window,
Services.prompt.alert(
window,
gAddressBookBundle.getString("mailListNameExistsTitle"),
gAddressBookBundle.getString("mailListNameExistsMessage"));
gAddressBookBundle.getString("mailListNameExistsMessage")
);
return true;
}
return false;
@ -51,11 +57,13 @@ function GetListValue(mailList, doAdd) {
var canonicalNewListName = listname.toLowerCase();
var canonicalOldListName = oldListName.toLowerCase();
if (doAdd) {
if (mailingListExists(canonicalNewListName))
if (mailingListExists(canonicalNewListName)) {
return false;
}
} else if (canonicalOldListName != canonicalNewListName) {
if (mailingListExists(canonicalNewListName))
if (mailingListExists(canonicalNewListName)) {
return false;
}
}
mailList.isMailList = true;
@ -70,36 +78,46 @@ function GetListValue(mailList, doAdd) {
while ((inputField = awGetInputElement(i))) {
fieldValue = inputField.value;
if (doAdd || pos >= oldTotal)
cardproperty = Cc["@mozilla.org/addressbook/cardproperty;1"].createInstance();
else
if (doAdd || pos >= oldTotal) {
cardproperty = Cc[
"@mozilla.org/addressbook/cardproperty;1"
].createInstance();
} else {
cardproperty = mailList.addressLists.queryElementAt(pos, Ci.nsIAbCard);
}
if (fieldValue == "") {
if (!doAdd && cardproperty)
try {
mailList.addressLists.removeElementAt(pos);
--oldTotal;
} catch (ex) {
// Ignore attempting to remove an item
// at a position greater than the number
// of elements in the addressLists attribute
if (!doAdd && cardproperty) {
try {
mailList.addressLists.removeElementAt(pos);
--oldTotal;
} catch (ex) {
// Ignore attempting to remove an item
// at a position greater than the number
// of elements in the addressLists attribute
}
}
} else if (cardproperty) {
cardproperty = cardproperty.QueryInterface(Ci.nsIAbCard);
if (cardproperty) {
let addrObjects = MailServices.headerParser
.makeFromDisplayAddress(fieldValue, {});
let addrObjects = MailServices.headerParser.makeFromDisplayAddress(
fieldValue,
{}
);
for (let j = 0; j < addrObjects.length; j++) {
if (j > 0) {
cardproperty = Cc["@mozilla.org/addressbook/cardproperty;1"].createInstance();
cardproperty = Cc[
"@mozilla.org/addressbook/cardproperty;1"
].createInstance();
cardproperty = cardproperty.QueryInterface(Ci.nsIAbCard);
}
cardproperty.primaryEmail = addrObjects[j].email;
cardproperty.displayName = addrObjects[j].name || addrObjects[j].email;
cardproperty.displayName =
addrObjects[j].name || addrObjects[j].email;
if (doAdd || pos >= oldTotal)
if (doAdd || pos >= oldTotal) {
mailList.addressLists.appendElement(cardproperty);
}
}
pos++;
}
@ -110,8 +128,9 @@ function GetListValue(mailList, doAdd) {
--i;
if (!doAdd && i < oldTotal) {
for (var j = i; j < oldTotal; j++)
for (var j = i; j < oldTotal; j++) {
mailList.addressLists.removeElementAt(j);
}
}
return true;
}
@ -125,12 +144,14 @@ function MailListOKButton(event) {
// should be able to just remove this if we are not seeing blank lines in the ab popup
if (!uri) {
event.preventDefault();
return; // don't close window
return; // don't close window
}
// -----
// Add mailing list to database
var mailList = Cc["@mozilla.org/addressbook/directoryproperty;1"].createInstance();
var mailList = Cc[
"@mozilla.org/addressbook/directoryproperty;1"
].createInstance();
mailList = mailList.QueryInterface(Ci.nsIAbDirectory);
if (GetListValue(mailList, true)) {
@ -165,8 +186,9 @@ function OnLoadNewMailList() {
}
}
if (!selectedAB)
if (!selectedAB) {
selectedAB = kPersonalAddressbookURI;
}
// set popup with address book names
var abPopup = document.getElementById("abPopup");
@ -182,8 +204,15 @@ function OnLoadNewMailList() {
// focus on first name
var listName = document.getElementById("ListName");
if (listName)
setTimeout(function(firstTextBox) { firstTextBox.focus(); }, 0, listName);
if (listName) {
setTimeout(
function(firstTextBox) {
firstTextBox.focus();
},
0,
listName
);
}
NotifyLoadListeners(directory);
}
@ -203,7 +232,7 @@ function EditListOKButton(event) {
gEditList.editMailListToDatabase(gListCard);
window.arguments[0].refresh = true;
return; // close the window
return; // close the window
}
event.preventDefault();
@ -213,7 +242,7 @@ function OnLoadEditList() {
InitCommonJS();
gListCard = window.arguments[0].abCard;
var listUri = window.arguments[0].listURI;
var listUri = window.arguments[0].listURI;
gEditList = GetDirectoryFromURI(listUri);
@ -222,7 +251,10 @@ function OnLoadEditList() {
document.getElementById("ListDescription").value = gEditList.description;
oldListName = gEditList.dirName;
document.title = gAddressBookBundle.getFormattedString("mailingListTitleEdit", [oldListName]);
document.title = gAddressBookBundle.getFormattedString(
"mailingListTitleEdit",
[oldListName]
);
if (gEditList.addressLists) {
let total = gEditList.addressLists.length;
@ -234,8 +266,9 @@ function OnLoadEditList() {
top.MAX_RECIPIENTS = 0;
for (let i = 0; i < total; i++) {
let card = gEditList.addressLists.queryElementAt(i, Ci.nsIAbCard);
let address = MailServices.headerParser.makeMailboxObject(
card.displayName, card.primaryEmail).toString();
let address = MailServices.headerParser
.makeMailboxObject(card.displayName, card.primaryEmail)
.toString();
SetInputValue(address, newListBoxNode, templateNode);
}
listbox.parentNode.replaceChild(newListBoxNode, listbox);
@ -247,8 +280,9 @@ function OnLoadEditList() {
if (gEditList.readOnly) {
const kMailListFields = ["ListName", "ListNickName", "ListDescription"];
for (let i = 0; i < kMailListFields.length; ++i)
for (let i = 0; i < kMailListFields.length; ++i) {
document.getElementById(kMailListFields[i]).readOnly = true;
}
document.documentElement.buttons = "accept";
document.documentElement.removeAttribute("ondialogaccept");
@ -278,16 +312,18 @@ function AppendLastRow() {
// focus on first name
let listName = document.getElementById("ListName");
if (listName)
if (listName) {
listName.focus();
}
}
function AppendNewRowAndSetFocus() {
let lastInput = awGetInputElement(top.MAX_RECIPIENTS);
if (lastInput && lastInput.value)
if (lastInput && lastInput.value) {
awAppendNewRow(true);
else
} else {
awSetFocusTo(lastInput);
}
}
function SetInputValue(inputValue, parentNode, templateNode) {
@ -310,32 +346,36 @@ function awNotAnEmptyArea(event) {
// This is temporary until i figure out how to ensure to always having an empty space after the last row
var lastInput = awGetInputElement(top.MAX_RECIPIENTS);
if (lastInput && lastInput.value)
if (lastInput && lastInput.value) {
awAppendNewRow(false);
}
event.stopPropagation();
}
function awClickEmptySpace(target, setFocus) {
if (target == null || target.localName != "hbox")
if (target == null || target.localName != "hbox") {
return;
}
let lastInput = awGetInputElement(top.MAX_RECIPIENTS);
if (lastInput && lastInput.value)
if (lastInput && lastInput.value) {
awAppendNewRow(setFocus);
else if (setFocus)
} else if (setFocus) {
awSetFocusTo(lastInput);
}
}
function awReturnHit(inputElement) {
let row = awGetRowByInputElement(inputElement);
if (inputElement.value) {
let nextInput = awGetInputElement(row + 1);
if (!nextInput)
if (!nextInput) {
awAppendNewRow(true);
else
} else {
awSetFocusTo(nextInput);
}
}
}
@ -345,26 +385,33 @@ function awDeleteRow(rowToDelete) {
awRemoveRow(rowToDelete);
var numberOfCols = awGetNumberOfCols();
for (var row = rowToDelete + 1; row <= maxRecipients; row++)
for (var col = 1; col <= numberOfCols; col++)
awGetElementByCol(row, col).setAttribute("id", "addressCol" + (col) + "#" + (row - 1));
for (var row = rowToDelete + 1; row <= maxRecipients; row++) {
for (var col = 1; col <= numberOfCols; col++) {
awGetElementByCol(row, col).setAttribute(
"id",
"addressCol" + col + "#" + (row - 1)
);
}
}
awTestRowSequence();
}
function awInputChanged(inputElement) {
// AutoCompleteAddress(inputElement);
// AutoCompleteAddress(inputElement);
// Do we need to add a new row?
var lastInput = awGetInputElement(top.MAX_RECIPIENTS);
if (lastInput && lastInput.value && !top.doNotCreateANewRow)
if (lastInput && lastInput.value && !top.doNotCreateANewRow) {
awAppendNewRow(false);
}
top.doNotCreateANewRow = false;
}
function awInputElementName() {
if (inputElementType == "")
inputElementType = document.getElementById("addressCol1#1").localName;
if (inputElementType == "") {
inputElementType = document.getElementById("addressCol1#1").localName;
}
return inputElementType;
}
@ -382,10 +429,11 @@ function awAppendNewRow(setFocus) {
if (body && listitem1) {
let nextDummy = awGetNextDummyRow();
let newNode = listitem1.cloneNode(true);
if (nextDummy)
if (nextDummy) {
body.replaceChild(newNode, nextDummy);
else
} else {
body.appendChild(newNode);
}
top.MAX_RECIPIENTS++;
@ -394,17 +442,18 @@ function awAppendNewRow(setFocus) {
input[0].setAttribute("value", "");
input[0].setAttribute("id", "addressCol1#" + top.MAX_RECIPIENTS);
if (input[0].getAttribute("focused") != "")
if (input[0].getAttribute("focused") != "") {
input[0].removeAttribute("focused");
}
}
// Focus the new input widget.
if (setFocus && input)
if (setFocus && input) {
awSetFocusTo(input[0]);
}
}
return input ? input[0] : null;
}
// functions for accessing the elements in the addressing widget
function awGetInputElement(row) {
@ -425,9 +474,11 @@ function DropOnAddressListTree(event) {
let trans;
try {
trans = Cc["@mozilla.org/widget/transferable;1"].createInstance(Ci.nsITransferable);
trans.init(getLoadContext());
trans.addDataFlavor("text/x-moz-address");
trans = Cc["@mozilla.org/widget/transferable;1"].createInstance(
Ci.nsITransferable
);
trans.init(getLoadContext());
trans.addDataFlavor("text/x-moz-address");
} catch (ex) {
return;
}
@ -438,15 +489,18 @@ function DropOnAddressListTree(event) {
let bestFlavor = {};
let len = {};
trans.getAnyTransferData(bestFlavor, dataObj, len);
if (dataObj)
if (dataObj) {
dataObj = dataObj.value.QueryInterface(Ci.nsISupportsString);
if (!dataObj)
}
if (!dataObj) {
continue;
}
// pull the URL out of the data object
let address = dataObj.data.substring(0, len.value);
if (!address)
if (!address) {
continue;
}
DropListAddress(event.target, address);
}
@ -455,14 +509,21 @@ function DropOnAddressListTree(event) {
function DropListAddress(target, address) {
// Set focus on a new available, visible row.
awClickEmptySpace(target, true);
if (top.MAX_RECIPIENTS == 0)
if (top.MAX_RECIPIENTS == 0) {
top.MAX_RECIPIENTS = 1;
}
// Break apart the MIME-ready header address into individual addressees to
// add to the dialog.
let addresses = {}, names = {}, fullNames = {};
MailServices.headerParser.parseHeadersWithArray(address, addresses, names,
fullNames);
let addresses = {},
names = {},
fullNames = {};
MailServices.headerParser.parseHeadersWithArray(
address,
addresses,
names,
fullNames
);
for (let full of fullNames.value) {
let lastInput = awGetInputElement(top.MAX_RECIPIENTS);
lastInput.value = full;
@ -484,8 +545,9 @@ function RegisterLoadListener(aListener) {
*/
function UnregisterLoadListener(aListener) {
var fIndex = gLoadListeners.indexOf(aListener);
if (fIndex != -1)
if (fIndex != -1) {
gLoadListeners.splice(fIndex, 1);
}
}
/* Allows extensions to register a listener function for
@ -502,21 +564,23 @@ function RegisterSaveListener(aListener) {
*/
function UnregisterSaveListener(aListener) {
var fIndex = gSaveListeners.indexOf(aListener);
if (fIndex != -1)
if (fIndex != -1) {
gSaveListeners.splice(fIndex, 1);
}
}
/* Notifies all load listeners.
*/
function NotifyLoadListeners(aMailingList) {
for (let i = 0; i < gLoadListeners.length; i++)
for (let i = 0; i < gLoadListeners.length; i++) {
gLoadListeners[i](aMailingList, document);
}
}
/* Notifies all save listeners.
*/
function NotifySaveListeners(aMailingList) {
for (let i = 0; i < gSaveListeners.length; i++)
for (let i = 0; i < gSaveListeners.length; i++) {
gSaveListeners[i](aMailingList, document);
}
}

Просмотреть файл

@ -64,24 +64,31 @@ function SetAbView(aURI) {
sortColumn = gAbView.sortColumn;
sortDirection = gAbView.sortDirection;
} else {
if (gAbResultsTree.hasAttribute("sortCol"))
if (gAbResultsTree.hasAttribute("sortCol")) {
sortColumn = gAbResultsTree.getAttribute("sortCol");
}
var sortColumnNode = document.getElementById(sortColumn);
if (sortColumnNode && sortColumnNode.hasAttribute("sortDirection"))
if (sortColumnNode && sortColumnNode.hasAttribute("sortDirection")) {
sortDirection = sortColumnNode.getAttribute("sortDirection");
}
}
var directory = GetDirectoryFromURI(aURI);
if (!gAbView)
gAbView = Cc["@mozilla.org/addressbook/abview;1"]
.createInstance(Ci.nsIAbView);
if (!gAbView) {
gAbView = Cc["@mozilla.org/addressbook/abview;1"].createInstance(
Ci.nsIAbView
);
}
var actualSortColumn = gAbView.setView(directory, GetAbViewListener(),
sortColumn, sortDirection);
var actualSortColumn = gAbView.setView(
directory,
GetAbViewListener(),
sortColumn,
sortDirection
);
gAbResultsTree.view =
gAbView.QueryInterface(Ci.nsITreeView);
gAbResultsTree.view = gAbView.QueryInterface(Ci.nsITreeView);
UpdateSortIndicators(actualSortColumn, sortDirection);
@ -89,31 +96,40 @@ function SetAbView(aURI) {
// inform the user of the empty results pane.
let abResultsTree = document.getElementById("abResultsTree");
let cardViewOuterBox = document.getElementById("CardViewOuterBox");
let blankResultsPaneMessageBox = document.getElementById("blankResultsPaneMessageBox");
let blankResultsPaneMessageBox = document.getElementById(
"blankResultsPaneMessageBox"
);
if (aURI.startsWith("moz-abldapdirectory://") && !aURI.includes("?")) {
if (abResultsTree)
if (abResultsTree) {
abResultsTree.hidden = true;
if (cardViewOuterBox)
}
if (cardViewOuterBox) {
cardViewOuterBox.hidden = true;
if (blankResultsPaneMessageBox)
}
if (blankResultsPaneMessageBox) {
blankResultsPaneMessageBox.hidden = false;
}
} else {
if (abResultsTree)
if (abResultsTree) {
abResultsTree.hidden = false;
if (cardViewOuterBox)
}
if (cardViewOuterBox) {
cardViewOuterBox.hidden = false;
if (blankResultsPaneMessageBox)
}
if (blankResultsPaneMessageBox) {
blankResultsPaneMessageBox.hidden = true;
}
}
}
function CloseAbView() {
if (gAbView)
if (gAbView) {
gAbView.clearView();
}
}
function GetOneOrMoreCardsSelected() {
return (gAbView && (gAbView.selection.getRangeCount() > 0));
return gAbView && gAbView.selection.getRangeCount() > 0;
}
function GetSelectedAddresses() {
@ -121,13 +137,12 @@ function GetSelectedAddresses() {
}
function GetNumSelectedCards() {
try {
return gAbView.selection.count;
} catch (ex) {
}
try {
return gAbView.selection.count;
} catch (ex) {}
// if something went wrong, return 0 for the count.
return 0;
// if something went wrong, return 0 for the count.
return 0;
}
function GetSelectedCardTypes() {
@ -137,17 +152,19 @@ function GetSelectedCardTypes() {
return kNothingSelected; // no view
}
var count = cards.length;
if (count == 0)
return kNothingSelected; // nothing selected
if (count == 0) {
return kNothingSelected;
} // nothing selected
var mailingListCnt = 0;
var cardCnt = 0;
for (let i = 0; i < count; i++) {
// We can assume no values from GetSelectedAbCards will be null.
if (cards[i].isMailList)
if (cards[i].isMailList) {
mailingListCnt++;
else
} else {
cardCnt++;
}
}
if (mailingListCnt == 0) {
@ -164,16 +181,18 @@ function GetSelectedCardTypes() {
// NOTE, will return -1 if more than one card selected, or no cards selected.
function GetSelectedCardIndex() {
if (!gAbView)
if (!gAbView) {
return -1;
}
var treeSelection = gAbView.selection;
if (treeSelection.getRangeCount() == 1) {
var start = {};
var end = {};
treeSelection.getRangeAt(0, start, end);
if (start.value == end.value)
if (start.value == end.value) {
return start.value;
}
}
return -1;
@ -182,7 +201,7 @@ function GetSelectedCardIndex() {
// NOTE, returns the card if exactly one card is selected, null otherwise
function GetSelectedCard() {
var index = GetSelectedCardIndex();
return (index == -1) ? null : gAbView.getCardFromRow(index);
return index == -1 ? null : gAbView.getCardFromRow(index);
}
/**
@ -198,14 +217,19 @@ function GetSelectedAbCards() {
if (document.getElementById("sidebar-box")) {
const abPanelUrl =
"chrome://messenger/content/addressbook/addressbook-panel.xul";
if (gCurFrame &&
gCurFrame.getAttribute("src") == abPanelUrl &&
document.commandDispatcher.focusedWindow == gCurFrame.contentDocument.defaultView)
if (
gCurFrame &&
gCurFrame.getAttribute("src") == abPanelUrl &&
document.commandDispatcher.focusedWindow ==
gCurFrame.contentDocument.defaultView
) {
abView = gCurFrame.contentDocument.defaultView.gAbView;
}
}
if (!abView)
if (!abView) {
return [];
}
let cards = [];
var count = abView.selection.getRangeCount();
@ -233,8 +257,9 @@ function GetSelectedAbCards() {
function GetSelectedRows() {
var selectedRows = "";
if (!gAbView)
if (!gAbView) {
return selectedRows;
}
var rangeCount = gAbView.selection.getRangeCount();
for (let i = 0; i < rangeCount; ++i) {
@ -242,8 +267,9 @@ function GetSelectedRows() {
var end = {};
gAbView.selection.getRangeAt(i, start, end);
for (let j = start.value; j <= end.value; ++j) {
if (selectedRows)
if (selectedRows) {
selectedRows += ",";
}
selectedRows += j;
}
}
@ -252,8 +278,9 @@ function GetSelectedRows() {
}
function AbSwapFirstNameLastName() {
if (gAbView)
if (gAbView) {
gAbView.swapFirstNameLastName();
}
}
function AbEditSelectedCard() {
@ -262,7 +289,9 @@ function AbEditSelectedCard() {
function AbResultsPaneOnClick(event) {
// we only care about button 0 (left click) events
if (event.button != 0) return;
if (event.button != 0) {
return;
}
// all we need to worry about here is double clicks
// and column header clicks.
@ -278,18 +307,22 @@ function AbResultsPaneOnClick(event) {
var currentDirection = t.getAttribute("sortDirection");
// Revert the sort order. If none is set, use Ascending.
sortDirection = currentDirection == kDefaultAscending ?
kDefaultDescending : kDefaultAscending;
sortDirection =
currentDirection == kDefaultAscending
? kDefaultDescending
: kDefaultAscending;
SortAndUpdateIndicators(t.id, sortDirection);
} else if (t.localName == "treechildren") {
// figure out what row the click was in
var row = gAbResultsTree.getRowAt(event.clientX, event.clientY);
if (row == -1)
if (row == -1) {
return;
}
if (event.detail == 2)
if (event.detail == 2) {
AbResultsPaneDoubleClick(gAbView.getCardFromRow(row));
}
}
}
@ -305,8 +338,9 @@ function AbSortDescending() {
function SortResultPane(sortColumn) {
var sortDirection = kDefaultAscending;
if (gAbView)
sortDirection = gAbView.sortDirection;
if (gAbView) {
sortDirection = gAbView.sortDirection;
}
SortAndUpdateIndicators(sortColumn, sortDirection);
}
@ -314,8 +348,9 @@ function SortResultPane(sortColumn) {
function SortAndUpdateIndicators(sortColumn, sortDirection) {
UpdateSortIndicators(sortColumn, sortDirection);
if (gAbView)
if (gAbView) {
gAbView.sortBy(sortColumn, sortDirection);
}
}
function UpdateSortIndicators(colID, sortDirection) {
@ -334,15 +369,17 @@ function UpdateSortIndicators(colID, sortDirection) {
// except the one we are sorted by
var currCol = gAbResultsTree.firstChild.firstChild;
while (currCol) {
if (currCol != sortedColumn && currCol.localName == "treecol")
if (currCol != sortedColumn && currCol.localName == "treecol") {
currCol.removeAttribute("sortDirection");
}
currCol = currCol.nextSibling;
}
}
function InvalidateResultsPane() {
if (gAbResultsTree)
if (gAbResultsTree) {
gAbResultsTree.invalidate();
}
}
// Controller object for Results Pane
@ -372,13 +409,14 @@ var ResultsPaneController = {
let numSelected;
let enabled = false;
if (gAbView && gAbView.selection) {
if (gAbView.directory)
if (gAbView.directory) {
enabled = !gAbView.directory.readOnly;
}
numSelected = gAbView.selection.count;
} else {
numSelected = 0;
}
enabled = enabled && (numSelected > 0);
enabled = enabled && numSelected > 0;
let labelAttr = null;
if (command == "cmd_delete") {
@ -394,7 +432,7 @@ var ResultsPaneController = {
break;
case kCardsOnly:
default:
labelAttr = (numSelected < 2) ? "valueCard" : "valueCards";
labelAttr = numSelected < 2 ? "valueCard" : "valueCards";
}
}
document.querySelectorAll(`[command=${command}]`).forEach(e => {
@ -407,7 +445,7 @@ var ResultsPaneController = {
}
case "cmd_printcardpreview":
case "cmd_printcard":
return (GetNumSelectedCards() > 0);
return GetNumSelectedCards() > 0;
case "cmd_properties": {
let attrs = {
label: "valueGeneric",
@ -435,7 +473,7 @@ var ResultsPaneController = {
break;
}
let enabled = (GetNumSelectedCards() == 1);
let enabled = GetNumSelectedCards() == 1;
document.querySelectorAll("[command=cmd_properties]").forEach(e => {
e.disabled = !enabled;
for (let [attr, name] of Object.entries(attrs)) {
@ -457,8 +495,9 @@ var ResultsPaneController = {
doCommand(command) {
switch (command) {
case "cmd_selectAll":
if (gAbView)
if (gAbView) {
gAbView.selectAll();
}
break;
case "cmd_delete":
case "button_delete":
@ -478,12 +517,14 @@ var ResultsPaneController = {
onEvent(event) {
// on blur events set the menu item texts back to the normal values
if (event == "blur")
if (event == "blur") {
goSetMenuValue("cmd_delete", "valueDefault");
}
},
};
function SelectFirstCard() {
if (gAbView && gAbView.selection && (gAbView.selection.count > 0))
if (gAbView && gAbView.selection && gAbView.selection.count > 0) {
gAbView.selection.select(0);
}
}

Просмотреть файл

@ -1,6 +1,6 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
"use strict";
@ -8,7 +8,9 @@
// Wrap in a block to prevent leaking to window scope.
{
const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm");
const { Services } = ChromeUtils.import(
"resource://gre/modules/Services.jsm"
);
/**
* The MozMapList widget behaves as a popup menu showing available map options
@ -23,12 +25,12 @@
}
this.setAttribute("is", "map-list");
this.addEventListener("command", (event) => {
this.addEventListener("command", event => {
this._chooseMapService(event.target);
event.stopPropagation();
});
this.addEventListener("popupshowing", (event) => {
this.addEventListener("popupshowing", event => {
this._listMapServices();
});
@ -77,13 +79,17 @@
_getMapURLPref(index = 0) {
let url = null;
if (!index) {
url = Services.prefs.getComplexValue("mail.addr_book.mapit_url.format",
Ci.nsIPrefLocalizedString).data;
url = Services.prefs.getComplexValue(
"mail.addr_book.mapit_url.format",
Ci.nsIPrefLocalizedString
).data;
} else {
try {
url = Services.prefs.getComplexValue("mail.addr_book.mapit_url." + index + ".format",
Ci.nsIPrefLocalizedString).data;
} catch (e) { }
url = Services.prefs.getComplexValue(
"mail.addr_book.mapit_url." + index + ".format",
Ci.nsIPrefLocalizedString
).data;
} catch (e) {}
}
return url;
@ -132,8 +138,10 @@
} else {
// Name is not mandatory, generate one if not found.
try {
urlName = Services.prefs.getComplexValue("mail.addr_book.mapit_url." + index + ".name",
Ci.nsIPrefLocalizedString).data;
urlName = Services.prefs.getComplexValue(
"mail.addr_book.mapit_url." + index + ".name",
Ci.nsIPrefLocalizedString
).data;
} catch (e) {
urlName = generateName(urlTemplate);
}
@ -141,8 +149,9 @@
if (itemFound) {
addMapService(urlTemplate, urlName);
index++;
if (urlTemplate == defaultUrl)
if (urlTemplate == defaultUrl) {
defaultFound = true;
}
} else if (index < kUserIndex) {
// After iterating the base region provided urls, check for user defined ones.
index = kUserIndex;
@ -155,10 +164,14 @@
// 'index' now points to the first unused entry in prefs.
let defaultName = generateName(defaultUrl);
addMapService(defaultUrl, defaultName);
Services.prefs.setCharPref("mail.addr_book.mapit_url." + index + ".format",
defaultUrl);
Services.prefs.setCharPref("mail.addr_book.mapit_url." + index + ".name",
defaultName);
Services.prefs.setCharPref(
"mail.addr_book.mapit_url." + index + ".format",
defaultUrl
);
Services.prefs.setCharPref(
"mail.addr_book.mapit_url." + index + ".name",
defaultName
);
}
}
@ -168,11 +181,15 @@
*/
_chooseMapService(item) {
// Save selected URL as the default.
let defaultUrl = Cc["@mozilla.org/pref-localizedstring;1"]
.createInstance(Ci.nsIPrefLocalizedString);
let defaultUrl = Cc["@mozilla.org/pref-localizedstring;1"].createInstance(
Ci.nsIPrefLocalizedString
);
defaultUrl.data = item.getAttribute("url");
Services.prefs.setComplexValue("mail.addr_book.mapit_url.format",
Ci.nsIPrefLocalizedString, defaultUrl);
Services.prefs.setComplexValue(
"mail.addr_book.mapit_url.format",
Ci.nsIPrefLocalizedString,
defaultUrl
);
}
/**
@ -196,5 +213,5 @@
}
}
customElements.define("map-list", MozMapList, { "extends": "menupopup" });
customElements.define("map-list", MozMapList, { extends: "menupopup" });
}

Просмотреть файл

@ -4,8 +4,16 @@
this.EXPORTED_SYMBOLS = ["AddrBookCard"];
ChromeUtils.defineModuleGetter(this, "MailServices", "resource:///modules/MailServices.jsm");
ChromeUtils.defineModuleGetter(this, "newUID", "resource:///modules/AddrBookUtils.jsm");
ChromeUtils.defineModuleGetter(
this,
"MailServices",
"resource:///modules/MailServices.jsm"
);
ChromeUtils.defineModuleGetter(
this,
"newUID",
"resource:///modules/AddrBookUtils.jsm"
);
/**
* Prototype for nsIAbCard objects that are not mailing lists.
@ -33,11 +41,17 @@ AddrBookCard.prototype = {
case Ci.nsIAbItem.GENERATE_DISPLAY_NAME:
return this.displayName;
case Ci.nsIAbItem.GENERATE_LAST_FIRST_ORDER:
format = bundle ? bundle.GetStringFromName("lastFirstFormat") : "%S, %S";
return format.replace("%S", this.lastName).replace("%S", this.firstName);
format = bundle
? bundle.GetStringFromName("lastFirstFormat")
: "%S, %S";
return format
.replace("%S", this.lastName)
.replace("%S", this.firstName);
case Ci.nsIAbItem.GENERATE_FIRST_LAST_ORDER:
format = bundle ? bundle.GetStringFromName("firstLastFormat") : "%S %S";
return format.replace("%S", this.firstName).replace("%S", this.lastName);
return format
.replace("%S", this.firstName)
.replace("%S", this.lastName);
}
return "";
@ -49,13 +63,13 @@ AddrBookCard.prototype = {
return this._directoryId;
},
set directoryId(value) {
return this._directoryId = value;
return (this._directoryId = value);
},
get localId() {
return this._localId;
},
set localId(value) {
return this._localId = value;
return (this._localId = value);
},
get UID() {
if (!this._uid) {
@ -90,7 +104,7 @@ AddrBookCard.prototype = {
QueryInterface: ChromeUtils.generateQI([Ci.nsIProperty]),
};
},
* [Symbol.iterator]() {
*[Symbol.iterator]() {
while (this.hasMoreElements()) {
yield this.getNext();
}

Просмотреть файл

@ -4,15 +4,51 @@
this.EXPORTED_SYMBOLS = ["AddrBookDirectory", "closeConnectionTo"];
ChromeUtils.defineModuleGetter(this, "FileUtils", "resource://gre/modules/FileUtils.jsm");
ChromeUtils.defineModuleGetter(this, "MailServices", "resource:///modules/MailServices.jsm");
ChromeUtils.defineModuleGetter(this, "Services", "resource://gre/modules/Services.jsm");
ChromeUtils.defineModuleGetter(this, "SimpleEnumerator", "resource:///modules/AddrBookUtils.jsm");
ChromeUtils.defineModuleGetter(this, "fixIterator", "resource:///modules/iteratorUtils.jsm");
ChromeUtils.defineModuleGetter(this, "AddrBookCard", "resource:///modules/AddrBookCard.jsm");
ChromeUtils.defineModuleGetter(this, "AddrBookMailingList", "resource:///modules/AddrBookMailingList.jsm");
ChromeUtils.defineModuleGetter(this, "newUID", "resource:///modules/AddrBookUtils.jsm");
ChromeUtils.defineModuleGetter(this, "toXPCOMArray", "resource:///modules/iteratorUtils.jsm");
ChromeUtils.defineModuleGetter(
this,
"FileUtils",
"resource://gre/modules/FileUtils.jsm"
);
ChromeUtils.defineModuleGetter(
this,
"MailServices",
"resource:///modules/MailServices.jsm"
);
ChromeUtils.defineModuleGetter(
this,
"Services",
"resource://gre/modules/Services.jsm"
);
ChromeUtils.defineModuleGetter(
this,
"SimpleEnumerator",
"resource:///modules/AddrBookUtils.jsm"
);
ChromeUtils.defineModuleGetter(
this,
"fixIterator",
"resource:///modules/iteratorUtils.jsm"
);
ChromeUtils.defineModuleGetter(
this,
"AddrBookCard",
"resource:///modules/AddrBookCard.jsm"
);
ChromeUtils.defineModuleGetter(
this,
"AddrBookMailingList",
"resource:///modules/AddrBookMailingList.jsm"
);
ChromeUtils.defineModuleGetter(
this,
"newUID",
"resource:///modules/AddrBookUtils.jsm"
);
ChromeUtils.defineModuleGetter(
this,
"toXPCOMArray",
"resource:///modules/iteratorUtils.jsm"
);
/* This is where the address book manager creates an nsIAbDirectory. We want
* to do things differently depending on whether or not the directory is a
@ -22,8 +58,7 @@ ChromeUtils.defineModuleGetter(this, "toXPCOMArray", "resource:///modules/iterat
* directory and calling addressLists on it. This will make more sense and be
* a lot neater once we stop using one XPCOM interface for two jobs. */
function AddrBookDirectory() {
}
function AddrBookDirectory() {}
AddrBookDirectory.prototype = {
QueryInterface: ChromeUtils.generateQI([Ci.nsIAbDirectory]),
classID: Components.ID("{e96ee804-0bd3-472f-81a6-8a9d65277ad3}"),
@ -37,7 +72,9 @@ AddrBookDirectory.prototype = {
uri = uri.substring(0, index);
}
if (/\/MailList\d+$/.test(uri)) {
let parent = MailServices.ab.getDirectory(uri.substring(0, uri.lastIndexOf("/")));
let parent = MailServices.ab.getDirectory(
uri.substring(0, uri.lastIndexOf("/"))
);
for (let list of parent.addressLists.enumerate()) {
list.QueryInterface(Ci.nsIAbDirectory);
if (list.URI == uri) {
@ -54,8 +91,14 @@ AddrBookDirectory.prototype = {
if (!this.dirPrefId) {
let filename = uri.substring("jsaddrbook://".length);
for (let child of Services.prefs.getChildList("ldap_2.servers.")) {
if (child.endsWith(".filename") && Services.prefs.getStringPref(child) == filename) {
this.dirPrefId = child.substring(0, child.length - ".filename".length);
if (
child.endsWith(".filename") &&
Services.prefs.getStringPref(child) == filename
) {
this.dirPrefId = child.substring(
0,
child.length - ".filename".length
);
break;
}
}
@ -113,13 +156,17 @@ var bookPrototype = {
if (connection.schemaVersion == 0) {
connection.executeSimpleSQL("PRAGMA journal_mode=WAL");
connection.executeSimpleSQL(
"CREATE TABLE cards (uid TEXT PRIMARY KEY, localId INTEGER)");
"CREATE TABLE cards (uid TEXT PRIMARY KEY, localId INTEGER)"
);
connection.executeSimpleSQL(
"CREATE TABLE properties (card TEXT, name TEXT, value TEXT)");
"CREATE TABLE properties (card TEXT, name TEXT, value TEXT)"
);
connection.executeSimpleSQL(
"CREATE TABLE lists (uid TEXT PRIMARY KEY, localId INTEGER, name TEXT, nickName TEXT, description TEXT)");
"CREATE TABLE lists (uid TEXT PRIMARY KEY, localId INTEGER, name TEXT, nickName TEXT, description TEXT)"
);
connection.executeSimpleSQL(
"CREATE TABLE list_cards (list TEXT, card TEXT, PRIMARY KEY(list, card))");
"CREATE TABLE list_cards (list TEXT, card TEXT, PRIMARY KEY(list, card))"
);
connection.schemaVersion = 1;
}
connections.set(file.path, connection);
@ -135,7 +182,8 @@ var bookPrototype = {
},
get _lists() {
let selectStatement = this._dbConnection.createStatement(
"SELECT uid, localId, name, nickName, description FROM lists");
"SELECT uid, localId, name, nickName, description FROM lists"
);
let results = new Map();
while (selectStatement.executeStep()) {
results.set(selectStatement.row.uid, {
@ -151,7 +199,8 @@ var bookPrototype = {
},
get _cards() {
let cardStatement = this._dbConnection.createStatement(
"SELECT uid, localId FROM cards");
"SELECT uid, localId FROM cards"
);
let results = new Map();
while (cardStatement.executeStep()) {
results.set(cardStatement.row.uid, {
@ -167,7 +216,8 @@ var bookPrototype = {
if (this._nextCardId === null) {
let value = 1;
let selectStatement = this._dbConnection.createStatement(
"SELECT MAX(localId) AS localId FROM cards");
"SELECT MAX(localId) AS localId FROM cards"
);
if (selectStatement.executeStep()) {
value = selectStatement.row.localId + 1;
}
@ -180,7 +230,8 @@ var bookPrototype = {
if (this._nextListId === null) {
let value = 1;
let selectStatement = this._dbConnection.createStatement(
"SELECT MAX(localId) AS localId FROM lists");
"SELECT MAX(localId) AS localId FROM lists"
);
if (selectStatement.executeStep()) {
value = selectStatement.row.localId + 1;
}
@ -200,7 +251,8 @@ var bookPrototype = {
_loadCardProperties(uid) {
let properties = new Map();
let propertyStatement = this._dbConnection.createStatement(
"SELECT name, value FROM properties WHERE card = :card");
"SELECT name, value FROM properties WHERE card = :card"
);
propertyStatement.params.card = uid;
while (propertyStatement.executeStep()) {
properties.set(propertyStatement.row.name, propertyStatement.row.value);
@ -211,11 +263,13 @@ var bookPrototype = {
_saveCardProperties(card) {
this._dbConnection.beginTransaction();
let deleteStatement = this._dbConnection.createStatement(
"DELETE FROM properties WHERE card = :card");
"DELETE FROM properties WHERE card = :card"
);
deleteStatement.params.card = card.UID;
deleteStatement.execute();
let insertStatement = this._dbConnection.createStatement(
"INSERT INTO properties VALUES (:card, :name, :value)");
"INSERT INTO properties VALUES (:card, :name, :value)"
);
for (let { name, value } of fixIterator(card.properties, Ci.nsIProperty)) {
if (value !== null && value !== undefined && value !== "") {
insertStatement.params.card = card.UID;
@ -232,7 +286,8 @@ var bookPrototype = {
_saveList(list) {
let replaceStatement = this._dbConnection.createStatement(
"REPLACE INTO lists (uid, localId, name, nickName, description) " +
"VALUES (:uid, :localId, :name, :nickName, :description)");
"VALUES (:uid, :localId, :name, :nickName, :description)"
);
replaceStatement.params.uid = list._uid;
replaceStatement.params.localId = list._localId;
replaceStatement.params.name = list._name;
@ -254,13 +309,15 @@ var bookPrototype = {
return false;
},
cardForEmailAddress(emailAddress) {
return this.getCardFromProperty("PrimaryEmail", emailAddress, false) ||
this.getCardFromProperty("SecondEmail", emailAddress, false);
return (
this.getCardFromProperty("PrimaryEmail", emailAddress, false) ||
this.getCardFromProperty("SecondEmail", emailAddress, false)
);
},
getCardFromProperty(property, value, caseSensitive) {
let sql = caseSensitive ?
"SELECT card FROM properties WHERE name = :name AND value = :value LIMIT 1" :
"SELECT card FROM properties WHERE name = :name AND LOWER(value) = LOWER(:value) LIMIT 1";
let sql = caseSensitive
? "SELECT card FROM properties WHERE name = :name AND value = :value LIMIT 1"
: "SELECT card FROM properties WHERE name = :name AND LOWER(value) = LOWER(:value) LIMIT 1";
let selectStatement = this._dbConnection.createStatement(sql);
selectStatement.params.name = property;
selectStatement.params.value = value;
@ -271,9 +328,9 @@ var bookPrototype = {
return null;
},
getCardsFromProperty(property, value, caseSensitive) {
let sql = caseSensitive ?
"SELECT card FROM properties WHERE name = :name AND value = :value" :
"SELECT card FROM properties WHERE name = :name AND LOWER(value) = LOWER(:value)";
let sql = caseSensitive
? "SELECT card FROM properties WHERE name = :name AND value = :value"
: "SELECT card FROM properties WHERE name = :name AND LOWER(value) = LOWER(:value)";
let selectStatement = this._dbConnection.createStatement(sql);
selectStatement.params.name = property;
selectStatement.params.value = value;
@ -330,28 +387,31 @@ var bookPrototype = {
get childNodes() {
let lists = Array.from(
this._lists.values(),
list => new AddrBookMailingList(list.uid,
this,
list.localId,
list.name,
list.nickName,
list.description).asDirectory
list =>
new AddrBookMailingList(
list.uid,
this,
list.localId,
list.name,
list.nickName,
list.description
).asDirectory
);
return new SimpleEnumerator(lists);
},
get childCards() {
let results = Array.from(
this._lists.values(),
list => new AddrBookMailingList(list.uid,
this,
list.localId,
list.name,
list.nickName,
list.description).asCard
).concat(Array.from(
this._cards.values(),
card => this._getCard(card))
);
list =>
new AddrBookMailingList(
list.uid,
this,
list.localId,
list.name,
list.nickName,
list.description
).asCard
).concat(Array.from(this._cards.values(), card => this._getCard(card)));
if (this._query) {
if (!this._processedQuery) {
@ -400,7 +460,7 @@ var bookPrototype = {
} else {
properties = this._loadCardProperties(card.UID);
}
let matches = (b) => {
let matches = b => {
if (typeof b == "string") {
let [name, condition, value] = b.split(",");
if (name == "IsMailList" && condition == "=") {
@ -432,7 +492,7 @@ var bookPrototype = {
case "c":
return cardValue.includes(value);
case "!c":
return !(cardValue.includes(value));
return !cardValue.includes(value);
case "~=":
case "regex":
default:
@ -465,12 +525,15 @@ var bookPrototype = {
get addressLists() {
let lists = Array.from(
this._lists.values(),
list => new AddrBookMailingList(list.uid,
this,
list.localId,
list.name,
list.nickName,
list.description).asDirectory
list =>
new AddrBookMailingList(
list.uid,
this,
list.localId,
list.name,
list.nickName,
list.description
).asDirectory
);
return toXPCOMArray(lists, Ci.nsIMutableArray);
},
@ -480,21 +543,25 @@ var bookPrototype = {
},
deleteDirectory(directory) {
let list = this._lists.get(directory.UID);
list = new AddrBookMailingList(list.uid,
this,
list.localId,
list.name,
list.nickName,
list.description);
list = new AddrBookMailingList(
list.uid,
this,
list.localId,
list.name,
list.nickName,
list.description
);
let deleteListStatement = this._dbConnection.createStatement(
"DELETE FROM lists WHERE uid = :uid");
"DELETE FROM lists WHERE uid = :uid"
);
deleteListStatement.params.uid = directory.UID;
deleteListStatement.execute();
deleteListStatement.finalize();
this._dbConnection.executeSimpleSQL(
"DELETE FROM list_cards WHERE list NOT IN (SELECT DISTINCT uid FROM lists)");
"DELETE FROM list_cards WHERE list NOT IN (SELECT DISTINCT uid FROM lists)"
);
MailServices.ab.notifyDirectoryItemDeleted(this, list.asCard);
MailServices.ab.notifyDirectoryItemDeleted(list.asDirectory, list.asCard);
MailServices.ab.notifyDirectoryDeleted(this, directory);
@ -543,9 +610,11 @@ var bookPrototype = {
}
let deleteCardStatement = this._dbConnection.createStatement(
"DELETE FROM cards WHERE uid = :uid");
"DELETE FROM cards WHERE uid = :uid"
);
let selectListCardStatement = this._dbConnection.createStatement(
"SELECT list FROM list_cards WHERE card = :card");
"SELECT list FROM list_cards WHERE card = :card"
);
for (let card of cards.enumerate(Ci.nsIAbCard)) {
deleteCardStatement.params.uid = card.UID;
deleteCardStatement.execute();
@ -554,13 +623,17 @@ var bookPrototype = {
selectListCardStatement.params.card = card.UID;
while (selectListCardStatement.executeStep()) {
let list = new AddrBookMailingList(selectListCardStatement.row.list, this);
let list = new AddrBookMailingList(
selectListCardStatement.row.list,
this
);
list.asDirectory.deleteCards(toXPCOMArray([card], Ci.nsIMutableArray));
}
}
this._dbConnection.executeSimpleSQL(
"DELETE FROM properties WHERE card NOT IN (SELECT DISTINCT uid FROM cards)");
"DELETE FROM properties WHERE card NOT IN (SELECT DISTINCT uid FROM cards)"
);
deleteCardStatement.finalize();
selectListCardStatement.finalize();
@ -569,10 +642,11 @@ var bookPrototype = {
let newCard = new AddrBookCard();
newCard.directoryId = this.uuid;
newCard.localId = this._getNextCardId().toString();
newCard._uid = (needToCopyCard || !card.UID) ? newUID() : card.UID;
newCard._uid = needToCopyCard || !card.UID ? newUID() : card.UID;
let insertStatement = this._dbConnection.createStatement(
"INSERT INTO cards (uid, localId) VALUES (:uid, :localId)");
"INSERT INTO cards (uid, localId) VALUES (:uid, :localId)"
);
insertStatement.params.uid = newCard.UID;
insertStatement.params.localId = newCard.localId;
insertStatement.execute();
@ -596,12 +670,14 @@ var bookPrototype = {
throw Cr.NS_ERROR_UNEXPECTED;
}
let newList = new AddrBookMailingList(newUID(),
this,
this._getNextListId(),
list.dirName || "",
list.listNickName || "",
list.description || "");
let newList = new AddrBookMailingList(
newUID(),
this,
this._getNextListId(),
list.dirName || "",
list.listNickName || "",
list.description || ""
);
this._saveList(newList);
let newListDirectory = newList.asDirectory;
@ -637,7 +713,8 @@ var bookPrototype = {
if (this._prefBranch.getPrefType(name) == Ci.nsIPrefBranch.PREF_INVALID) {
return defaultValue;
}
return this._prefBranch.getComplexValue(name, Ci.nsIPrefLocalizedString).value;
return this._prefBranch.getComplexValue(name, Ci.nsIPrefLocalizedString)
.value;
},
setIntValue(name, value) {
this._prefBranch.setIntPref(name, value);

Просмотреть файл

@ -4,9 +4,21 @@
this.EXPORTED_SYMBOLS = ["AddrBookFactory"];
ChromeUtils.defineModuleGetter(this, "FileUtils", "resource://gre/modules/FileUtils.jsm");
ChromeUtils.defineModuleGetter(this, "MailServices", "resource:///modules/MailServices.jsm");
ChromeUtils.defineModuleGetter(this, "closeConnectionTo", "resource:///modules/AddrBookDirectory.jsm");
ChromeUtils.defineModuleGetter(
this,
"FileUtils",
"resource://gre/modules/FileUtils.jsm"
);
ChromeUtils.defineModuleGetter(
this,
"MailServices",
"resource:///modules/MailServices.jsm"
);
ChromeUtils.defineModuleGetter(
this,
"closeConnectionTo",
"resource:///modules/AddrBookDirectory.jsm"
);
/**
* Address book factory. This looks like it should be a useful for keeping
@ -15,8 +27,7 @@ ChromeUtils.defineModuleGetter(this, "closeConnectionTo", "resource:///modules/A
*
* @implements {nsIAbDirFactory}
*/
function AddrBookFactory() {
}
function AddrBookFactory() {}
AddrBookFactory.prototype = {
QueryInterface: ChromeUtils.generateQI([Ci.nsIAbDirFactory]),
classID: Components.ID("{567c1f22-bae5-4bc9-9951-885678dc14a5}"),
@ -40,7 +51,7 @@ AddrBookFactory.prototype = {
throw Cr.NS_ERROR_NOT_AVAILABLE;
},
QueryInterface: ChromeUtils.generateQI([Ci.nsISimpleEnumerator]),
* [Symbol.iterator]() {
*[Symbol.iterator]() {
while (this.hasMoreElements()) {
yield this.getNext();
}

Просмотреть файл

@ -4,17 +4,40 @@
this.EXPORTED_SYMBOLS = ["AddrBookMailingList"];
ChromeUtils.defineModuleGetter(this, "MailServices", "resource:///modules/MailServices.jsm");
ChromeUtils.defineModuleGetter(this, "Services", "resource://gre/modules/Services.jsm");
ChromeUtils.defineModuleGetter(this, "SimpleEnumerator", "resource:///modules/AddrBookUtils.jsm");
ChromeUtils.defineModuleGetter(this, "toXPCOMArray", "resource:///modules/iteratorUtils.jsm");
ChromeUtils.defineModuleGetter(
this,
"MailServices",
"resource:///modules/MailServices.jsm"
);
ChromeUtils.defineModuleGetter(
this,
"Services",
"resource://gre/modules/Services.jsm"
);
ChromeUtils.defineModuleGetter(
this,
"SimpleEnumerator",
"resource:///modules/AddrBookUtils.jsm"
);
ChromeUtils.defineModuleGetter(
this,
"toXPCOMArray",
"resource:///modules/iteratorUtils.jsm"
);
/* Prototype for mailing lists. A mailing list can appear as nsIAbDirectory
* or as nsIAbCard. Here we keep all relevant information in the class itself
* and fulfill each interface on demand. This will make more sense and be
* a lot neater once we stop using two XPCOM interfaces for one job. */
function AddrBookMailingList(uid, parent, localId, name, nickName, description) {
function AddrBookMailingList(
uid,
parent,
localId,
name,
nickName,
description
) {
this._uid = uid;
this._parent = parent;
this._localId = localId;
@ -47,9 +70,19 @@ AddrBookMailingList.prototype = {
set dirName(value) {
let oldValue = self._name;
self._name = value;
MailServices.ab.notifyItemPropertyChanged(this, "DirName", oldValue, value);
MailServices.ab.notifyItemPropertyChanged(
this,
"DirName",
oldValue,
value
);
// Fired twice for compatibility.
MailServices.ab.notifyItemPropertyChanged(this, "DirName", oldValue, value);
MailServices.ab.notifyItemPropertyChanged(
this,
"DirName",
oldValue,
value
);
},
get listNickName() {
return self._nickName;
@ -71,11 +104,14 @@ AddrBookMailingList.prototype = {
},
get childCards() {
let selectStatement = self._parent._dbConnection.createStatement(
"SELECT card FROM list_cards WHERE list = :list ORDER BY oid");
"SELECT card FROM list_cards WHERE list = :list ORDER BY oid"
);
selectStatement.params.list = self._uid;
let results = [];
while (selectStatement.executeStep()) {
results.push(self._parent._getCard({ uid: selectStatement.row.card }));
results.push(
self._parent._getCard({ uid: selectStatement.row.card })
);
}
selectStatement.finalize();
return new SimpleEnumerator(results);
@ -85,11 +121,14 @@ AddrBookMailingList.prototype = {
},
get addressLists() {
let selectStatement = self._parent._dbConnection.createStatement(
"SELECT card FROM list_cards WHERE list = :list ORDER BY oid");
"SELECT card FROM list_cards WHERE list = :list ORDER BY oid"
);
selectStatement.params.list = self._uid;
let results = [];
while (selectStatement.executeStep()) {
results.push(self._parent._getCard({ uid: selectStatement.row.card }));
results.push(
self._parent._getCard({ uid: selectStatement.row.card })
);
}
selectStatement.finalize();
return toXPCOMArray(results, Ci.nsIMutableArray);
@ -100,7 +139,8 @@ AddrBookMailingList.prototype = {
return card;
}
let insertStatement = self._parent._dbConnection.createStatement(
"REPLACE INTO list_cards (list, card) VALUES (:list, :card)");
"REPLACE INTO list_cards (list, card) VALUES (:list, :card)"
);
insertStatement.params.list = self._uid;
insertStatement.params.card = card.UID;
insertStatement.execute();
@ -114,14 +154,19 @@ AddrBookMailingList.prototype = {
},
deleteCards(cards) {
let deleteCardStatement = self._parent._dbConnection.createStatement(
"DELETE FROM list_cards WHERE list = :list AND card = :card");
"DELETE FROM list_cards WHERE list = :list AND card = :card"
);
for (let card of cards.enumerate()) {
deleteCardStatement.params.list = self._uid;
deleteCardStatement.params.card = card.UID;
deleteCardStatement.execute();
deleteCardStatement.reset();
MailServices.ab.notifyDirectoryItemDeleted(this, card);
Services.obs.notifyObservers(card, "addrbook-list-member-removed", self._uid);
Services.obs.notifyObservers(
card,
"addrbook-list-member-removed",
self._uid
);
}
deleteCardStatement.finalize();
},
@ -130,7 +175,11 @@ AddrBookMailingList.prototype = {
card = this._parent.dropCard(card, true);
}
this.addCard(card);
Services.obs.notifyObservers(card, "addrbook-list-member-added", self._uid);
Services.obs.notifyObservers(
card,
"addrbook-list-member-added",
self._uid
);
},
editMailListToDatabase(listCard) {
self._parent._saveList(self);

Просмотреть файл

@ -4,10 +4,17 @@
this.EXPORTED_SYMBOLS = ["newUID", "SimpleEnumerator"];
ChromeUtils.defineModuleGetter(this, "XPCOMUtils", "resource://gre/modules/XPCOMUtils.jsm");
ChromeUtils.defineModuleGetter(
this,
"XPCOMUtils",
"resource://gre/modules/XPCOMUtils.jsm"
);
XPCOMUtils.defineLazyServiceGetter(
this, "uuidGenerator", "@mozilla.org/uuid-generator;1", "nsIUUIDGenerator"
this,
"uuidGenerator",
"@mozilla.org/uuid-generator;1",
"nsIUUIDGenerator"
);
function SimpleEnumerator(elements) {
@ -25,7 +32,7 @@ SimpleEnumerator.prototype = {
throw Cr.NS_ERROR_NOT_AVAILABLE;
},
QueryInterface: ChromeUtils.generateQI([Ci.nsISimpleEnumerator]),
* [Symbol.iterator]() {
*[Symbol.iterator]() {
while (this.hasMoreElements()) {
yield this.getNext();
}
@ -33,5 +40,8 @@ SimpleEnumerator.prototype = {
};
function newUID() {
return uuidGenerator.generateUUID().toString().substring(1, 37);
return uuidGenerator
.generateUUID()
.toString()
.substring(1, 37);
}

Просмотреть файл

@ -3,22 +3,22 @@
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
var {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm");
var {MailServices} = ChromeUtils.import("resource:///modules/MailServices.jsm");
var {
isLegalHostNameOrIP,
cleanUpHostName,
} = ChromeUtils.import("resource:///modules/hostnameUtils.jsm");
var {
fixIterator,
} = ChromeUtils.import("resource:///modules/iteratorUtils.jsm");
var { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm");
var { MailServices } = ChromeUtils.import(
"resource:///modules/MailServices.jsm"
);
var { isLegalHostNameOrIP, cleanUpHostName } = ChromeUtils.import(
"resource:///modules/hostnameUtils.jsm"
);
var { fixIterator } = ChromeUtils.import(
"resource:///modules/iteratorUtils.jsm"
);
var gCurrentDirectory = null;
var gReplicationBundle = null;
var gReplicationService =
Cc["@mozilla.org/addressbook/ldap-replication-service;1"].
getService(Ci.nsIAbLDAPReplicationService);
var gReplicationService = Cc[
"@mozilla.org/addressbook/ldap-replication-service;1"
].getService(Ci.nsIAbLDAPReplicationService);
var gReplicationCancelled = false;
var gProgressText;
var gProgressMeter;
@ -26,7 +26,7 @@ var gDownloadInProgress = false;
var kDefaultLDAPPort = 389;
var kDefaultSecureLDAPPort = 636;
var kLDAPDirectory = 0; // defined in nsDirPrefs.h
var kLDAPDirectory = 0; // defined in nsDirPrefs.h
document.addEventListener("dialogaccept", onAccept);
document.addEventListener("dialogcancel", onCancel);
@ -34,7 +34,9 @@ document.addEventListener("dialogcancel", onCancel);
var ldapOfflineObserver = {
observe(subject, topic, state) {
// sanity checks
if (topic != "network:offline-status-changed") return;
if (topic != "network:offline-status-changed") {
return;
}
setDownloadOfflineOnlineState(state == "offline");
},
};
@ -42,30 +44,43 @@ var ldapOfflineObserver = {
function Startup() {
gReplicationBundle = document.getElementById("bundle_replication");
document.getElementById("download").label =
gReplicationBundle.getString("downloadButton");
document.getElementById("download").accessKey =
gReplicationBundle.getString("downloadButton.accesskey");
document.getElementById("download").label = gReplicationBundle.getString(
"downloadButton"
);
document.getElementById("download").accessKey = gReplicationBundle.getString(
"downloadButton.accesskey"
);
if ("arguments" in window && window.arguments[0]) {
gCurrentDirectory = window.arguments[0].selectedDirectory;
try {
fillSettings();
} catch (ex) {
dump("pref-directory-add.js:Startup(): fillSettings() exception: "
+ ex + "\n");
dump(
"pref-directory-add.js:Startup(): fillSettings() exception: " +
ex +
"\n"
);
}
let oldListName = gCurrentDirectory.dirName;
document.title = gReplicationBundle.getFormattedString("directoryTitleEdit", [oldListName]);
document.title = gReplicationBundle.getFormattedString(
"directoryTitleEdit",
[oldListName]
);
// Only set up the download button for online/offline status toggling
// if the pref isn't locked to disable the button.
if (!Services.prefs.prefIsLocked(gCurrentDirectory.dirPrefId +
".disable_button_download")) {
if (
!Services.prefs.prefIsLocked(
gCurrentDirectory.dirPrefId + ".disable_button_download"
)
) {
// Now connect to the offline/online observer
Services.obs.addObserver(ldapOfflineObserver,
"network:offline-status-changed");
Services.obs.addObserver(
ldapOfflineObserver,
"network:offline-status-changed"
);
// Now set the initial offline/online state and update the state
setDownloadOfflineOnlineState(Services.io.offline);
@ -78,13 +93,18 @@ function Startup() {
}
function onUnload() {
if ("arguments" in window &&
window.arguments[0] &&
!Services.prefs.prefIsLocked(gCurrentDirectory.dirPrefId +
".disable_button_download")) {
if (
"arguments" in window &&
window.arguments[0] &&
!Services.prefs.prefIsLocked(
gCurrentDirectory.dirPrefId + ".disable_button_download"
)
) {
// Remove the observer that we put in on dialog startup
Services.obs.removeObserver(ldapOfflineObserver,
"network:offline-status-changed");
Services.obs.removeObserver(
ldapOfflineObserver,
"network:offline-status-changed"
);
}
}
@ -93,34 +113,45 @@ var progressListener = {
if (aStateFlags & Ci.nsIWebProgressListener.STATE_START) {
// start the spinning
gProgressMeter.removeAttribute("value");
gProgressText.value = gReplicationBundle.getString(aStatus ?
"replicationStarted" :
"changesStarted");
gProgressText.value = gReplicationBundle.getString(
aStatus ? "replicationStarted" : "changesStarted"
);
gDownloadInProgress = true;
document.getElementById("download").label =
gReplicationBundle.getString("cancelDownloadButton");
document.getElementById("download").accessKey =
gReplicationBundle.getString("cancelDownloadButton.accesskey");
document.getElementById("download").label = gReplicationBundle.getString(
"cancelDownloadButton"
);
document.getElementById(
"download"
).accessKey = gReplicationBundle.getString(
"cancelDownloadButton.accesskey"
);
}
if (aStateFlags & Ci.nsIWebProgressListener.STATE_STOP) {
EndDownload(aStatus);
}
},
onProgressChange(aWebProgress, aRequest, aCurSelfProgress, aMaxSelfProgress, aCurTotalProgress, aMaxTotalProgress) {
gProgressText.value = gReplicationBundle.getFormattedString("currentCount",
[aCurSelfProgress]);
onProgressChange(
aWebProgress,
aRequest,
aCurSelfProgress,
aMaxSelfProgress,
aCurTotalProgress,
aMaxTotalProgress
) {
gProgressText.value = gReplicationBundle.getFormattedString(
"currentCount",
[aCurSelfProgress]
);
},
onLocationChange(aWebProgress, aRequest, aLocation, aFlags) {
},
onStatusChange(aWebProgress, aRequest, aStatus, aMessage) {
},
onSecurityChange(aWebProgress, aRequest, state) {
},
onContentBlockingEvent(aWebProgress, aRequest, aEvent) {
},
QueryInterface: ChromeUtils.generateQI(["nsIWebProgressListener",
"nsISupportsWeakReference"]),
onLocationChange(aWebProgress, aRequest, aLocation, aFlags) {},
onStatusChange(aWebProgress, aRequest, aStatus, aMessage) {},
onSecurityChange(aWebProgress, aRequest, state) {},
onContentBlockingEvent(aWebProgress, aRequest, aEvent) {},
QueryInterface: ChromeUtils.generateQI([
"nsIWebProgressListener",
"nsISupportsWeakReference",
]),
};
function DownloadNow() {
@ -133,11 +164,14 @@ function DownloadNow() {
gReplicationCancelled = false;
try {
if (gCurrentDirectory instanceof Ci.nsIAbLDAPDirectory)
gReplicationService.startReplication(gCurrentDirectory,
progressListener);
else
if (gCurrentDirectory instanceof Ci.nsIAbLDAPDirectory) {
gReplicationService.startReplication(
gCurrentDirectory,
progressListener
);
} else {
EndDownload(false);
}
} catch (ex) {
EndDownload(false);
}
@ -154,10 +188,12 @@ function DownloadNow() {
}
function EndDownload(aStatus) {
document.getElementById("download").label =
gReplicationBundle.getString("downloadButton");
document.getElementById("download").accessKey =
gReplicationBundle.getString("downloadButton.accesskey");
document.getElementById("download").label = gReplicationBundle.getString(
"downloadButton"
);
document.getElementById("download").accessKey = gReplicationBundle.getString(
"downloadButton.accesskey"
);
// stop the spinning
gProgressMeter.value = 100;
@ -189,62 +225,80 @@ function fillSettings() {
var sub = document.getElementById("sub");
switch (ldapUrl.scope) {
case Ci.nsILDAPURL.SCOPE_ONELEVEL:
sub.radioGroup.selectedItem = document.getElementById("one");
break;
default:
sub.radioGroup.selectedItem = sub;
break;
case Ci.nsILDAPURL.SCOPE_ONELEVEL:
sub.radioGroup.selectedItem = document.getElementById("one");
break;
default:
sub.radioGroup.selectedItem = sub;
break;
}
var sasl = document.getElementById("saslMechanism");
switch (gCurrentDirectory.saslMechanism) {
case "GSSAPI":
sasl.selectedItem = document.getElementById("GSSAPI");
break;
default:
sasl.selectedItem = document.getElementById("Simple");
break;
case "GSSAPI":
sasl.selectedItem = document.getElementById("GSSAPI");
break;
default:
sasl.selectedItem = document.getElementById("Simple");
break;
}
var secure = ldapUrl.options & ldapUrl.OPT_SECURE;
if (secure)
if (secure) {
document.getElementById("secure").setAttribute("checked", "true");
}
if (ldapUrl.port == -1)
document.getElementById("port").value =
(secure ? kDefaultSecureLDAPPort : kDefaultLDAPPort);
else
if (ldapUrl.port == -1) {
document.getElementById("port").value = secure
? kDefaultSecureLDAPPort
: kDefaultLDAPPort;
} else {
document.getElementById("port").value = ldapUrl.port;
}
}
// check if any of the preferences for this server are locked.
// If they are locked disable them
DisableUriFields(gCurrentDirectory.dirPrefId + ".uri");
DisableElementIfPrefIsLocked(gCurrentDirectory.dirPrefId + ".description", "description");
DisableElementIfPrefIsLocked(gCurrentDirectory.dirPrefId + ".disable_button_download", "download");
DisableElementIfPrefIsLocked(gCurrentDirectory.dirPrefId + ".maxHits", "results");
DisableElementIfPrefIsLocked(gCurrentDirectory.dirPrefId + ".auth.dn", "login");
DisableElementIfPrefIsLocked(
gCurrentDirectory.dirPrefId + ".description",
"description"
);
DisableElementIfPrefIsLocked(
gCurrentDirectory.dirPrefId + ".disable_button_download",
"download"
);
DisableElementIfPrefIsLocked(
gCurrentDirectory.dirPrefId + ".maxHits",
"results"
);
DisableElementIfPrefIsLocked(
gCurrentDirectory.dirPrefId + ".auth.dn",
"login"
);
}
function DisableElementIfPrefIsLocked(aPrefName, aElementId) {
if (Services.prefs.prefIsLocked(aPrefName))
if (Services.prefs.prefIsLocked(aPrefName)) {
document.getElementById(aElementId).setAttribute("disabled", true);
}
}
// disables all the text fields corresponding to the .uri pref.
function DisableUriFields(aPrefName) {
if (Services.prefs.prefIsLocked(aPrefName)) {
let lockedElements = document.querySelectorAll('[disableiflocked="true"]');
for (let i = 0; i < lockedElements.length; i++)
for (let i = 0; i < lockedElements.length; i++) {
lockedElements[i].setAttribute("disabled", "true");
}
}
}
function onSecure() {
document.getElementById("port").value =
document.getElementById("secure").checked ? kDefaultSecureLDAPPort :
kDefaultLDAPPort;
document.getElementById("port").value = document.getElementById("secure")
.checked
? kDefaultSecureLDAPPort
: kDefaultLDAPPort;
}
function fillDefaultSettings() {
@ -255,16 +309,19 @@ function fillDefaultSettings() {
// Disable the download button and add some text indicating why.
document.getElementById("download").disabled = true;
document.getElementById("downloadWarningMsg").hidden = false;
document.getElementById("downloadWarningMsg").textContent = document.
getElementById("bundle_addressBook").
getString("abReplicationSaveSettings");
document.getElementById(
"downloadWarningMsg"
).textContent = document
.getElementById("bundle_addressBook")
.getString("abReplicationSaveSettings");
}
function hasCharacters(number) {
var re = /[0-9]/g;
var num = number.match(re);
if (num && (num.length == number.length))
if (num && num.length == number.length) {
return false;
}
return true;
}
@ -281,10 +338,14 @@ function onAccept(event) {
let findDupeName = function(newName) {
// Do not allow an already existing name.
for (let ab of fixIterator(MailServices.ab.directories,
Ci.nsIAbDirectory)) {
if ((ab.dirName.toLowerCase() == newName.toLowerCase()) &&
(!gCurrentDirectory || (ab.URI != gCurrentDirectory.URI))) {
for (let ab of fixIterator(
MailServices.ab.directories,
Ci.nsIAbDirectory
)) {
if (
ab.dirName.toLowerCase() == newName.toLowerCase() &&
(!gCurrentDirectory || ab.URI != gCurrentDirectory.URI)
) {
return ab.dirName;
}
}
@ -307,24 +368,25 @@ function onAccept(event) {
if (!errorValue) {
// XXX Due to the LDAP c-sdk pass a dummy url to the IO service, then
// update the parts (bug 473351).
let ldapUrl = Services.io.newURI(
(secure.checked ? "ldaps://" : "ldap://") + "localhost/dc=???")
let ldapUrl = Services.io
.newURI((secure.checked ? "ldaps://" : "ldap://") + "localhost/dc=???")
.QueryInterface(Ci.nsILDAPURL);
let newPort = port;
if (!port) {
port = secure.checked ? kDefaultSecureLDAPPort : kDefaultLDAPPort;
}
ldapUrl = ldapUrl.mutate()
.setHost(hostname)
.setPort(newPort)
.finalize()
.QueryInterface(Ci.nsILDAPURL);
ldapUrl = ldapUrl
.mutate()
.setHost(hostname)
.setPort(newPort)
.finalize()
.QueryInterface(Ci.nsILDAPURL);
ldapUrl.dn = document.getElementById("basedn").value;
ldapUrl.scope = document.getElementById("one").selected ?
Ci.nsILDAPURL.SCOPE_ONELEVEL :
Ci.nsILDAPURL.SCOPE_SUBTREE;
ldapUrl.scope = document.getElementById("one").selected
? Ci.nsILDAPURL.SCOPE_ONELEVEL
: Ci.nsILDAPURL.SCOPE_SUBTREE;
ldapUrl.filter = document.getElementById("search").value;
if (document.getElementById("GSSAPI").selected) {
@ -336,18 +398,22 @@ function onAccept(event) {
gCurrentDirectory.dirName = description;
gCurrentDirectory.lDAPURL = ldapUrl.QueryInterface(Ci.nsILDAPURL);
window.opener.gNewServerString = gCurrentDirectory.dirPrefId;
} else { // adding a new directory
window.opener.gNewServerString =
MailServices.ab.newAddressBook(description, ldapUrl.spec, kLDAPDirectory);
} else {
// adding a new directory
window.opener.gNewServerString = MailServices.ab.newAddressBook(
description,
ldapUrl.spec,
kLDAPDirectory
);
}
// XXX This is really annoying - both new/modify Address Book don't
// give us back the new directory we just created - so go find it from
// rdf so we can set a few final things up on it.
var targetURI = "moz-abldapdirectory://" + window.opener.gNewServerString;
var theDirectory =
MailServices.ab.getDirectory(targetURI)
.QueryInterface(Ci.nsIAbLDAPDirectory);
var theDirectory = MailServices.ab
.getDirectory(targetURI)
.QueryInterface(Ci.nsIAbLDAPDirectory);
theDirectory.maxHits = results;
theDirectory.authDn = document.getElementById("login").value;
@ -361,17 +427,22 @@ function onAccept(event) {
let addressBookBundle = document.getElementById("bundle_addressBook");
let errorText;
if (errorArg)
errorText = addressBookBundle.getFormattedString(errorValue, [errorArg]);
else
if (errorArg) {
errorText = addressBookBundle.getFormattedString(errorValue, [
errorArg,
]);
} else {
errorText = addressBookBundle.getString(errorValue);
}
Services.prompt.alert(window, document.title, errorText);
event.preventDefault();
return;
}
} catch (outer) {
Cu.reportError("Internal error in pref-directory-add.js:onAccept() " + outer);
Cu.reportError(
"Internal error in pref-directory-add.js:onAccept() " + outer
);
}
}
@ -384,9 +455,11 @@ function onCancel() {
function setDownloadOfflineOnlineState(isOffline) {
if (isOffline) {
// Disable the download button and add some text indicating why.
document.getElementById("downloadWarningMsg").textContent = document.
getElementById("bundle_addressBook").
getString("abReplicationOfflineWarning");
document.getElementById(
"downloadWarningMsg"
).textContent = document
.getElementById("bundle_addressBook")
.getString("abReplicationOfflineWarning");
}
document.getElementById("downloadWarningMsg").hidden = !isOffline;
document.getElementById("download").disabled = isOffline;

Просмотреть файл

@ -5,8 +5,10 @@
/* import-globals-from ../../../../mail/components/addrbook/content/abCommon.js */
var {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm");
var {MailServices} = ChromeUtils.import("resource:///modules/MailServices.jsm");
var { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm");
var { MailServices } = ChromeUtils.import(
"resource:///modules/MailServices.jsm"
);
// Listener to refresh the list items if something changes. In all these
// cases we just rebuild the list as it is easier than searching/adding in the
@ -34,18 +36,21 @@ function onInitEditDirectories() {
gAddressBookBundle = document.getElementById("bundle_addressBook");
// If the pref is locked disable the "Add" button
if (Services.prefs.prefIsLocked("ldap_2.disable_button_add"))
if (Services.prefs.prefIsLocked("ldap_2.disable_button_add")) {
document.getElementById("addButton").setAttribute("disabled", true);
}
// Fill out the directory list
fillDirectoryList();
const nsIAbListener = Ci.nsIAbListener;
// Add a listener so we can update correctly if the list should change
MailServices.ab.addAddressBookListener(gAddressBookAbListener,
nsIAbListener.itemAdded |
nsIAbListener.directoryRemoved |
nsIAbListener.itemChanged);
MailServices.ab.addAddressBookListener(
gAddressBookAbListener,
nsIAbListener.itemAdded |
nsIAbListener.directoryRemoved |
nsIAbListener.itemChanged
);
}
function onUninitEditDirectories() {
@ -56,19 +61,23 @@ function fillDirectoryList() {
var abList = document.getElementById("directoriesList");
// Empty out anything in the list
while (abList.hasChildNodes())
while (abList.hasChildNodes()) {
abList.lastChild.remove();
}
// Init the address book list
let directories = MailServices.ab.directories;
let holdingArray = [];
while (directories && directories.hasMoreElements()) {
let ab = directories.getNext();
if (ab instanceof Ci.nsIAbDirectory && ab.isRemote)
if (ab instanceof Ci.nsIAbDirectory && ab.isRemote) {
holdingArray.push(ab);
}
}
holdingArray.sort(function(a, b) { return a.dirName.localeCompare(b.dirName); });
holdingArray.sort(function(a, b) {
return a.dirName.localeCompare(b.dirName);
});
holdingArray.forEach(function(ab) {
let item = document.createXULElement("richlistitem");
@ -92,11 +101,15 @@ function selectDirectory() {
// If the disable delete button pref for the selected directory is set,
// disable the delete button for that directory.
let ab = MailServices.ab.getDirectory(abList.value);
let disable = Services.prefs.getBoolPref(ab.dirPrefId + ".disable_delete", false);
if (disable)
let disable = Services.prefs.getBoolPref(
ab.dirPrefId + ".disable_delete",
false
);
if (disable) {
removeButton.setAttribute("disabled", true);
else
} else {
removeButton.removeAttribute("disabled");
}
} else {
editButton.setAttribute("disabled", true);
removeButton.setAttribute("disabled", true);
@ -105,8 +118,9 @@ function selectDirectory() {
function dblClickDirectory(event) {
// We only care about left click events.
if (event.button != 0)
if (event.button != 0) {
return;
}
editDirectory();
}
@ -118,15 +132,19 @@ function editDirectory() {
let abURI = abList.value;
let ab = MailServices.ab.getDirectory(abURI);
window.openDialog(ab.propertiesChromeURI, "editDirectory",
"chrome,modal=yes,resizable=no",
{ selectedDirectory: ab });
window.openDialog(
ab.propertiesChromeURI,
"editDirectory",
"chrome,modal=yes,resizable=no",
{ selectedDirectory: ab }
);
}
}
function removeDirectory() {
var abList = document.getElementById("directoriesList");
if (abList && abList.selectedItem)
if (abList && abList.selectedItem) {
AbDeleteDirectory(abList.value);
}
}

Просмотреть файл

@ -2,15 +2,18 @@
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
var {MailServices} = ChromeUtils.import("resource:///modules/MailServices.jsm");
var {XPCOMUtils} = ChromeUtils.import("resource://gre/modules/XPCOMUtils.jsm");
var { MailServices } = ChromeUtils.import(
"resource:///modules/MailServices.jsm"
);
var { XPCOMUtils } = ChromeUtils.import(
"resource://gre/modules/XPCOMUtils.jsm"
);
function nsAbAutoCompleteMyDomain() {}
nsAbAutoCompleteMyDomain.prototype = {
classID: Components.ID("{5b259db2-e451-4de9-8a6f-cfba91402973}"),
QueryInterface: ChromeUtils.generateQI([
Ci.nsIAutoCompleteSearch]),
QueryInterface: ChromeUtils.generateQI([Ci.nsIAutoCompleteSearch]),
cachedIdKey: "",
cachedIdentity: null,
@ -19,17 +22,20 @@ nsAbAutoCompleteMyDomain.prototype = {
startSearch(aString, aSearchParam, aResult, aListener) {
let params = aSearchParam ? JSON.parse(aSearchParam) : {};
let applicable = ("type" in params) && this.applicableHeaders.has(params.type);
let applicable =
"type" in params && this.applicableHeaders.has(params.type);
const ACR = Ci.nsIAutoCompleteResult;
var address = null;
if (applicable && aString && !aString.includes(",")) {
if (("idKey" in params) && (params.idKey != this.cachedIdKey)) {
if ("idKey" in params && params.idKey != this.cachedIdKey) {
this.cachedIdentity = MailServices.accounts.getIdentity(params.idKey);
this.cachedIdKey = params.idKey;
}
if (this.cachedIdentity.autocompleteToMyDomain)
address = aString.includes("@") ? aString :
this.cachedIdentity.email.replace(/[^@]*/, aString);
if (this.cachedIdentity.autocompleteToMyDomain) {
address = aString.includes("@")
? aString
: this.cachedIdentity.email.replace(/[^@]*/, aString);
}
}
var result = {
@ -38,11 +44,21 @@ nsAbAutoCompleteMyDomain.prototype = {
defaultIndex: -1,
errorDescription: null,
matchCount: address ? 1 : 0,
getValueAt() { return address; },
getLabelAt() { return this.getValueAt(); },
getCommentAt() { return null; },
getStyleAt() { return "default-match"; },
getImageAt() { return null; },
getValueAt() {
return address;
},
getLabelAt() {
return this.getValueAt();
},
getCommentAt() {
return null;
},
getStyleAt() {
return "default-match";
},
getImageAt() {
return null;
},
getFinalCompleteValueAt(aIndex) {
return this.getValueAt(aIndex);
},

Просмотреть файл

@ -2,15 +2,19 @@
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
var {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm");
var {MailServices} = ChromeUtils.import("resource:///modules/MailServices.jsm");
var { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm");
var { MailServices } = ChromeUtils.import(
"resource:///modules/MailServices.jsm"
);
var {
getSearchTokens,
getModelQuery,
modelQueryHasUserValue,
generateQueryURI,
} = ChromeUtils.import("resource:///modules/ABQueryUtils.jsm");
var {XPCOMUtils} = ChromeUtils.import("resource://gre/modules/XPCOMUtils.jsm");
var { XPCOMUtils } = ChromeUtils.import(
"resource://gre/modules/XPCOMUtils.jsm"
);
var ACR = Ci.nsIAutoCompleteResult;
var nsIAbAutoCompleteResult = Ci.nsIAbAutoCompleteResult;
@ -20,12 +24,14 @@ function nsAbAutoCompleteResult(aSearchString) {
// all instances
this._searchResults = []; // final results
this.searchString = aSearchString;
this._collectedValues = new Map(); // temporary unsorted results
this._collectedValues = new Map(); // temporary unsorted results
// Get model query from pref; this will return mail.addr_book.autocompletequery.format.phonetic
// if mail.addr_book.show_phonetic_fields == true
this.modelQuery = getModelQuery("mail.addr_book.autocompletequery.format");
// check if the currently active model query has been modified by user
this._modelQueryHasUserValue = modelQueryHasUserValue("mail.addr_book.autocompletequery.format");
this._modelQueryHasUserValue = modelQueryHasUserValue(
"mail.addr_book.autocompletequery.format"
);
}
nsAbAutoCompleteResult.prototype = {
@ -67,8 +73,7 @@ nsAbAutoCompleteResult.prototype = {
return this.getValueAt(aIndex);
},
removeValueAt(aRowIndex, aRemoveFromDB) {
},
removeValueAt(aRowIndex, aRemoveFromDB) {},
// nsIAbAutoCompleteResult
@ -119,8 +124,9 @@ nsAbAutoCompleteSearch.prototype = {
popularityIndex = parseInt(popularityValue, 16);
// If its still NaN, just give up, we shouldn't ever get here.
if (isNaN(popularityIndex))
if (isNaN(popularityIndex)) {
popularityIndex = 0;
}
// Now store this change so that we're not changing it each time around.
if (!aDirectory.readOnly) {
@ -152,28 +158,35 @@ nsAbAutoCompleteSearch.prototype = {
// is the nick name for the card or at least in the beginning of it.
let nick = aCard.getProperty("NickName", "").toLocaleLowerCase();
aSearchString = aSearchString.toLocaleLowerCase();
if (nick == aSearchString)
if (nick == aSearchString) {
return BEST + 1;
if (nick.indexOf(aSearchString) == 0)
}
if (nick.indexOf(aSearchString) == 0) {
return BEST;
}
// We'll do this case-insensitively and ignore the domain.
let atIdx = aAddress.lastIndexOf("@");
if (atIdx != -1) // mail lists don't have an @
if (atIdx != -1) {
// mail lists don't have an @
aAddress = aAddress.substr(0, atIdx);
}
let idx = aAddress.indexOf(aSearchString);
if (idx == 0)
if (idx == 0) {
return BEST;
if (idx == -1)
}
if (idx == -1) {
return 0;
}
// We want to treat firstname, lastname and word boundary(ish) parts of
// the email address the same. E.g. for "John Doe (:xx) <jd.who@example.com>"
// all of these should score the same: "John", "Doe", "xx",
// ":xx", "jd", "who".
let prevCh = aAddress.charAt(idx - 1);
if (/[ :."'(\-_<&]/.test(prevCh))
if (/[ :."'(\-_<&]/.test(prevCh)) {
return BEST;
}
// The match was inside a word -> we don't care about the position.
return 0;
@ -191,9 +204,12 @@ nsAbAutoCompleteSearch.prototype = {
_searchCards(searchQuery, directory, result) {
let childCards;
try {
childCards = this._abManager.getDirectory(directory.URI + searchQuery).childCards;
childCards = this._abManager.getDirectory(directory.URI + searchQuery)
.childCards;
} catch (e) {
Cu.reportError("Error running addressbook query '" + searchQuery + "': " + e);
Cu.reportError(
"Error running addressbook query '" + searchQuery + "': " + e
);
return;
}
@ -209,12 +225,28 @@ nsAbAutoCompleteSearch.prototype = {
this._addToResult(commentColumn, directory, card, "", true, result);
} else {
let email = card.primaryEmail;
if (email)
this._addToResult(commentColumn, directory, card, email, true, result);
if (email) {
this._addToResult(
commentColumn,
directory,
card,
email,
true,
result
);
}
email = card.getProperty("SecondEmail", "");
if (email)
this._addToResult(commentColumn, directory, card, email, false, result);
if (email) {
this._addToResult(
commentColumn,
directory,
card,
email,
false,
result
);
}
}
}
}
@ -241,17 +273,22 @@ nsAbAutoCompleteSearch.prototype = {
// but for now we hard-code the default value equivalent of the pref here
// or else bail out before and reconstruct the full c++ query if the pref
// has been customized (modelQueryHasUserValue), so that we won't get here.
let cumulativeFieldText = aCard.displayName + " " +
aCard.firstName + " " +
aCard.lastName + " " +
aEmailToUse + " " +
aCard.getProperty("NickName", "");
if (aCard.isMailList)
let cumulativeFieldText =
aCard.displayName +
" " +
aCard.firstName +
" " +
aCard.lastName +
" " +
aEmailToUse +
" " +
aCard.getProperty("NickName", "");
if (aCard.isMailList) {
cumulativeFieldText += " " + aCard.getProperty("Notes", "");
}
cumulativeFieldText = cumulativeFieldText.toLocaleLowerCase();
return aSearchWords.every(String.prototype.includes,
cumulativeFieldText);
return aSearchWords.every(String.prototype.includes, cumulativeFieldText);
},
/**
@ -268,8 +305,9 @@ nsAbAutoCompleteSearch.prototype = {
*/
_checkDuplicate(directory, card, lcEmailAddress, currentResults) {
let existingResult = currentResults._collectedValues.get(lcEmailAddress);
if (!existingResult)
if (!existingResult) {
return false;
}
let popIndex = this._getPopularityIndex(directory, card);
// It's a duplicate, is the new one more popular?
@ -298,20 +336,32 @@ nsAbAutoCompleteSearch.prototype = {
* it is the case. For mailing lists set it to true.
* @param result The result to add the new entry to.
*/
_addToResult(commentColumn, directory, card, emailToUse, isPrimaryEmail, result) {
let mbox = this._parser.makeMailboxObject(card.displayName,
card.isMailList ? card.getProperty("Notes", "") || card.displayName :
emailToUse);
if (!mbox.email)
_addToResult(
commentColumn,
directory,
card,
emailToUse,
isPrimaryEmail,
result
) {
let mbox = this._parser.makeMailboxObject(
card.displayName,
card.isMailList
? card.getProperty("Notes", "") || card.displayName
: emailToUse
);
if (!mbox.email) {
return;
}
let emailAddress = mbox.toString();
let lcEmailAddress = emailAddress.toLocaleLowerCase();
// If it is a duplicate, then just return and don't add it. The
// _checkDuplicate function deals with it all for us.
if (this._checkDuplicate(directory, card, lcEmailAddress, result))
if (this._checkDuplicate(directory, card, lcEmailAddress, result)) {
return;
}
result._collectedValues.set(lcEmailAddress, {
value: emailAddress,
@ -337,7 +387,7 @@ nsAbAutoCompleteSearch.prototype = {
startSearch(aSearchString, aSearchParam, aPreviousResult, aListener) {
let params = aSearchParam ? JSON.parse(aSearchParam) : {};
var result = new nsAbAutoCompleteResult(aSearchString);
if (("type" in params) && !this.applicableHeaders.has(params.type)) {
if ("type" in params && !this.applicableHeaders.has(params.type)) {
result.searchResult = ACR.RESULT_IGNORED;
aListener.onSearchResult(this, result);
return;
@ -362,13 +412,18 @@ nsAbAutoCompleteSearch.prototype = {
let searchWords = getSearchTokens(fullString);
// Find out about the comment column
this._commentColumn = Services.prefs.getIntPref("mail.autoComplete.commentColumn", 0);
this._commentColumn = Services.prefs.getIntPref(
"mail.autoComplete.commentColumn",
0
);
if (aPreviousResult instanceof nsIAbAutoCompleteResult &&
aSearchString.startsWith(aPreviousResult.searchString) &&
aPreviousResult.searchResult == ACR.RESULT_SUCCESS &&
!result._modelQueryHasUserValue &&
result.modelQuery == aPreviousResult.modelQuery) {
if (
aPreviousResult instanceof nsIAbAutoCompleteResult &&
aSearchString.startsWith(aPreviousResult.searchString) &&
aPreviousResult.searchResult == ACR.RESULT_SUCCESS &&
!result._modelQueryHasUserValue &&
result.modelQuery == aPreviousResult.modelQuery
) {
// We have successful previous matches, and model query has not changed since
// previous search, therefore just iterate through the list of previous result
// entries and reduce as appropriate (via _checkEntry function).
@ -389,12 +444,14 @@ nsAbAutoCompleteSearch.prototype = {
value: aPreviousResult.getValueAt(i),
comment: aPreviousResult.getCommentAt(i),
card,
isPrimaryEmail: (card.primaryEmail == email),
isPrimaryEmail: card.primaryEmail == email,
emailToUse: email,
popularity: parseInt(card.getProperty("PopularityIndex", "0")),
score: this._getScore(card,
score: this._getScore(
card,
aPreviousResult.getValueAt(i).toLocaleLowerCase(),
fullString),
fullString
),
});
}
}
@ -420,8 +477,10 @@ nsAbAutoCompleteSearch.prototype = {
// just going to find duplicates.
while (allABs.hasMoreElements()) {
let dir = allABs.getNext();
if (dir instanceof Ci.nsIAbDirectory &&
dir.useForAutocomplete(("idKey" in params) ? params.idKey : null)) {
if (
dir instanceof Ci.nsIAbDirectory &&
dir.useForAutocomplete("idKey" in params ? params.idKey : null)
) {
this._searchCards(searchQuery, dir, result);
}
}
@ -435,10 +494,12 @@ nsAbAutoCompleteSearch.prototype = {
// Order by 1) descending score, then 2) descending popularity,
// then 3) primary email before secondary for the same card, then
// 4) by emails sorted alphabetically.
return (b.score - a.score) ||
(b.popularity - a.popularity) ||
((a.card == b.card && a.isPrimaryEmail) ? -1 : 0) ||
a.value.localeCompare(b.value);
return (
b.score - a.score ||
b.popularity - a.popularity ||
(a.card == b.card && a.isPrimaryEmail ? -1 : 0) ||
a.value.localeCompare(b.value)
);
});
if (result.matchCount) {
@ -449,8 +510,7 @@ nsAbAutoCompleteSearch.prototype = {
aListener.onSearchResult(this, result);
},
stopSearch() {
},
stopSearch() {},
// nsISupports

Просмотреть файл

@ -2,13 +2,17 @@
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
var {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm");
var {XPCOMUtils} = ChromeUtils.import("resource://gre/modules/XPCOMUtils.jsm");
var { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm");
var { XPCOMUtils } = ChromeUtils.import(
"resource://gre/modules/XPCOMUtils.jsm"
);
var NS_ABLDAPATTRIBUTEMAP_CID = Components.ID(
"{127b341a-bdda-4270-85e1-edff569a9b85}");
"{127b341a-bdda-4270-85e1-edff569a9b85}"
);
var NS_ABLDAPATTRIBUTEMAPSERVICE_CID = Components.ID(
"{4ed7d5e1-8800-40da-9e78-c4f509d7ac5e}");
"{4ed7d5e1-8800-40da-9e78-c4f509d7ac5e}"
);
function nsAbLDAPAttributeMap() {
this.mPropertyMap = {};
@ -131,7 +135,9 @@ nsAbLDAPAttributeMap.prototype = {
var msgAttrs = aMessage.getAttributes(msgAttrCount);
// downcase the array for comparison
function toLower(a) { return a.toLowerCase(); }
function toLower(a) {
return a.toLowerCase();
}
msgAttrs = msgAttrs.map(toLower);
// deal with each addressbook property
@ -147,8 +153,9 @@ nsAbLDAPAttributeMap.prototype = {
// strip out the optional label from the labeledURI
if (attr == "labeleduri" && values[0]) {
var index = values[0].indexOf(" ");
if (index != -1)
if (index != -1) {
values[0] = values[0].substring(0, index);
}
}
aCard.setProperty(prop, values[0]);
@ -191,11 +198,9 @@ nsAbLDAPAttributeMap.prototype = {
QueryInterface: ChromeUtils.generateQI([Ci.nsIAbLDAPAttributeMap]),
};
function nsAbLDAPAttributeMapService() {
}
function nsAbLDAPAttributeMapService() {}
nsAbLDAPAttributeMapService.prototype = {
classID: NS_ABLDAPATTRIBUTEMAPSERVICE_CID,
mAttrMaps: {},
@ -221,5 +226,7 @@ nsAbLDAPAttributeMapService.prototype = {
QueryInterface: ChromeUtils.generateQI([Ci.nsIAbLDAPAttributeMapService]),
};
var NSGetFactory = XPCOMUtils.generateNSGetFactory([nsAbLDAPAttributeMap, nsAbLDAPAttributeMapService]);
var NSGetFactory = XPCOMUtils.generateNSGetFactory([
nsAbLDAPAttributeMap,
nsAbLDAPAttributeMapService,
]);

Просмотреть файл

@ -3,14 +3,17 @@
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
var {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm");
var {MailServices} = ChromeUtils.import("resource:///modules/MailServices.jsm");
var {XPCOMUtils} = ChromeUtils.import("resource://gre/modules/XPCOMUtils.jsm");
var { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm");
var { MailServices } = ChromeUtils.import(
"resource:///modules/MailServices.jsm"
);
var { XPCOMUtils } = ChromeUtils.import(
"resource://gre/modules/XPCOMUtils.jsm"
);
var ACR = Ci.nsIAutoCompleteResult;
var nsIAbAutoCompleteResult = Ci.nsIAbAutoCompleteResult;
var nsIAbDirectoryQueryResultListener =
Ci.nsIAbDirectoryQueryResultListener;
var nsIAbDirectoryQueryResultListener = Ci.nsIAbDirectoryQueryResultListener;
// nsAbLDAPAutoCompleteResult
// Derived from nsIAbAutoCompleteResult, provides a LDAP specific result
@ -51,8 +54,9 @@ nsAbLDAPAutoCompleteResult.prototype = {
},
getStyleAt(aIndex) {
return this.searchResult == ACR.RESULT_FAILURE ? "remote-err" :
"remote-abook";
return this.searchResult == ACR.RESULT_FAILURE
? "remote-err"
: "remote-abook";
},
getImageAt(aIndex) {
@ -63,8 +67,7 @@ nsAbLDAPAutoCompleteResult.prototype = {
return this.getValueAt(aIndex);
},
removeValueAt(aRowIndex, aRemoveFromDB) {
},
removeValueAt(aRowIndex, aRemoveFromDB) {},
// nsIAbAutoCompleteResult
@ -79,8 +82,7 @@ nsAbLDAPAutoCompleteResult.prototype = {
function nsAbLDAPAutoCompleteSearch() {
Services.obs.addObserver(this, "quit-application");
this._timer = Cc["@mozilla.org/timer;1"]
.createInstance(Ci.nsITimer);
this._timer = Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer);
}
nsAbLDAPAutoCompleteSearch.prototype = {
@ -118,26 +120,34 @@ nsAbLDAPAutoCompleteSearch.prototype = {
},
_addToResult(card) {
let mbox = this._parser.makeMailboxObject(card.displayName,
card.isMailList ? card.getProperty("Notes", "") || card.displayName :
card.primaryEmail);
if (!mbox.email)
let mbox = this._parser.makeMailboxObject(
card.displayName,
card.isMailList
? card.getProperty("Notes", "") || card.displayName
: card.primaryEmail
);
if (!mbox.email) {
return;
}
let emailAddress = mbox.toString();
// If it is a duplicate, then just return and don't add it. The
// _checkDuplicate function deals with it all for us.
if (this._checkDuplicate(card, emailAddress))
if (this._checkDuplicate(card, emailAddress)) {
return;
}
// Find out where to insert the card.
var insertPosition = 0;
// Next sort on full address
while (insertPosition < this._result._searchResults.length &&
emailAddress > this._result._searchResults[insertPosition].value)
while (
insertPosition < this._result._searchResults.length &&
emailAddress > this._result._searchResults[insertPosition].value
) {
++insertPosition;
}
this._result._searchResults.splice(insertPosition, 0, {
value: emailAddress,
@ -167,7 +177,8 @@ nsAbLDAPAutoCompleteSearch.prototype = {
startSearch(aSearchString, aParam, aPreviousResult, aListener) {
let params = JSON.parse(aParam) || {};
let applicable = !("type" in params) || this.applicableHeaders.has(params.type);
let applicable =
!("type" in params) || this.applicableHeaders.has(params.type);
this._result = new nsAbLDAPAutoCompleteResult(aSearchString);
aSearchString = aSearchString.toLocaleLowerCase();
@ -192,8 +203,10 @@ nsAbLDAPAutoCompleteSearch.prototype = {
try {
identity = MailServices.accounts.getIdentity(params.idKey);
} catch (ex) {
Cu.reportError("Couldn't get specified identity, " +
"falling back to global settings");
Cu.reportError(
"Couldn't get specified identity, " +
"falling back to global settings"
);
}
}
@ -202,7 +215,9 @@ nsAbLDAPAutoCompleteSearch.prototype = {
acDirURI = identity.directoryServer;
} else if (Services.prefs.getBoolPref("ldap_2.autoComplete.useDirectory")) {
// Try the global one
acDirURI = Services.prefs.getCharPref("ldap_2.autoComplete.directoryServer");
acDirURI = Services.prefs.getCharPref(
"ldap_2.autoComplete.directoryServer"
);
}
if (!acDirURI || Services.io.offline) {
@ -216,49 +231,76 @@ nsAbLDAPAutoCompleteSearch.prototype = {
// If we don't already have a cached query for this URI, build a new one.
acDirURI = "moz-abldapdirectory://" + acDirURI;
if (!this._book || this._book.URI != acDirURI) {
this._query =
Cc["@mozilla.org/addressbook/ldap-directory-query;1"]
.createInstance(Ci.nsIAbDirectoryQuery);
this._book = MailServices.ab.getDirectory(acDirURI)
.QueryInterface(Ci.nsIAbLDAPDirectory);
this._query = Cc[
"@mozilla.org/addressbook/ldap-directory-query;1"
].createInstance(Ci.nsIAbDirectoryQuery);
this._book = MailServices.ab
.getDirectory(acDirURI)
.QueryInterface(Ci.nsIAbLDAPDirectory);
// Create a minimal map just for the display name and primary email.
this._attributes =
Cc["@mozilla.org/addressbook/ldap-attribute-map;1"]
.createInstance(Ci.nsIAbLDAPAttributeMap);
this._attributes.setAttributeList("DisplayName",
this._book.attributeMap.getAttributeList("DisplayName", {}), true);
this._attributes.setAttributeList("PrimaryEmail",
this._book.attributeMap.getAttributeList("PrimaryEmail", {}), true);
this._attributes = Cc[
"@mozilla.org/addressbook/ldap-attribute-map;1"
].createInstance(Ci.nsIAbLDAPAttributeMap);
this._attributes.setAttributeList(
"DisplayName",
this._book.attributeMap.getAttributeList("DisplayName", {}),
true
);
this._attributes.setAttributeList(
"PrimaryEmail",
this._book.attributeMap.getAttributeList("PrimaryEmail", {}),
true
);
}
this._result._commentColumn = this._book.dirName;
this._listener = aListener;
this._timer.init(this, 60000, Ci.nsITimer.TYPE_ONE_SHOT);
var args =
Cc["@mozilla.org/addressbook/directory/query-arguments;1"]
.createInstance(Ci.nsIAbDirectoryQueryArguments);
var args = Cc[
"@mozilla.org/addressbook/directory/query-arguments;1"
].createInstance(Ci.nsIAbDirectoryQueryArguments);
var filterTemplate = this._book.getStringValue("autoComplete.filterTemplate", "");
var filterTemplate = this._book.getStringValue(
"autoComplete.filterTemplate",
""
);
// Use default value when preference is not set or it contains empty string
if (!filterTemplate)
if (!filterTemplate) {
filterTemplate = "(|(cn=%v1*%v2-*)(mail=%v1*%v2-*)(sn=%v1*%v2-*))";
}
// Create filter from filter template and search string
var ldapSvc = Cc["@mozilla.org/network/ldap-service;1"]
.getService(Ci.nsILDAPService);
var filter = ldapSvc.createFilter(1024, filterTemplate, "", "", "", aSearchString);
if (!filter)
throw new Error("Filter string is empty, check if filterTemplate variable is valid in prefs.js.");
var ldapSvc = Cc["@mozilla.org/network/ldap-service;1"].getService(
Ci.nsILDAPService
);
var filter = ldapSvc.createFilter(
1024,
filterTemplate,
"",
"",
"",
aSearchString
);
if (!filter) {
throw new Error(
"Filter string is empty, check if filterTemplate variable is valid in prefs.js."
);
}
args.typeSpecificArg = this._attributes;
args.querySubDirectories = true;
args.filter = filter;
// Start the actual search
this._context =
this._query.doQuery(this._book, args, this, this._book.maxHits, 0);
this._context = this._query.doQuery(
this._book,
args,
this,
this._book.maxHits,
0
);
},
stopSearch() {
@ -271,8 +313,9 @@ nsAbLDAPAutoCompleteSearch.prototype = {
// nsIAbDirSearchListener
onSearchFinished(aResult, aErrorMsg) {
if (!this._listener)
if (!this._listener) {
return;
}
if (aResult == nsIAbDirectoryQueryResultListener.queryResultComplete) {
if (this._result.matchCount) {
@ -292,8 +335,9 @@ nsAbLDAPAutoCompleteSearch.prototype = {
},
onSearchFoundCard(aCard) {
if (!this._listener)
if (!this._listener) {
return;
}
this._addToResult(aCard);
@ -309,11 +353,15 @@ nsAbLDAPAutoCompleteSearch.prototype = {
// nsISupports
QueryInterface: ChromeUtils.generateQI([Ci.nsIObserver,
Ci.nsIAutoCompleteSearch,
Ci.nsIAbDirSearchListener]),
QueryInterface: ChromeUtils.generateQI([
Ci.nsIObserver,
Ci.nsIAutoCompleteSearch,
Ci.nsIAbDirSearchListener,
]),
};
// Module
var NSGetFactory = XPCOMUtils.generateNSGetFactory([nsAbLDAPAutoCompleteSearch]);
var NSGetFactory = XPCOMUtils.generateNSGetFactory([
nsAbLDAPAutoCompleteSearch,
]);

Просмотреть файл

@ -1,6 +1,10 @@
var {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm");
var {MailServices} = ChromeUtils.import("resource:///modules/MailServices.jsm");
var {XPCOMUtils} = ChromeUtils.import("resource://gre/modules/XPCOMUtils.jsm");
var { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm");
var { MailServices } = ChromeUtils.import(
"resource:///modules/MailServices.jsm"
);
var { XPCOMUtils } = ChromeUtils.import(
"resource://gre/modules/XPCOMUtils.jsm"
);
var CC = Components.Constructor;

Просмотреть файл

@ -1,6 +1,10 @@
var {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm");
var {MailServices} = ChromeUtils.import("resource:///modules/MailServices.jsm");
var {XPCOMUtils} = ChromeUtils.import("resource://gre/modules/XPCOMUtils.jsm");
var { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm");
var { MailServices } = ChromeUtils.import(
"resource:///modules/MailServices.jsm"
);
var { XPCOMUtils } = ChromeUtils.import(
"resource://gre/modules/XPCOMUtils.jsm"
);
// Ensure the profile directory is set up
do_get_profile();
@ -51,10 +55,12 @@ function loadABFile(source, dest) {
let destFile = do_get_profile();
destFile.append(kPABData.fileName);
let fstream = Cc["@mozilla.org/network/file-input-stream;1"]
.createInstance(Ci.nsIFileInputStream);
let cstream = Cc["@mozilla.org/intl/converter-input-stream;1"]
.createInstance(Ci.nsIConverterInputStream);
let fstream = Cc["@mozilla.org/network/file-input-stream;1"].createInstance(
Ci.nsIFileInputStream
);
let cstream = Cc["@mozilla.org/intl/converter-input-stream;1"].createInstance(
Ci.nsIConverterInputStream
);
fstream.init(sourceFile, -1, 0, 0);
cstream.init(fstream, "UTF-8", 0, 0);

Просмотреть файл

@ -16,8 +16,9 @@ var kCompanyValue = "Test\u00D0 Company";
function run_test() {
// Create a new card
var card = Cc["@mozilla.org/addressbook/cardproperty;1"]
.createInstance(Ci.nsIAbCard);
var card = Cc["@mozilla.org/addressbook/cardproperty;1"].createInstance(
Ci.nsIAbCard
);
// Test - Set First, Last and Display Names and Email Address
// via setProperty, and check correctly saved via their
@ -91,7 +92,9 @@ function run_test() {
card.firstName = kFNValue;
card.lastName = kLNValue;
let bundle = Services.strings.createBundle("chrome://messenger/locale/addressbook/addressBook.properties");
let bundle = Services.strings.createBundle(
"chrome://messenger/locale/addressbook/addressBook.properties"
);
Assert.equal(card.generateName(1, bundle), kLNValue + ", " + kFNValue);

Просмотреть файл

@ -33,8 +33,9 @@ function check_ab(abConfig) {
// Test - Is it the right type?
if (abConfig.dirType == 2)
if (abConfig.dirType == 2) {
Assert.ok(AB instanceof Ci.nsIAbMDBDirectory);
}
// Test - Check attributes
@ -72,32 +73,45 @@ function check_ab(abConfig) {
Assert.equal(AB.getStringValue("random", "abc"), "abc");
Assert.equal(AB.getLocalizedStringValue("random", "xyz"), "xyz");
// Test - check get/set int preferences on nsIAbDirectory
AB.setIntValue("inttest", 12345);
Assert.equal(Services.prefs.getIntPref(abConfig.dirPrefID + ".inttest"), 12345);
Assert.equal(
Services.prefs.getIntPref(abConfig.dirPrefID + ".inttest"),
12345
);
Assert.equal(AB.getIntValue("inttest", -1), 12345);
AB.setIntValue("inttest", 123456);
Assert.equal(Services.prefs.getIntPref(abConfig.dirPrefID + ".inttest"), 123456);
Assert.equal(
Services.prefs.getIntPref(abConfig.dirPrefID + ".inttest"),
123456
);
Assert.equal(AB.getIntValue("inttest", -2), 123456);
// Test - check get/set bool preferences on nsIAbDirectory
AB.setBoolValue("booltest", true);
Assert.equal(Services.prefs.getBoolPref(abConfig.dirPrefID + ".booltest"), true);
Assert.equal(
Services.prefs.getBoolPref(abConfig.dirPrefID + ".booltest"),
true
);
Assert.equal(AB.getBoolValue("booltest", false), true);
AB.setBoolValue("booltest", false);
Assert.equal(Services.prefs.getBoolPref(abConfig.dirPrefID + ".booltest"), false);
Assert.equal(
Services.prefs.getBoolPref(abConfig.dirPrefID + ".booltest"),
false
);
Assert.equal(AB.getBoolValue("booltest", true), false);
// Test - check get/set string preferences on nsIAbDirectory
AB.setStringValue("stringtest", "tyu");
Assert.equal(Services.prefs.getCharPref(abConfig.dirPrefID + ".stringtest"), "tyu");
Assert.equal(
Services.prefs.getCharPref(abConfig.dirPrefID + ".stringtest"),
"tyu"
);
Assert.equal(AB.getStringValue("stringtest", ""), "tyu");
}

Просмотреть файл

@ -3,26 +3,34 @@ function run_test() {
MailServices.ab.directories;
let book = MailServices.ab.getDirectory(kPABData.URI);
let list = Cc["@mozilla.org/addressbook/directoryproperty;1"].createInstance(Ci.nsIAbDirectory);
let list = Cc["@mozilla.org/addressbook/directoryproperty;1"].createInstance(
Ci.nsIAbDirectory
);
list.isMailList = true;
list.dirName = "list";
list = book.addMailList(list);
let contact1 = Cc["@mozilla.org/addressbook/cardproperty;1"].createInstance(Ci.nsIAbCard);
let contact1 = Cc["@mozilla.org/addressbook/cardproperty;1"].createInstance(
Ci.nsIAbCard
);
contact1.firstName = "contact";
contact1.lastName = "1";
contact1.primaryEmail = "contact1@invalid";
contact1 = book.addCard(contact1);
list.addCard(contact1);
let contact2 = Cc["@mozilla.org/addressbook/cardproperty;1"].createInstance(Ci.nsIAbCard);
let contact2 = Cc["@mozilla.org/addressbook/cardproperty;1"].createInstance(
Ci.nsIAbCard
);
contact2.firstName = "contact";
contact2.lastName = "2";
// No email address!
contact2 = book.addCard(contact2);
list.addCard(contact2);
let contact3 = Cc["@mozilla.org/addressbook/cardproperty;1"].createInstance(Ci.nsIAbCard);
let contact3 = Cc["@mozilla.org/addressbook/cardproperty;1"].createInstance(
Ci.nsIAbCard
);
contact3.firstName = "contact";
contact3.lastName = "3";
contact3.primaryEmail = "contact3@invalid";
@ -65,7 +73,9 @@ function run_test() {
// For some unknown reason this is necessary for book.addressLists to be populated.
if (kPABData.dirType == 2) {
book.QueryInterface(Ci.nsIAbMDBDirectory).database.getMailingListsFromDB(book);
book
.QueryInterface(Ci.nsIAbMDBDirectory)
.database.getMailingListsFromDB(book);
equal(1, book.addressLists.Count());
}
list = book.addressLists.GetElementAt(0).QueryInterface(Ci.nsIAbDirectory);

Просмотреть файл

@ -6,5 +6,7 @@
function run_test() {
// Before bug 387403 this would hang, eating up all the memory until it
// crashed.
MailServices.ab.escapedVCardToAbCard("begin:vcard\nfn;quoted-printable:Xxxx=C5=82xx Xxx\nn;quoted-printable:Xxx;Xxxx=C5=82xx \nadr;quoted-printable;quoted-printable;dom:;;xx. Xxxxxxxxxxxx X;Xxxxxx=C3=3");
MailServices.ab.escapedVCardToAbCard(
"begin:vcard\nfn;quoted-printable:Xxxx=C5=82xx Xxx\nn;quoted-printable:Xxx;Xxxx=C5=82xx \nadr;quoted-printable;quoted-printable;dom:;;xx. Xxxxxxxxxxxx X;Xxxxxx=C3=3"
);
}

Просмотреть файл

@ -8,7 +8,9 @@ function run_test() {
Assert.ok(pab instanceof Ci.nsIAbDirectory);
try {
pab.deleteCards(null); // this should throw an error
do_throw("Error, deleteCards should throw an error when null is passed to it");
do_throw(
"Error, deleteCards should throw an error when null is passed to it"
);
} catch (e) {
// make sure the correct error message was thrown
Assert.equal(e.result, Cr.NS_ERROR_INVALID_POINTER);

Просмотреть файл

@ -36,5 +36,7 @@ function run_test() {
}
}
results.forEach(function(result) { Assert.ok(result.result); });
results.forEach(function(result) {
Assert.ok(result.result);
});
}

Просмотреть файл

@ -15,7 +15,10 @@ function check_correct_card(card) {
Assert.equal(card.lastName, "LastName1");
Assert.equal(card.displayName, "DisplayName1");
Assert.equal(card.primaryEmail, "PrimaryEmail1@test.invalid");
Assert.equal(card.getProperty("SecondEmail", "BAD"), "SecondEmail1\u00D0@test.invalid");
Assert.equal(
card.getProperty("SecondEmail", "BAD"),
"SecondEmail1\u00D0@test.invalid"
);
}
function run_test() {
@ -76,7 +79,7 @@ function run_test() {
cards = AB.getCardsFromProperty("LastName", "Doe", true);
var i = 0;
var data = [ "John", "Jane" ];
var data = ["John", "Jane"];
while (cards.hasMoreElements()) {
i++;

Просмотреть файл

@ -19,95 +19,120 @@ var nsIAbPMF = Ci.nsIAbPreferMailFormat;
// address to add a different card each time.
var addEmailChecks =
// First 3 items aimed at basic collection and mail format.
[ { emailHeader: "test0@foo.invalid",
[
{
emailHeader: "test0@foo.invalid",
primaryEmail: "test0@foo.invalid",
mailFormat: nsIAbPMF.unknown,
displayName: "",
firstName: "",
lastName: "",
screenName: "" },
{ emailHeader: "test1@foo.invalid",
screenName: "",
},
{
emailHeader: "test1@foo.invalid",
primaryEmail: "test1@foo.invalid",
mailFormat: nsIAbPMF.plaintext,
displayName: "",
firstName: "",
lastName: "",
screenName: "" },
{ emailHeader: "test2@foo.invalid",
screenName: "",
},
{
emailHeader: "test2@foo.invalid",
primaryEmail: "test2@foo.invalid",
mailFormat: nsIAbPMF.html,
displayName: "",
firstName: "",
lastName: "",
screenName: "" },
screenName: "",
},
// UTF-8 based addresses (bug 407564)
{ emailHeader: "test0@\u00D0.invalid",
{
emailHeader: "test0@\u00D0.invalid",
primaryEmail: "test0@\u00D0.invalid",
mailFormat: nsIAbPMF.unknown,
displayName: "",
firstName: "",
lastName: "",
screenName: "" },
{ emailHeader: "test0\u00D0@foo.invalid",
screenName: "",
},
{
emailHeader: "test0\u00D0@foo.invalid",
primaryEmail: "test0\u00D0@foo.invalid",
mailFormat: nsIAbPMF.unknown,
displayName: "",
firstName: "",
lastName: "",
screenName: "" },
screenName: "",
},
// Screen names
{ emailHeader: "invalid\u00D00@aol.com",
{
emailHeader: "invalid\u00D00@aol.com",
primaryEmail: "invalid\u00D00@aol.com",
mailFormat: nsIAbPMF.unknown,
displayName: "",
firstName: "",
lastName: "",
screenName: "invalid\u00D00" },
{ emailHeader: "invalid1\u00D00@cs.com",
screenName: "invalid\u00D00",
},
{
emailHeader: "invalid1\u00D00@cs.com",
primaryEmail: "invalid1\u00D00@cs.com",
mailFormat: nsIAbPMF.unknown,
displayName: "",
firstName: "",
lastName: "",
screenName: "invalid1\u00D00" },
{ emailHeader: "invalid2\u00D00@netscape.net",
screenName: "invalid1\u00D00",
},
{
emailHeader: "invalid2\u00D00@netscape.net",
primaryEmail: "invalid2\u00D00@netscape.net",
mailFormat: nsIAbPMF.unknown,
displayName: "",
firstName: "",
lastName: "",
screenName: "invalid2\u00D00" },
screenName: "invalid2\u00D00",
},
// Collection of names
{ emailHeader: "Test User <test3@foo.invalid>",
{
emailHeader: "Test User <test3@foo.invalid>",
primaryEmail: "test3@foo.invalid",
mailFormat: nsIAbPMF.unknown,
displayName: "Test User",
firstName: "Test",
lastName: "User",
screenName: "" },
{ emailHeader: "Test <test4@foo.invalid>",
screenName: "",
},
{
emailHeader: "Test <test4@foo.invalid>",
primaryEmail: "test4@foo.invalid",
mailFormat: nsIAbPMF.unknown,
displayName: "Test",
firstName: "",
lastName: "",
screenName: "" },
screenName: "",
},
// Collection of names with UTF-8 specific items
{ emailHeader: "Test\u00D0 User <test5@foo.invalid>",
{
emailHeader: "Test\u00D0 User <test5@foo.invalid>",
primaryEmail: "test5@foo.invalid",
mailFormat: nsIAbPMF.unknown,
displayName: "Test\u00D0 User",
firstName: "Test\u00D0",
lastName: "User",
screenName: "" },
{ emailHeader: "Test\u00D0 <test6@foo.invalid>",
screenName: "",
},
{
emailHeader: "Test\u00D0 <test6@foo.invalid>",
primaryEmail: "test6@foo.invalid",
mailFormat: nsIAbPMF.unknown,
displayName: "Test\u00D0",
firstName: "",
lastName: "",
screenName: "" },
];
screenName: "",
},
];
// Source fields (emailHeader/mailFormat) and expected results for use for
// testing the modification of cards in the database.
@ -115,63 +140,79 @@ var addEmailChecks =
// Note: these sets re-use some of the ones for ease of definition.
var modifyEmailChecks =
// No display name/other details. Add details and modify mail format.
[ { emailHeader: "Modify User\u00D0 <test0@\u00D0.invalid>",
[
{
emailHeader: "Modify User\u00D0 <test0@\u00D0.invalid>",
primaryEmail: "test0@\u00D0.invalid",
mailFormat: nsIAbPMF.html,
displayName: "Modify User\u00D0",
firstName: "Modify",
lastName: "User\u00D0",
screenName: "" },
{ emailHeader: "Modify <test0\u00D0@foo.invalid>",
screenName: "",
},
{
emailHeader: "Modify <test0\u00D0@foo.invalid>",
primaryEmail: "test0\u00D0@foo.invalid",
mailFormat: nsIAbPMF.plaintext,
displayName: "Modify",
firstName: "",
lastName: "",
screenName: "" },
screenName: "",
},
// No modification of existing cards with display names
{ emailHeader: "Modify2 User\u00D02 <test0@\u00D0.invalid>",
{
emailHeader: "Modify2 User\u00D02 <test0@\u00D0.invalid>",
primaryEmail: "test0@\u00D0.invalid",
mailFormat: nsIAbPMF.html,
displayName: "Modify User\u00D0",
firstName: "Modify",
lastName: "User\u00D0",
screenName: "" },
{ emailHeader: "Modify3 <test0\u00D0@foo.invalid>",
screenName: "",
},
{
emailHeader: "Modify3 <test0\u00D0@foo.invalid>",
primaryEmail: "test0\u00D0@foo.invalid",
mailFormat: nsIAbPMF.plaintext,
displayName: "Modify",
firstName: "",
lastName: "",
screenName: "" },
screenName: "",
},
// Check no modification of cards for mail format where format is not
// "unknown".
{ emailHeader: "Modify User\u00D0 <test0@\u00D0.invalid>",
{
emailHeader: "Modify User\u00D0 <test0@\u00D0.invalid>",
primaryEmail: "test0@\u00D0.invalid",
mailFormat: nsIAbPMF.plaintext,
mailFormatOut: nsIAbPMF.html,
displayName: "Modify User\u00D0",
firstName: "Modify",
lastName: "User\u00D0",
screenName: "" },
{ emailHeader: "Modify <test0\u00D0@foo.invalid>",
screenName: "",
},
{
emailHeader: "Modify <test0\u00D0@foo.invalid>",
primaryEmail: "test0\u00D0@foo.invalid",
mailFormat: nsIAbPMF.html,
mailFormatOut: nsIAbPMF.plaintext,
displayName: "Modify",
firstName: "",
lastName: "",
screenName: "" },
screenName: "",
},
// No modification of cards with email in second email address.
{ emailHeader: "Modify Secondary <usersec\u00D0@foo.invalid>",
{
emailHeader: "Modify Secondary <usersec\u00D0@foo.invalid>",
primaryEmail: "userprim\u00D0@foo.invalid",
secondEmail: "usersec\u00D0@foo.invalid",
mailFormat: nsIAbPMF.unknown,
displayName: "",
firstName: "",
lastName: "",
screenName: "" },
{ emailHeader: "Modify <usersec\u00D0@foo.invalid>",
screenName: "",
},
{
emailHeader: "Modify <usersec\u00D0@foo.invalid>",
primaryEmail: "userprim\u00D0@foo.invalid",
secondEmail: "usersec\u00D0@foo.invalid",
mailFormat: nsIAbPMF.html,
@ -179,8 +220,9 @@ var modifyEmailChecks =
displayName: "",
firstName: "",
lastName: "",
screenName: "" },
];
screenName: "",
},
];
var collectChecker = {
addressCollect: null,
@ -189,13 +231,22 @@ var collectChecker = {
checkAddress(aDetails) {
try {
this.addressCollect.collectAddress(aDetails.emailHeader, true,
aDetails.mailFormat);
this.addressCollect.collectAddress(
aDetails.emailHeader,
true,
aDetails.mailFormat
);
this.checkCardResult(aDetails, false);
} catch (e) {
throw new Error("FAILED in checkAddress emailHeader: " + aDetails.emailHeader +
" part: " + this.part + " : " + e);
throw new Error(
"FAILED in checkAddress emailHeader: " +
aDetails.emailHeader +
" part: " +
this.part +
" : " +
e
);
}
++this.part;
},
@ -206,17 +257,18 @@ var collectChecker = {
var emailHeader = "";
var i;
for (i = 0; i < aDetailsArray.length - 1; ++i)
for (i = 0; i < aDetailsArray.length - 1; ++i) {
emailHeader += aDetailsArray[i].emailHeader + ", ";
}
emailHeader += aDetailsArray[aDetailsArray.length - 1].emailHeader;
// Now add it. In this case we just set the Mail format Type to unknown.
this.addressCollect.collectAddress(emailHeader, true,
nsIAbPMF.unknown);
this.addressCollect.collectAddress(emailHeader, true, nsIAbPMF.unknown);
for (i = 0; i < aDetailsArray.length; ++i)
for (i = 0; i < aDetailsArray.length; ++i) {
this.checkCardResult(aDetailsArray[i], true);
}
} catch (e) {
throw new Error("FAILED in checkAll item: " + i + " : " + e);
}
@ -228,22 +280,41 @@ var collectChecker = {
Assert.ok(card != null);
if ("secondEmail" in aDetails)
Assert.equal(card.getProperty("SecondEmail", "BAD"), aDetails.secondEmail);
if ("secondEmail" in aDetails) {
Assert.equal(
card.getProperty("SecondEmail", "BAD"),
aDetails.secondEmail
);
}
if (overrideMailFormat)
Assert.equal(card.getProperty("PreferMailFormat", "BAD"), nsIAbPMF.unknown);
else if ("mailFormatOut" in aDetails)
Assert.equal(card.getProperty("PreferMailFormat", "BAD"), aDetails.mailFormatOut);
else
Assert.equal(card.getProperty("PreferMailFormat", "BAD"), aDetails.mailFormat);
if (overrideMailFormat) {
Assert.equal(
card.getProperty("PreferMailFormat", "BAD"),
nsIAbPMF.unknown
);
} else if ("mailFormatOut" in aDetails) {
Assert.equal(
card.getProperty("PreferMailFormat", "BAD"),
aDetails.mailFormatOut
);
} else {
Assert.equal(
card.getProperty("PreferMailFormat", "BAD"),
aDetails.mailFormat
);
}
Assert.equal(card.displayName, aDetails.displayName);
Assert.equal(card.firstName, aDetails.firstName);
Assert.equal(card.lastName, aDetails.lastName);
Assert.equal(card.getProperty("_AimScreenName", ""), aDetails.screenName);
} catch (e) {
throw new Error("FAILED in checkCardResult emailHeader: " + aDetails.emailHeader + " : " + e);
throw new Error(
"FAILED in checkCardResult emailHeader: " +
aDetails.emailHeader +
" : " +
e
);
}
},
};
@ -257,18 +328,22 @@ function run_test() {
// Get the actual AB for the collector so we can check cards have been
// added.
collectChecker.AB =
MailServices.ab.getDirectory(Services.prefs.getCharPref("mail.collect_addressbook"));
collectChecker.AB = MailServices.ab.getDirectory(
Services.prefs.getCharPref("mail.collect_addressbook")
);
// Get the actual collecter
collectChecker.addressCollect =
Cc["@mozilla.org/addressbook/services/addressCollector;1"]
.getService(Ci.nsIAbAddressCollector);
collectChecker.addressCollect = Cc[
"@mozilla.org/addressbook/services/addressCollector;1"
].getService(Ci.nsIAbAddressCollector);
// Test - Addition of header without email address.
collectChecker.addressCollect.collectAddress("MyTest <>", true,
nsIAbPMF.unknown);
collectChecker.addressCollect.collectAddress(
"MyTest <>",
true,
nsIAbPMF.unknown
);
// Address book should have no cards present.
Assert.ok(!collectChecker.AB.childCards.hasMoreElements());
@ -277,11 +352,15 @@ function run_test() {
// As we've just set everything up, we know we haven't got anything in the
// AB, so just try and collect without adding.
collectChecker.addressCollect.collectAddress(addEmailChecks[0].emailHeader,
false,
addEmailChecks[0].mailFormat);
collectChecker.addressCollect.collectAddress(
addEmailChecks[0].emailHeader,
false,
addEmailChecks[0].mailFormat
);
var card = collectChecker.AB.cardForEmailAddress(addEmailChecks[0].emailHeader);
var card = collectChecker.AB.cardForEmailAddress(
addEmailChecks[0].emailHeader
);
Assert.ok(card == null);
@ -295,8 +374,9 @@ function run_test() {
// First delete all existing cards
var childCards = collectChecker.AB.childCards;
var cardsToDelete = Cc["@mozilla.org/array;1"]
.createInstance(Ci.nsIMutableArray);
var cardsToDelete = Cc["@mozilla.org/array;1"].createInstance(
Ci.nsIMutableArray
);
while (childCards.hasMoreElements()) {
cardsToDelete.appendElement(childCards.getNext());
}
@ -310,7 +390,10 @@ function run_test() {
// Address book should have no cards present.
Assert.ok(!collectChecker.AB.childCards.hasMoreElements());
Assert.equal(collectChecker.AB.cardForEmailAddress(addEmailChecks[0].emailHeader), null);
Assert.equal(
collectChecker.AB.cardForEmailAddress(addEmailChecks[0].emailHeader),
null
);
// Now do all emails at the same time.
collectChecker.checkAll(addEmailChecks);
@ -319,8 +402,9 @@ function run_test() {
// Add a basic card with just primary and second email to allow testing
// of the case where we don't modify when second email is matching.
card = Cc["@mozilla.org/addressbook/cardproperty;1"]
.createInstance(Ci.nsIAbCard);
card = Cc["@mozilla.org/addressbook/cardproperty;1"].createInstance(
Ci.nsIAbCard
);
card.primaryEmail = "userprim\u00D0@foo.invalid";
card.setProperty("SecondEmail", "usersec\u00D0@foo.invalid");
@ -338,41 +422,50 @@ function run_test() {
// Add an email that is already there and check we get two instances of it in
// the AB.
const kSingleAddress = modifyEmailChecks[modifyEmailChecks.length - 1]
.primaryEmail;
const kSingleAddress =
modifyEmailChecks[modifyEmailChecks.length - 1].primaryEmail;
const kSingleDisplayName = "Test Single";
collectChecker.addressCollect.collectSingleAddress(kSingleAddress,
kSingleDisplayName,
true,
nsIAbPMF.unknown,
true);
collectChecker.addressCollect.collectSingleAddress(
kSingleAddress,
kSingleDisplayName,
true,
nsIAbPMF.unknown,
true
);
// Try collecting the same address in another case. This shouldn't create any
// new card.
collectChecker.addressCollect.collectSingleAddress(kSingleAddress.toUpperCase(),
kSingleDisplayName,
true,
nsIAbPMF.unknown,
true);
collectChecker.addressCollect.collectSingleAddress(
kSingleAddress.toUpperCase(),
kSingleDisplayName,
true,
nsIAbPMF.unknown,
true
);
childCards = collectChecker.AB.childCards;
var foundCards = [];
while (childCards.hasMoreElements()) {
card = childCards.getNext();
if (card instanceof Ci.nsIAbCard &&
card.primaryEmail == kSingleAddress)
if (card instanceof Ci.nsIAbCard && card.primaryEmail == kSingleAddress) {
foundCards.push(card);
}
}
Assert.equal(foundCards.length, 2);
if (foundCards[0].displayName != kSingleDisplayName &&
foundCards[1].displayName != kSingleDisplayName)
if (
foundCards[0].displayName != kSingleDisplayName &&
foundCards[1].displayName != kSingleDisplayName
) {
do_throw("Error, collectSingleCard didn't create a new card");
}
if (foundCards[0].displayName != "" &&
foundCards[1].displayName != "")
do_throw("Error, collectSingleCard created ok, but other card does not exist");
if (foundCards[0].displayName != "" && foundCards[1].displayName != "") {
do_throw(
"Error, collectSingleCard created ok, but other card does not exist"
);
}
}

Просмотреть файл

@ -12,9 +12,9 @@ function run_test() {
// Test - Get the address collecter
// Get the actual collecter
var addressCollect =
Cc["@mozilla.org/addressbook/services/addressCollector;1"]
.getService(Ci.nsIAbAddressCollector);
var addressCollect = Cc[
"@mozilla.org/addressbook/services/addressCollector;1"
].getService(Ci.nsIAbAddressCollector);
// Set the new pref afterwards to ensure we change correctly
Services.prefs.setCharPref("mail.collect_addressbook", kCABData.URI);
@ -25,8 +25,11 @@ function run_test() {
// address collecter can't currently create ABs itself (bug 314448).
MailServices.ab.directories;
addressCollect.collectAddress("Other Book <other@book.invalid>", true,
nsIAbPMF.unknown);
addressCollect.collectAddress(
"Other Book <other@book.invalid>",
true,
nsIAbPMF.unknown
);
let PAB = MailServices.ab.getDirectory(kPABData.URI);

Просмотреть файл

@ -3,8 +3,12 @@
* addr database and delete the underlying directory, which forces the ab
* closed.
*/
var ab_prefix = "test-537815-";
var card_properties = { FirstName: "01-first-3", LastName: "02-last", PrimaryEmail: "08-email-1@zindus.invalid" };
var ab_prefix = "test-537815-";
var card_properties = {
FirstName: "01-first-3",
LastName: "02-last",
PrimaryEmail: "08-email-1@zindus.invalid",
};
var max_addressbooks = 10;
function bug_537815_fixture_setup() {
@ -26,10 +30,13 @@ function bug_537815_fixture_setup() {
if (j == 1 && elem.dirName.startsWith(ab_prefix)) {
for (i = 1; i <= 1000; i++) {
let abCard = Cc["@mozilla.org/addressbook/cardproperty;1"].createInstance().QueryInterface(Ci.nsIAbCard);
let abCard = Cc["@mozilla.org/addressbook/cardproperty;1"]
.createInstance()
.QueryInterface(Ci.nsIAbCard);
for (key in card_properties)
for (key in card_properties) {
abCard.setProperty(key, card_properties[key]);
}
abCard = dir.addCard(abCard);
}
@ -45,8 +52,8 @@ function bug_537815_test() {
while (enm_dirs.hasMoreElements()) {
let elem = enm_dirs.getNext().QueryInterface(Ci.nsIAbDirectory);
let uri = elem.URI;
let dir = MailServices.ab.getDirectory(uri);
let uri = elem.URI;
let dir = MailServices.ab.getDirectory(uri);
if (elem.dirName.startsWith(ab_prefix)) {
let enm_cards = dir.childCards;
@ -83,8 +90,9 @@ function bug_537815_fixture_tear_down() {
}
}
for (let uri in a_uri)
for (let uri in a_uri) {
MailServices.ab.deleteAddressBook(uri);
}
}
function run_test() {

Просмотреть файл

@ -8,7 +8,9 @@ var DIR_TYPE = kPABData.dirType;
var FILE_NAME = DIR_TYPE == 101 ? "abook-2.sqlite" : "abook-1.mab";
var SCHEME = DIR_TYPE == 101 ? "jsaddrbook" : "moz-abmdbdirectory";
var { MailServices } = ChromeUtils.import("resource:///modules/MailServices.jsm");
var { MailServices } = ChromeUtils.import(
"resource:///modules/MailServices.jsm"
);
var { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm");
var book, contact, list, listCard;
@ -36,21 +38,34 @@ var observer = {
this.events.push(["onItemRemoved", parent, item]);
},
onItemPropertyChanged(item, property, oldValue, newValue) {
this.events.push(["onItemPropertyChanged", item, property, oldValue, newValue]);
this.events.push([
"onItemPropertyChanged",
item,
property,
oldValue,
newValue,
]);
},
observe(subject, topic, data) {
this.events.push([topic, subject, data]);
},
checkEvents(...events) {
info("Actual events: " + JSON.stringify(observer.events.map(e => e.map(a => {
if (a instanceof Ci.nsIAbDirectory) {
return `[nsIAbDirectory]`;
}
if (a instanceof Ci.nsIAbCard) {
return `[nsIAbCard]`;
}
return a;
}))));
info(
"Actual events: " +
JSON.stringify(
observer.events.map(e =>
e.map(a => {
if (a instanceof Ci.nsIAbDirectory) {
return `[nsIAbDirectory]`;
}
if (a instanceof Ci.nsIAbCard) {
return `[nsIAbCard]`;
}
return a;
})
)
)
);
equal(observer.events.length, events.length);
for (let expectedEvent of events) {
@ -107,22 +122,39 @@ add_task(async function createAddressBook() {
equal(Array.from(book.childCards).length, 0);
// Check prefs.
equal(Services.prefs.getStringPref("ldap_2.servers.newbook.description"), "new book");
equal(
Services.prefs.getStringPref("ldap_2.servers.newbook.description"),
"new book"
);
equal(Services.prefs.getIntPref("ldap_2.servers.newbook.dirType"), DIR_TYPE);
equal(Services.prefs.getStringPref("ldap_2.servers.newbook.filename"), FILE_NAME);
equal(
Services.prefs.getStringPref("ldap_2.servers.newbook.filename"),
FILE_NAME
);
equal(Services.prefs.getStringPref("ldap_2.servers.newbook.uid"), book.UID);
equal([...MailServices.ab.directories].length, DIR_TYPE == 101 ? 5 : 3);
});
add_task(async function editAddressBook() {
book.dirName = "updated book";
observer.checkEvents(["onItemPropertyChanged", book, "DirName", "new book", "updated book"]);
observer.checkEvents([
"onItemPropertyChanged",
book,
"DirName",
"new book",
"updated book",
]);
equal(book.dirName, "updated book");
equal(Services.prefs.getStringPref("ldap_2.servers.newbook.description"), "updated book");
equal(
Services.prefs.getStringPref("ldap_2.servers.newbook.description"),
"updated book"
);
});
add_task(async function createContact() {
contact = Cc["@mozilla.org/addressbook/cardproperty;1"].createInstance(Ci.nsIAbCard);
contact = Cc["@mozilla.org/addressbook/cardproperty;1"].createInstance(
Ci.nsIAbCard
);
contact.displayName = "a new contact";
contact.firstName = "new";
contact.lastName = "contact";
@ -134,7 +166,9 @@ add_task(async function createContact() {
);
// Check enumerations.
let childCards = Array.from(book.childCards, cc => cc.QueryInterface(Ci.nsIAbCard));
let childCards = Array.from(book.childCards, cc =>
cc.QueryInterface(Ci.nsIAbCard)
);
equal(childCards.length, 1);
ok(childCards[0].equals(contact));
@ -142,9 +176,18 @@ add_task(async function createContact() {
equal(contact.uuid, "ldap_2.servers.newbook&updated book#1");
// Check nsIAbItem methods.
equal(contact.generateName(Ci.nsIAbItem.GENERATE_DISPLAY_NAME), "a new contact");
equal(contact.generateName(Ci.nsIAbItem.GENERATE_LAST_FIRST_ORDER), "contact, new");
equal(contact.generateName(Ci.nsIAbItem.GENERATE_FIRST_LAST_ORDER), "new contact");
equal(
contact.generateName(Ci.nsIAbItem.GENERATE_DISPLAY_NAME),
"a new contact"
);
equal(
contact.generateName(Ci.nsIAbItem.GENERATE_LAST_FIRST_ORDER),
"contact, new"
);
equal(
contact.generateName(Ci.nsIAbItem.GENERATE_FIRST_LAST_ORDER),
"new contact"
);
// Check nsIAbCard properties.
equal(contact.directoryId, book.uuid);
@ -164,27 +207,35 @@ add_task(async function editContact() {
observer.checkEvents(
// TODO MDB has three null args but we can do better than that.
["onItemPropertyChanged", contact],
["addrbook-contact-updated", contact, book.UID],
["addrbook-contact-updated", contact, book.UID]
);
equal(contact.firstName, "updated");
equal(contact.lastName, "contact");
});
add_task(async function createMailingList() {
list = Cc["@mozilla.org/addressbook/directoryproperty;1"].createInstance(Ci.nsIAbDirectory);
list = Cc["@mozilla.org/addressbook/directoryproperty;1"].createInstance(
Ci.nsIAbDirectory
);
list.isMailList = true;
list.dirName = "new list";
list = book.addMailList(list);
// Skip checking events temporarily, until listCard is defined.
// Check enumerations.
let addressLists = Array.from(book.addressLists.enumerate(), al => al.QueryInterface(Ci.nsIAbDirectory));
let addressLists = Array.from(book.addressLists.enumerate(), al =>
al.QueryInterface(Ci.nsIAbDirectory)
);
equal(addressLists.length, 1);
equal(addressLists[0].UID, list.UID); // TODO Object equality doesn't work because of XPCOM.
let childNodes = Array.from(book.childNodes, cn => cn.QueryInterface(Ci.nsIAbDirectory));
let childNodes = Array.from(book.childNodes, cn =>
cn.QueryInterface(Ci.nsIAbDirectory)
);
equal(childNodes.length, 1);
equal(childNodes[0].UID, list.UID); // TODO Object equality doesn't work because of XPCOM.
let childCards = Array.from(book.childCards, cc => cc.QueryInterface(Ci.nsIAbCard));
let childCards = Array.from(book.childCards, cc =>
cc.QueryInterface(Ci.nsIAbCard)
);
equal(childCards.length, 2);
if (childCards[0].isMailList) {
listCard = childCards[0];
@ -234,17 +285,21 @@ add_task(async function addMailingListMember() {
["onItemPropertyChanged", contact, null, null, null],
["onItemPropertyChanged", contact, null, null, null],
["onItemAdded", book, contact],
["onItemAdded", list, contact],
["onItemAdded", list, contact]
// ["addrbook-list-member-added", contact, list.UID] // MDB fires this on dropcard but not addcard?!
);
equal(1, list.addressLists.Count());
// Check list enumerations.
let addressLists = Array.from(list.addressLists.enumerate(), al => al.QueryInterface(Ci.nsIAbCard));
let addressLists = Array.from(list.addressLists.enumerate(), al =>
al.QueryInterface(Ci.nsIAbCard)
);
equal(addressLists.length, 1);
ok(addressLists[0].equals(contact));
equal(Array.from(list.childNodes).length, 0);
let childCards = Array.from(list.childCards, cc => cc.QueryInterface(Ci.nsIAbCard));
let childCards = Array.from(list.childCards, cc =>
cc.QueryInterface(Ci.nsIAbCard)
);
equal(childCards.length, 1);
ok(childCards[0].equals(contact));
});
@ -295,7 +350,10 @@ add_task(async function deleteAddressBook() {
ok(!dbFile.exists());
equal([...MailServices.ab.directories].length, DIR_TYPE == 101 ? 4 : 2);
if (DIR_TYPE == 101) {
throws(() => MailServices.ab.getDirectory(`${SCHEME}://${FILE_NAME}`), /.*/);
throws(
() => MailServices.ab.getDirectory(`${SCHEME}://${FILE_NAME}`),
/.*/
);
}
});

Просмотреть файл

@ -10,15 +10,21 @@ var kLDAPTestSpec = "ldap://invalidhost//dc=intranet??sub?(objectclass=*)";
function run_test() {
// If nsIAbLDAPDirectory doesn't exist in our build options, someone has
// specified --disable-ldap
if (!("nsIAbLDAPDirectory" in Ci))
if (!("nsIAbLDAPDirectory" in Ci)) {
return;
}
// Test - Create an LDAP directory
let abUri = MailServices.ab.newAddressBook("test", kLDAPTestSpec, kLDAPDirectory);
let abUri = MailServices.ab.newAddressBook(
"test",
kLDAPTestSpec,
kLDAPDirectory
);
// Test - Check we have the directory.
let abDir = MailServices.ab.getDirectory(kLDAPUriPrefix + abUri)
.QueryInterface(Ci.nsIAbLDAPDirectory);
let abDir = MailServices.ab
.getDirectory(kLDAPUriPrefix + abUri)
.QueryInterface(Ci.nsIAbLDAPDirectory);
// Test - Check various fields
Assert.equal(abDir.dirName, "test");
@ -36,59 +42,149 @@ function run_test() {
let identity = MailServices.accounts.createIdentity();
const localAcTests = [
// Online checks
{ useDir: false, dirSer: "",
idOver: false, idSer: "", idKey: "",
offline: false, result: false },
{ useDir: true, dirSer: abDir.dirPrefId,
idOver: false, idSer: "", idKey: "",
offline: false, result: false },
// Offline checks with and without global prefs set, no identity key
{ useDir: false, dirSer: "",
idOver: false, idSer: "", idKey: "",
offline: true, result: false },
{ useDir: true, dirSer: "",
idOver: false, idSer: "", idKey: "",
offline: true, result: false },
{ useDir: true, dirSer: abDir.dirPrefId,
idOver: false, idSer: "", idKey: "",
offline: true, result: true },
// Offline checks with and without global prefs set, with identity key
{ useDir: false, dirSer: "",
idOver: false, idSer: "", idKey: identity.key,
offline: true, result: false },
{ useDir: true, dirSer: "",
idOver: false, idSer: "", idKey: identity.key,
offline: true, result: false },
{ useDir: true, dirSer: abDir.dirPrefId,
idOver: false, idSer: "", idKey: identity.key,
offline: true, result: true },
// Offline checks, no global prefs, identity ones only
{ useDir: false, dirSer: "",
idOver: true, idSer: "", idKey: identity.key,
offline: true, result: false },
{ useDir: false, dirSer: "",
idOver: true, idSer: kPABData.dirPrefID, idKey: identity.key,
offline: true, result: false },
{ useDir: false, dirSer: "",
idOver: true, idSer: abDir.dirPrefId, idKey: identity.key,
offline: true, result: true },
{ useDir: false, dirSer: "",
idOver: false, idSer: abDir.dirPrefId, idKey: identity.key,
offline: true, result: false },
// Offline checks, global prefs and identity ones
{ useDir: true, dirSer: kPABData.dirPrefID,
idOver: true, idSer: abDir.dirPrefId, idKey: identity.key,
offline: true, result: true },
{ useDir: true, dirSer: abDir.dirPrefId,
idOver: true, idSer: kPABData.dirPrefID, idKey: identity.key,
offline: true, result: false },
// Online checks
{
useDir: false,
dirSer: "",
idOver: false,
idSer: "",
idKey: "",
offline: false,
result: false,
},
{
useDir: true,
dirSer: abDir.dirPrefId,
idOver: false,
idSer: "",
idKey: "",
offline: false,
result: false,
},
// Offline checks with and without global prefs set, no identity key
{
useDir: false,
dirSer: "",
idOver: false,
idSer: "",
idKey: "",
offline: true,
result: false,
},
{
useDir: true,
dirSer: "",
idOver: false,
idSer: "",
idKey: "",
offline: true,
result: false,
},
{
useDir: true,
dirSer: abDir.dirPrefId,
idOver: false,
idSer: "",
idKey: "",
offline: true,
result: true,
},
// Offline checks with and without global prefs set, with identity key
{
useDir: false,
dirSer: "",
idOver: false,
idSer: "",
idKey: identity.key,
offline: true,
result: false,
},
{
useDir: true,
dirSer: "",
idOver: false,
idSer: "",
idKey: identity.key,
offline: true,
result: false,
},
{
useDir: true,
dirSer: abDir.dirPrefId,
idOver: false,
idSer: "",
idKey: identity.key,
offline: true,
result: true,
},
// Offline checks, no global prefs, identity ones only
{
useDir: false,
dirSer: "",
idOver: true,
idSer: "",
idKey: identity.key,
offline: true,
result: false,
},
{
useDir: false,
dirSer: "",
idOver: true,
idSer: kPABData.dirPrefID,
idKey: identity.key,
offline: true,
result: false,
},
{
useDir: false,
dirSer: "",
idOver: true,
idSer: abDir.dirPrefId,
idKey: identity.key,
offline: true,
result: true,
},
{
useDir: false,
dirSer: "",
idOver: false,
idSer: abDir.dirPrefId,
idKey: identity.key,
offline: true,
result: false,
},
// Offline checks, global prefs and identity ones
{
useDir: true,
dirSer: kPABData.dirPrefID,
idOver: true,
idSer: abDir.dirPrefId,
idKey: identity.key,
offline: true,
result: true,
},
{
useDir: true,
dirSer: abDir.dirPrefId,
idOver: true,
idSer: kPABData.dirPrefID,
idKey: identity.key,
offline: true,
result: false,
},
];
function checkAc(element, index, array) {
dump("Testing index " + index + "\n");
Services.prefs.setBoolPref("ldap_2.autoComplete.useDirectory", element.useDir);
Services.prefs.setCharPref("ldap_2.autoComplete.directoryServer", element.dirSer);
Services.prefs.setBoolPref(
"ldap_2.autoComplete.useDirectory",
element.useDir
);
Services.prefs.setCharPref(
"ldap_2.autoComplete.directoryServer",
element.dirSer
);
identity.overrideGlobalPref = element.idOver;
identity.directoryServer = element.idSer;
Services.io.offline = element.offline;

Просмотреть файл

@ -11,19 +11,23 @@ var kLDAPTestSpec = "ldap://invalidhost//dc=intranet??sub?(objectclass=*)";
function run_test() {
// If nsIAbLDAPDirectory doesn't exist in our build options, someone has
// specified --disable-ldap
if (!("nsIAbLDAPDirectory" in Ci))
if (!("nsIAbLDAPDirectory" in Ci)) {
return;
}
// Test - Create an LDAP directory
// Use a UTF-8 based directory name
var abUri =
MailServices.ab.newAddressBook("\u041C\u0435\u043B\u0435\u043D\u043A\u0438",
kLDAPTestSpec, kLDAPDirectory);
var abUri = MailServices.ab.newAddressBook(
"\u041C\u0435\u043B\u0435\u043D\u043A\u0438",
kLDAPTestSpec,
kLDAPDirectory
);
// Test - Check we have the directory.
let abDir = MailServices.ab.getDirectory(kLDAPUriPrefix + abUri)
.QueryInterface(Ci.nsIAbLDAPDirectory);
let abDir = MailServices.ab
.getDirectory(kLDAPUriPrefix + abUri)
.QueryInterface(Ci.nsIAbLDAPDirectory);
// Test - Check various fields
Assert.equal(abDir.dirName, "\u041C\u0435\u043B\u0435\u043D\u043A\u0438");

Просмотреть файл

@ -13,14 +13,20 @@ var kLDAPTestSpec = "ldap://invalidhost//dc=intranet??sub?(objectclass=*)";
function run_test() {
// If nsIAbLDAPDirectory doesn't exist in our build options, someone has
// specified --disable-ldap
if (!("nsIAbLDAPDirectory" in Ci))
if (!("nsIAbLDAPDirectory" in Ci)) {
return;
}
// Test set-up
let abUri = MailServices.ab.newAddressBook("test", kLDAPTestSpec, kLDAPDirectory);
let abUri = MailServices.ab.newAddressBook(
"test",
kLDAPTestSpec,
kLDAPDirectory
);
let abDir = MailServices.ab.getDirectory(kLDAPUriPrefix + abUri)
.QueryInterface(Ci.nsIAbLDAPDirectory);
let abDir = MailServices.ab
.getDirectory(kLDAPUriPrefix + abUri)
.QueryInterface(Ci.nsIAbLDAPDirectory);
const kLDAPFileName = "ldap-1.mab";

Просмотреть файл

@ -10,14 +10,18 @@
function checkLists(childNodes, number) {
var mailListArray = new Array(number);
for (var i = 0; i < number; ++i)
for (var i = 0; i < number; ++i) {
mailListArray[i] = null;
}
// See comment above for matching requirements
while (childNodes.hasMoreElements()) {
var list = childNodes.getNext();
if (list instanceof Ci.nsIAbDirectory &&
list.isMailList && list.dirName.startsWith("TestList")) {
if (
list instanceof Ci.nsIAbDirectory &&
list.isMailList &&
list.dirName.startsWith("TestList")
) {
var index = list.dirName.substr(8, list.dirName.length - 8);
Assert.equal(mailListArray[index - 1], null);
Assert.equal(list.URI, kPABData.URI + "/MailList" + index);
@ -26,7 +30,9 @@ function checkLists(childNodes, number) {
}
}
mailListArray.forEach(function(value) { Assert.notEqual(value, null); });
mailListArray.forEach(function(value) {
Assert.notEqual(value, null);
});
}
function run_test() {
@ -47,8 +53,9 @@ function run_test() {
// Test - Add a new list.
var mailList = Cc["@mozilla.org/addressbook/directoryproperty;1"]
.createInstance(Ci.nsIAbDirectory);
var mailList = Cc[
"@mozilla.org/addressbook/directoryproperty;1"
].createInstance(Ci.nsIAbDirectory);
mailList.isMailList = true;
mailList.dirName = "TestList4";

Просмотреть файл

@ -21,7 +21,13 @@ var abListener = {
},
onItemPropertyChanged(item, property, oldValue, newValue) {
Assert.ok(this.result.length < this.maxResults);
this.result.push(["onItemPropertyChanged", item, property, oldValue, newValue]);
this.result.push([
"onItemPropertyChanged",
item,
property,
oldValue,
newValue,
]);
},
};
@ -54,8 +60,9 @@ add_test(function() {
// Test - add a card
var card = Cc["@mozilla.org/addressbook/cardproperty;1"]
.createInstance(Ci.nsIAbCard);
var card = Cc["@mozilla.org/addressbook/cardproperty;1"].createInstance(
Ci.nsIAbCard
);
card.firstName = "test";
card.primaryEmail = "test@foo.invalid";
@ -83,8 +90,9 @@ add_test(function() {
// Test - delete a card
var cardsToDelete = Cc["@mozilla.org/array;1"]
.createInstance(Ci.nsIMutableArray);
var cardsToDelete = Cc["@mozilla.org/array;1"].createInstance(
Ci.nsIMutableArray
);
cardsToDelete.appendElement(newCard);
@ -99,8 +107,9 @@ add_test(function() {
// Test - add a mailing list
var mailList = Cc["@mozilla.org/addressbook/directoryproperty;1"]
.createInstance(Ci.nsIAbDirectory);
var mailList = Cc[
"@mozilla.org/addressbook/directoryproperty;1"
].createInstance(Ci.nsIAbDirectory);
mailList.isMailList = true;
mailList.dirName = "TestList";
@ -147,7 +156,10 @@ add_test(function() {
Assert.equal(abListener.result[0][0], "onItemRemoved");
Assert.equal(abListener.result[0][1], AB);
Assert.equal(abListener.result[1][0], "onItemRemoved");
Assert.equal(abListener.result[1][1].QueryInterface(Ci.nsIAbDirectory).UID, book.UID);
Assert.equal(
abListener.result[1][1].QueryInterface(Ci.nsIAbDirectory).UID,
book.UID
);
Assert.equal(abListener.result[2][0], "onItemRemoved");
Assert.equal(abListener.result[2][1], AB);
@ -172,23 +184,30 @@ add_test(function() {
});
add_test(function() {
let dirName = MailServices.ab.newAddressBook("TestBook", "", kPABData.dirType);
let dirName = MailServices.ab.newAddressBook(
"TestBook",
"",
kPABData.dirType
);
let AB = MailServices.ab.getDirectoryFromId(dirName);
let mailList = Cc["@mozilla.org/addressbook/directoryproperty;1"]
.createInstance(Ci.nsIAbDirectory);
let mailList = Cc[
"@mozilla.org/addressbook/directoryproperty;1"
].createInstance(Ci.nsIAbDirectory);
mailList.isMailList = true;
mailList.dirName = "TestList";
mailList = AB.addMailList(mailList);
let card1 = Cc["@mozilla.org/addressbook/cardproperty;1"]
.createInstance(Ci.nsIAbCard);
let card1 = Cc["@mozilla.org/addressbook/cardproperty;1"].createInstance(
Ci.nsIAbCard
);
card1.firstName = "test1";
card1.primaryEmail = "test1@foo.invalid";
card1 = AB.addCard(card1);
let card2 = Cc["@mozilla.org/addressbook/cardproperty;1"]
.createInstance(Ci.nsIAbCard);
let card2 = Cc["@mozilla.org/addressbook/cardproperty;1"].createInstance(
Ci.nsIAbCard
);
card2.firstName = "test2";
card2.primaryEmail = "test2@foo.invalid";
card2 = AB.addCard(card2);
@ -200,8 +219,9 @@ add_test(function() {
abObserver.maxResults = 0;
abObserver.result = [];
let cardsToDelete = Cc["@mozilla.org/array;1"]
.createInstance(Ci.nsIMutableArray);
let cardsToDelete = Cc["@mozilla.org/array;1"].createInstance(
Ci.nsIMutableArray
);
cardsToDelete.appendElement(card1);
AB.deleteCards(cardsToDelete);

Просмотреть файл

@ -20,8 +20,9 @@ acObserver.prototype = {
function run_test() {
// Test - Create a new search component
var acs = Cc["@mozilla.org/autocomplete/search;1?name=mydomain"]
.getService(Ci.nsIAutoCompleteSearch);
var acs = Cc["@mozilla.org/autocomplete/search;1?name=mydomain"].getService(
Ci.nsIAutoCompleteSearch
);
var obs = new acObserver();
let obsNews = new acObserver();
@ -36,8 +37,14 @@ function run_test() {
// Set up autocomplete parameters
let params = JSON.stringify({ idKey: identity.key, type: "addr_to" });
let paramsNews = JSON.stringify({ idKey: identity.key, type: "addr_newsgroups" });
let paramsFollowup = JSON.stringify({ idKey: identity.key, type: "addr_followup" });
let paramsNews = JSON.stringify({
idKey: identity.key,
type: "addr_newsgroups",
});
let paramsFollowup = JSON.stringify({
idKey: identity.key,
type: "addr_followup",
});
// Test - Valid search - this should return no results (autocomplete disabled)
acs.startSearch("test", params, null, obs);
@ -103,7 +110,6 @@ function run_test() {
acs.startSearch("a@b", paramsFollowup, null, obsFollowup);
Assert.ok(obsFollowup._result == null || obsFollowup._result.matchCount == 0);
// Test - Add default domain
acs.startSearch("test1", params, null, obs);

Просмотреть файл

@ -12,71 +12,94 @@ var ACR = Ci.nsIAutoCompleteResult;
// on a pattern rather just doing the odd spot check.
//
// Note the expected arrays are in expected sort order as well.
var results = [ { email: "d <ema@foo.invalid>", dirName: kPABData.dirName }, // 0
{ email: "di <emai@foo.invalid>", dirName: kPABData.dirName }, // 1
{ email: "dis <email@foo.invalid>", dirName: kPABData.dirName }, // 2
{ email: "disp <e@foo.invalid>", dirName: kPABData.dirName }, // 3
{ email: "displ <em@foo.invalid>", dirName: kPABData.dirName }, // 4
{ email: "DisplayName1 <PrimaryEmail1@test.invalid>", // 5
dirName: kCABData.dirName },
{ email: "t <list>", dirName: kPABData.dirName }, // 6
{ email: "te <lis>", dirName: kPABData.dirName }, // 7
{ email: "tes <li>", dirName: kPABData.dirName }, // 8
// this contact has a nickname of "abcdef"
{ email: "test <l>", dirName: kPABData.dirName }, // 9
];
var firstNames = [ { search: "f", expected: [0, 1, 2, 3, 4, 5, 9] },
{ search: "fi", expected: [0, 1, 3, 4, 5] },
{ search: "fir", expected: [0, 1, 4, 5] },
{ search: "firs", expected: [0, 1, 5] },
{ search: "first", expected: [1, 5] },
{ search: "firstn", expected: [5] } ];
var results = [
{ email: "d <ema@foo.invalid>", dirName: kPABData.dirName }, // 0
{ email: "di <emai@foo.invalid>", dirName: kPABData.dirName }, // 1
{ email: "dis <email@foo.invalid>", dirName: kPABData.dirName }, // 2
{ email: "disp <e@foo.invalid>", dirName: kPABData.dirName }, // 3
{ email: "displ <em@foo.invalid>", dirName: kPABData.dirName }, // 4
{
email: "DisplayName1 <PrimaryEmail1@test.invalid>", // 5
dirName: kCABData.dirName,
},
{ email: "t <list>", dirName: kPABData.dirName }, // 6
{ email: "te <lis>", dirName: kPABData.dirName }, // 7
{ email: "tes <li>", dirName: kPABData.dirName }, // 8
// this contact has a nickname of "abcdef"
{ email: "test <l>", dirName: kPABData.dirName }, // 9
];
var firstNames = [
{ search: "f", expected: [0, 1, 2, 3, 4, 5, 9] },
{ search: "fi", expected: [0, 1, 3, 4, 5] },
{ search: "fir", expected: [0, 1, 4, 5] },
{ search: "firs", expected: [0, 1, 5] },
{ search: "first", expected: [1, 5] },
{ search: "firstn", expected: [5] },
];
var lastNames = [ { search: "l", expected: [6, 7, 8, 9, 0, 1, 2, 3, 4, 5] },
{ search: "la", expected: [0, 2, 3, 4, 5] },
{ search: "las", expected: [0, 3, 4, 5] },
{ search: "last", expected: [0, 4, 5] },
{ search: "lastn", expected: [0, 5] },
{ search: "lastna", expected: [5]} ];
var lastNames = [
{ search: "l", expected: [6, 7, 8, 9, 0, 1, 2, 3, 4, 5] },
{ search: "la", expected: [0, 2, 3, 4, 5] },
{ search: "las", expected: [0, 3, 4, 5] },
{ search: "last", expected: [0, 4, 5] },
{ search: "lastn", expected: [0, 5] },
{ search: "lastna", expected: [5] },
];
var displayNames = [ { search: "d", expected: [0, 1, 2, 3, 4, 5, 9] },
{ search: "di", expected: [1, 2, 3, 4, 5] },
{ search: "dis", expected: [2, 3, 4, 5] },
{ search: "disp", expected: [3, 4, 5]},
{ search: "displ", expected: [4, 5]},
{ search: "displa", expected: [5]} ];
var displayNames = [
{ search: "d", expected: [0, 1, 2, 3, 4, 5, 9] },
{ search: "di", expected: [1, 2, 3, 4, 5] },
{ search: "dis", expected: [2, 3, 4, 5] },
{ search: "disp", expected: [3, 4, 5] },
{ search: "displ", expected: [4, 5] },
{ search: "displa", expected: [5] },
];
var nickNames = [ { search: "n", expected: [4, 0, 1, 2, 3, 5] },
{ search: "ni", expected: [0, 1, 2, 3, 5] },
{ search: "nic", expected: [1, 2, 3, 5] },
{ search: "nick", expected: [2, 3, 5] },
{ search: "nickn", expected: [3, 5] },
{ search: "nickna", expected: [5] } ];
var nickNames = [
{ search: "n", expected: [4, 0, 1, 2, 3, 5] },
{ search: "ni", expected: [0, 1, 2, 3, 5] },
{ search: "nic", expected: [1, 2, 3, 5] },
{ search: "nick", expected: [2, 3, 5] },
{ search: "nickn", expected: [3, 5] },
{ search: "nickna", expected: [5] },
];
var emails = [ { search: "e", expected: [0, 1, 2, 3, 4, 5, 7, 8, 9] },
{ search: "em", expected: [0, 1, 2, 4, 5] },
{ search: "ema", expected: [0, 1, 2, 5] },
{ search: "emai", expected: [1, 2, 5] },
{ search: "email", expected: [2, 5] } ];
var emails = [
{ search: "e", expected: [0, 1, 2, 3, 4, 5, 7, 8, 9] },
{ search: "em", expected: [0, 1, 2, 4, 5] },
{ search: "ema", expected: [0, 1, 2, 5] },
{ search: "emai", expected: [1, 2, 5] },
{ search: "email", expected: [2, 5] },
];
// "l" case tested above
var lists = [ { search: "li", expected: [6, 7, 8, 0, 1, 2, 3, 4, 5] },
{ search: "lis", expected: [6, 7] },
{ search: "list", expected: [6] },
{ search: "t", expected: [6, 7, 8, 9, 0, 1, 4, 5] },
{ search: "te", expected: [7, 8, 9, 5] },
{ search: "tes", expected: [8, 9, 5] },
{ search: "test", expected: [9, 5] },
{ search: "abcdef", expected: [9] }, // Bug 441586
];
var lists = [
{ search: "li", expected: [6, 7, 8, 0, 1, 2, 3, 4, 5] },
{ search: "lis", expected: [6, 7] },
{ search: "list", expected: [6] },
{ search: "t", expected: [6, 7, 8, 9, 0, 1, 4, 5] },
{ search: "te", expected: [7, 8, 9, 5] },
{ search: "tes", expected: [8, 9, 5] },
{ search: "test", expected: [9, 5] },
{ search: "abcdef", expected: [9] }, // Bug 441586
];
var bothNames = [ { search: "f l", expected: [0, 1, 2, 3, 4, 5, 9] },
{ search: "l f", expected: [0, 1, 2, 3, 4, 5, 9] },
{ search: "firstn lastna", expected: [5] },
{ search: "lastna firstna", expected: [5] } ];
var bothNames = [
{ search: "f l", expected: [0, 1, 2, 3, 4, 5, 9] },
{ search: "l f", expected: [0, 1, 2, 3, 4, 5, 9] },
{ search: "firstn lastna", expected: [5] },
{ search: "lastna firstna", expected: [5] },
];
var inputs = [ firstNames, lastNames, displayNames, nickNames, emails,
lists, bothNames ];
var inputs = [
firstNames,
lastNames,
displayNames,
nickNames,
emails,
lists,
bothNames,
];
function acObserver() {}
@ -92,91 +115,91 @@ acObserver.prototype = {
var PAB_CARD_DATA = [
{
"FirstName": "firs",
"LastName": "lastn",
"DisplayName": "d",
"NickName": "ni",
"PrimaryEmail": "ema@foo.invalid",
"PreferDisplayName": true,
"PopularityIndex": 0,
FirstName: "firs",
LastName: "lastn",
DisplayName: "d",
NickName: "ni",
PrimaryEmail: "ema@foo.invalid",
PreferDisplayName: true,
PopularityIndex: 0,
},
{
"FirstName": "first",
"LastName": "l",
"DisplayName": "di",
"NickName": "nic",
"PrimaryEmail": "emai@foo.invalid",
"PreferDisplayName": true,
"PopularityIndex": 0,
FirstName: "first",
LastName: "l",
DisplayName: "di",
NickName: "nic",
PrimaryEmail: "emai@foo.invalid",
PreferDisplayName: true,
PopularityIndex: 0,
},
{
"FirstName": "f",
"LastName": "la",
"DisplayName": "dis",
"NickName": "nick",
"PrimaryEmail": "email@foo.invalid",
"PreferDisplayName": true,
"PopularityIndex": 0,
FirstName: "f",
LastName: "la",
DisplayName: "dis",
NickName: "nick",
PrimaryEmail: "email@foo.invalid",
PreferDisplayName: true,
PopularityIndex: 0,
},
{
"FirstName": "fi",
"LastName": "las",
"DisplayName": "disp",
"NickName": "nickn",
"PrimaryEmail": "e@foo.invalid",
"PreferDisplayName": true,
"PopularityIndex": 0,
FirstName: "fi",
LastName: "las",
DisplayName: "disp",
NickName: "nickn",
PrimaryEmail: "e@foo.invalid",
PreferDisplayName: true,
PopularityIndex: 0,
},
{
"FirstName": "fir",
"LastName": "last",
"DisplayName": "displ",
"NickName": "n",
"PrimaryEmail": "em@foo.invalid",
"PreferDisplayName": true,
"PopularityIndex": 0,
FirstName: "fir",
LastName: "last",
DisplayName: "displ",
NickName: "n",
PrimaryEmail: "em@foo.invalid",
PreferDisplayName: true,
PopularityIndex: 0,
},
];
var PAB_LIST_DATA = [
var PAB_LIST_DATA = [
{
"dirName": "t",
"listNickName": null,
"description": "list",
dirName: "t",
listNickName: null,
description: "list",
},
{
"dirName": "te",
"listNickName": null,
"description": "lis",
dirName: "te",
listNickName: null,
description: "lis",
},
{
"dirName": "tes",
"listNickName": null,
"description": "li",
dirName: "tes",
listNickName: null,
description: "li",
},
{
"dirName": "test",
"listNickName": "abcdef",
"description": "l",
dirName: "test",
listNickName: "abcdef",
description: "l",
},
];
var CAB_CARD_DATA = [
{
"FirstName": "FirstName1",
"LastName": "LastName1",
"DisplayName": "DisplayName1",
"NickName": "NickName1",
"PrimaryEmail": "PrimaryEmail1@test.invalid",
"PreferDisplayName": true,
"PopularityIndex": 0,
FirstName: "FirstName1",
LastName: "LastName1",
DisplayName: "DisplayName1",
NickName: "NickName1",
PrimaryEmail: "PrimaryEmail1@test.invalid",
PreferDisplayName: true,
PopularityIndex: 0,
},
{
"FirstName": "Empty",
"LastName": "Email",
"DisplayName": "Empty Email",
"PreferDisplayName": true,
"PopularityIndex": 0,
FirstName: "Empty",
LastName: "Email",
DisplayName: "Empty Email",
PreferDisplayName: true,
PopularityIndex: 0,
},
];
@ -196,8 +219,9 @@ function setupAddressBookData(aDirURI, aCardData, aMailListData) {
}
aCardData.forEach(function(cd) {
let card = Cc["@mozilla.org/addressbook/cardproperty;1"]
.createInstance(Ci.nsIAbCard);
let card = Cc["@mozilla.org/addressbook/cardproperty;1"].createInstance(
Ci.nsIAbCard
);
for (var prop in cd) {
card.setProperty(prop, cd[prop]);
}
@ -205,8 +229,9 @@ function setupAddressBookData(aDirURI, aCardData, aMailListData) {
});
aMailListData.forEach(function(ld) {
let list = Cc["@mozilla.org/addressbook/directoryproperty;1"]
.createInstance(Ci.nsIAbDirectory);
let list = Cc[
"@mozilla.org/addressbook/directoryproperty;1"
].createInstance(Ci.nsIAbDirectory);
list.isMailList = true;
for (var prop in ld) {
list[prop] = ld[prop];
@ -228,8 +253,9 @@ function run_test() {
// Test - Create a new search component
var acs = Cc["@mozilla.org/autocomplete/search;1?name=addrbook"]
.getService(Ci.nsIAutoCompleteSearch);
var acs = Cc["@mozilla.org/autocomplete/search;1?name=addrbook"].getService(
Ci.nsIAutoCompleteSearch
);
var obs = new acObserver();
let obsNews = new acObserver();
@ -239,9 +265,9 @@ function run_test() {
Services.prefs.setBoolPref("mail.enable_autocomplete", false);
let param = JSON.stringify({ type: "addr_to" });
let paramNews = JSON.stringify({ type: "addr_newsgroups" });
let paramFollowup = JSON.stringify({ type: "addr_followup" });
let param = JSON.stringify({ type: "addr_to" });
let paramNews = JSON.stringify({ type: "addr_newsgroups" });
let paramFollowup = JSON.stringify({ type: "addr_followup" });
acs.startSearch("abc", param, null, obs);
@ -357,8 +383,14 @@ function run_test() {
}
for (let i = 0; i < element.expected.length; i++) {
print("... expected " + i + " (result " + element.expected[i] + "): " +
results[element.expected[i]].email);
print(
"... expected " +
i +
" (result " +
element.expected[i] +
"): " +
results[element.expected[i]].email
);
}
Assert.equal(obs._search, acs);
@ -369,9 +401,18 @@ function run_test() {
Assert.equal(obs._result.defaultIndex, 0);
for (let i = 0; i < element.expected.length; ++i) {
Assert.equal(obs._result.getValueAt(i), results[element.expected[i]].email);
Assert.equal(obs._result.getLabelAt(i), results[element.expected[i]].email);
Assert.equal(obs._result.getCommentAt(i), results[element.expected[i]].dirName);
Assert.equal(
obs._result.getValueAt(i),
results[element.expected[i]].email
);
Assert.equal(
obs._result.getLabelAt(i),
results[element.expected[i]].email
);
Assert.equal(
obs._result.getCommentAt(i),
results[element.expected[i]].dirName
);
Assert.equal(obs._result.getStyleAt(i), "local-abook");
Assert.equal(obs._result.getImageAt(i), "");
}
@ -391,36 +432,39 @@ function run_test() {
while (childCards.hasMoreElements()) {
var card = childCards.getNext().QueryInterface(Ci.nsIAbCard);
if (card.isMailList)
if (card.isMailList) {
continue;
}
switch (card.displayName) {
case "dis": // 2
case "disp": // 3
card.setProperty("PopularityIndex", 4);
break;
case "displ": // 4
card.setProperty("PopularityIndex", 5);
break;
case "d": // 0
card.setProperty("PopularityIndex", 1);
break;
case "di": // 1
card.setProperty("PopularityIndex", 20);
break;
default:
break;
case "dis": // 2
case "disp": // 3
card.setProperty("PopularityIndex", 4);
break;
case "displ": // 4
card.setProperty("PopularityIndex", 5);
break;
case "d": // 0
card.setProperty("PopularityIndex", 1);
break;
case "di": // 1
card.setProperty("PopularityIndex", 20);
break;
default:
break;
}
pab.modifyCard(card);
}
const popularitySearch = [ { search: "d", expected: [1, 4, 2, 3, 0, 5, 9] },
{ search: "di", expected: [1, 4, 2, 3, 5] },
{ search: "dis", expected: [4, 2, 3, 5] },
{ search: "disp", expected: [4, 3, 5] },
{ search: "displ", expected: [4, 5] },
{ search: "displa", expected: [5] } ];
const popularitySearch = [
{ search: "d", expected: [1, 4, 2, 3, 0, 5, 9] },
{ search: "di", expected: [1, 4, 2, 3, 5] },
{ search: "dis", expected: [4, 2, 3, 5] },
{ search: "disp", expected: [4, 3, 5] },
{ search: "displ", expected: [4, 5] },
{ search: "displa", expected: [5] },
];
popularitySearch.forEach(checkInputItem);
}

Просмотреть файл

@ -8,9 +8,9 @@
* books.
*/
var {
getModelQuery,
} = ChromeUtils.import("resource:///modules/ABQueryUtils.jsm");
var { getModelQuery } = ChromeUtils.import(
"resource:///modules/ABQueryUtils.jsm"
);
// taken from nsAbAutoCompleteSearch.js
var ACR = Ci.nsIAutoCompleteResult;
@ -63,8 +63,7 @@ nsAbAutoCompleteResult.prototype = {
return this.getValueAt(aIndex);
},
removeValueAt: function removeValueAt(aRowIndex, aRemoveFromDB) {
},
removeValueAt: function removeValueAt(aRowIndex, aRemoveFromDB) {},
// nsIAbAutoCompleteResult
@ -83,8 +82,9 @@ nsAbAutoCompleteResult.prototype = {
};
function createCard(chars, popularity) {
var card = Cc["@mozilla.org/addressbook/cardproperty;1"]
.createInstance(Ci.nsIAbCard);
var card = Cc["@mozilla.org/addressbook/cardproperty;1"].createInstance(
Ci.nsIAbCard
);
card.firstName = "firstName".slice(0, chars);
card.lastName = "lastName".slice(0, chars);
@ -95,15 +95,21 @@ function createCard(chars, popularity) {
return card;
}
var results = [ { email: "d <e@foo.invalid>", dirName: kPABData.dirName },
{ email: "di <em@foo.invalid>", dirName: kPABData.dirName },
{ email: "dis <ema@foo.invalid>", dirName: kPABData.dirName } ];
var results = [
{ email: "d <e@foo.invalid>", dirName: kPABData.dirName },
{ email: "di <em@foo.invalid>", dirName: kPABData.dirName },
{ email: "dis <ema@foo.invalid>", dirName: kPABData.dirName },
];
var firstNames = [ { search: "fi", expected: [1, 2] },
{ search: "fir", expected: [2] } ];
var firstNames = [
{ search: "fi", expected: [1, 2] },
{ search: "fir", expected: [2] },
];
var lastNames = [ { search: "la", expected: [1, 2] },
{ search: "las", expected: [2] } ];
var lastNames = [
{ search: "la", expected: [1, 2] },
{ search: "las", expected: [2] },
];
var inputs = [firstNames, lastNames];
@ -122,8 +128,9 @@ acObserver.prototype = {
function run_test() {
// Test - Create a new search component
var acs = Cc["@mozilla.org/autocomplete/search;1?name=addrbook"]
.getService(Ci.nsIAutoCompleteSearch);
var acs = Cc["@mozilla.org/autocomplete/search;1?name=addrbook"].getService(
Ci.nsIAutoCompleteSearch
);
var obs = new acObserver();
@ -145,12 +152,16 @@ function run_test() {
});
}
// Test - Matches
// Now check multiple matches
function checkInputItem(element, index, array) {
acs.startSearch(element.search, JSON.stringify({ type: "addr_to", idKey: "" }), lastResult, obs);
acs.startSearch(
element.search,
JSON.stringify({ type: "addr_to", idKey: "" }),
lastResult,
obs
);
Assert.equal(obs._search, acs);
Assert.equal(obs._result.searchString, element.search);
@ -159,9 +170,18 @@ function run_test() {
Assert.equal(obs._result.matchCount, element.expected.length);
for (let i = 0; i < element.expected.length; ++i) {
Assert.equal(obs._result.getValueAt(i), results[element.expected[i]].email);
Assert.equal(obs._result.getLabelAt(i), results[element.expected[i]].email);
Assert.equal(obs._result.getCommentAt(i), results[element.expected[i]].dirName);
Assert.equal(
obs._result.getValueAt(i),
results[element.expected[i]].email
);
Assert.equal(
obs._result.getLabelAt(i),
results[element.expected[i]].email
);
Assert.equal(
obs._result.getCommentAt(i),
results[element.expected[i]].dirName
);
Assert.equal(obs._result.getStyleAt(i), "local-abook");
Assert.equal(obs._result.getImageAt(i), "");
}

Просмотреть файл

@ -6,27 +6,72 @@
var ACR = Ci.nsIAutoCompleteResult;
var cards = [
{ email: "test@foo.invalid", displayName: "",
popularityIndex: 0, firstName: "test0", value: "test@foo.invalid" },
{ email: "test@foo.invalid", displayName: "",
popularityIndex: 1, firstName: "test1", value: "test@foo.invalid" },
{ email: "abc@foo.invalid", displayName: "",
popularityIndex: 1, firstName: "test2", value: "abc@foo.invalid" },
{ email: "foo1@foo.invalid", displayName: "d",
popularityIndex: 0, firstName: "first1", value: "d <foo1@foo.invalid>" },
{ email: "foo2@foo.invalid", displayName: "di",
popularityIndex: 1, firstName: "first1", value: "di <foo2@foo.invalid>" },
{ email: "foo3@foo.invalid", displayName: "dis",
popularityIndex: 2, firstName: "first2", value: "dis <foo3@foo.invalid>" },
{ email: "foo2@foo.invalid", displayName: "di",
popularityIndex: 3, firstName: "first2", value: "di <foo2@foo.invalid>" },
{
email: "test@foo.invalid",
displayName: "",
popularityIndex: 0,
firstName: "test0",
value: "test@foo.invalid",
},
{
email: "test@foo.invalid",
displayName: "",
popularityIndex: 1,
firstName: "test1",
value: "test@foo.invalid",
},
{
email: "abc@foo.invalid",
displayName: "",
popularityIndex: 1,
firstName: "test2",
value: "abc@foo.invalid",
},
{
email: "foo1@foo.invalid",
displayName: "d",
popularityIndex: 0,
firstName: "first1",
value: "d <foo1@foo.invalid>",
},
{
email: "foo2@foo.invalid",
displayName: "di",
popularityIndex: 1,
firstName: "first1",
value: "di <foo2@foo.invalid>",
},
{
email: "foo3@foo.invalid",
displayName: "dis",
popularityIndex: 2,
firstName: "first2",
value: "dis <foo3@foo.invalid>",
},
{
email: "foo2@foo.invalid",
displayName: "di",
popularityIndex: 3,
firstName: "first2",
value: "di <foo2@foo.invalid>",
},
// this just tests we can search for the special chars '(' and ')', bug 749097
{ email: "bracket@not.invalid", secondEmail: "h@not.invalid", firstName: "Mr.",
displayName: "Mr. (Bracket)", value: "Mr. (Bracket) <bracket@not.invalid>",
popularityIndex: 2 },
{ email: "mr@(bracket).not.invalid", secondEmail: "bracket@not.invalid", firstName: "Mr.",
displayName: "Mr. Bracket", value: "Mr. Bracket <mr@(bracket).not.invalid>",
popularityIndex: 1 },
{
email: "bracket@not.invalid",
secondEmail: "h@not.invalid",
firstName: "Mr.",
displayName: "Mr. (Bracket)",
value: "Mr. (Bracket) <bracket@not.invalid>",
popularityIndex: 2,
},
{
email: "mr@(bracket).not.invalid",
secondEmail: "bracket@not.invalid",
firstName: "Mr.",
displayName: "Mr. Bracket",
value: "Mr. Bracket <mr@(bracket).not.invalid>",
popularityIndex: 1,
},
];
var duplicates = [
@ -35,7 +80,6 @@ var duplicates = [
{ search: "(bracket)", expected: [7, 8] },
];
function acObserver() {}
acObserver.prototype = {
@ -58,8 +102,9 @@ function run_test() {
let ab = MailServices.ab.getDirectory(kPABData.URI);
function createAndAddCard(element) {
var card = Cc["@mozilla.org/addressbook/cardproperty;1"]
.createInstance(Ci.nsIAbCard);
var card = Cc["@mozilla.org/addressbook/cardproperty;1"].createInstance(
Ci.nsIAbCard
);
card.primaryEmail = element.email;
card.displayName = element.displayName;
@ -73,22 +118,34 @@ function run_test() {
// Test - duplicate elements
var acs = Cc["@mozilla.org/autocomplete/search;1?name=addrbook"]
.getService(Ci.nsIAutoCompleteSearch);
var acs = Cc["@mozilla.org/autocomplete/search;1?name=addrbook"].getService(
Ci.nsIAutoCompleteSearch
);
var obs = new acObserver();
function checkInputItem(element, index, array) {
print("Search #" + index + ": search=" + element.search);
acs.startSearch(element.search, JSON.stringify({ type: "addr_to" }), null, obs);
acs.startSearch(
element.search,
JSON.stringify({ type: "addr_to" }),
null,
obs
);
for (let i = 0; i < obs._result.matchCount; i++) {
print("... got " + i + ": " + obs._result.getValueAt(i));
}
for (let i = 0; i < element.expected.length; i++) {
print("... expected " + i + " (card " + element.expected[i] + "): " +
cards[element.expected[i]].value);
print(
"... expected " +
i +
" (card " +
element.expected[i] +
"): " +
cards[element.expected[i]].value
);
}
Assert.equal(obs._search, acs);
@ -104,8 +161,10 @@ function run_test() {
Assert.equal(obs._result.getStyleAt(i), "local-abook");
Assert.equal(obs._result.getImageAt(i), "");
obs._result.QueryInterface(Ci.nsIAbAutoCompleteResult);
Assert.equal(obs._result.getCardAt(i).firstName,
cards[element.expected[i]].firstName);
Assert.equal(
obs._result.getCardAt(i).firstName,
cards[element.expected[i]].firstName
);
}
}

Просмотреть файл

@ -6,84 +6,139 @@ var ACR = Ci.nsIAutoCompleteResult;
var cards = [
// Basic tests for primary and secondary emails.
{ email: "primary@test.invalid", secondEmail: "second@test.invalid",
firstName: "" },
{ email: "test1@test.invalid", secondEmail: "test2@test.invalid",
firstName: "firstName" },
{ email: "bar1@test.invalid", secondEmail: "bar2@test.invalid",
firstName: "sweet" },
{ email: "boo1@test.invalid", secondEmail: "boo2@test.invalid",
firstName: "sample" },
{ email: "name@test.invalid", secondEmail: "thename@test.invalid",
firstName: "thename" },
{
email: "primary@test.invalid",
secondEmail: "second@test.invalid",
firstName: "",
},
{
email: "test1@test.invalid",
secondEmail: "test2@test.invalid",
firstName: "firstName",
},
{
email: "bar1@test.invalid",
secondEmail: "bar2@test.invalid",
firstName: "sweet",
},
{
email: "boo1@test.invalid",
secondEmail: "boo2@test.invalid",
firstName: "sample",
},
{
email: "name@test.invalid",
secondEmail: "thename@test.invalid",
firstName: "thename",
},
// Test to check correct sorting of primary and secondary emails.
{ email: "foo_b@test.invalid", secondEmail: "foo_a@test.invalid",
displayName: "sortbasic" },
{ email: "d@test.invalid", secondEmail: "e@test.invalid",
displayName: "testsort" },
{ email: "c@test.invalid", secondEmail: "a@test.invalid",
displayName: "testsort" },
{
email: "foo_b@test.invalid",
secondEmail: "foo_a@test.invalid",
displayName: "sortbasic",
},
{
email: "d@test.invalid",
secondEmail: "e@test.invalid",
displayName: "testsort",
},
{
email: "c@test.invalid",
secondEmail: "a@test.invalid",
displayName: "testsort",
},
// "2testsort" does the same as "testsort" but turns the cards around to
// ensure the order is always consistent.
{ email: "c@test.invalid", secondEmail: "a@test.invalid",
displayName: "2testsort" },
{ email: "d@test.invalid", secondEmail: "e@test.invalid",
displayName: "2testsort" },
{ email: "g@test.invalid", secondEmail: "f@test.invalid",
displayName: "3testsort", popularityIndex: 3 },
{ email: "j@test.invalid", secondEmail: "h@test.invalid",
displayName: "3testsort", popularityIndex: 5 },
{
email: "c@test.invalid",
secondEmail: "a@test.invalid",
displayName: "2testsort",
},
{
email: "d@test.invalid",
secondEmail: "e@test.invalid",
displayName: "2testsort",
},
{
email: "g@test.invalid",
secondEmail: "f@test.invalid",
displayName: "3testsort",
popularityIndex: 3,
},
{
email: "j@test.invalid",
secondEmail: "h@test.invalid",
displayName: "3testsort",
popularityIndex: 5,
},
// Add a contact that matches, but has no email. Should not show up.
{ displayName: "primaryX" },
];
// These are for the initial search
var searches = [ "primary", "second", "firstName", "thename", "sortbasic",
"testsort", "2testsort", "3testsort" ];
var searches = [
"primary",
"second",
"firstName",
"thename",
"sortbasic",
"testsort",
"2testsort",
"3testsort",
];
var expectedResults = [ [ "primary@test.invalid",
"second@test.invalid"], // searching for primary/second returns
[ "second@test.invalid", // both the emails as the new search query
"primary@test.invalid" ], // looks in both the fields.
[ "test1@test.invalid",
"test2@test.invalid" ],
[ "thename@test.invalid",
"name@test.invalid"],
[ "sortbasic <foo_b@test.invalid>",
"sortbasic <foo_a@test.invalid>" ],
[ "testsort <c@test.invalid>",
"testsort <a@test.invalid>",
"testsort <d@test.invalid>",
"testsort <e@test.invalid>",
"3testsort <j@test.invalid>",
"3testsort <h@test.invalid>",
"3testsort <g@test.invalid>",
"3testsort <f@test.invalid>",
"2testsort <c@test.invalid>",
"2testsort <a@test.invalid>",
"2testsort <d@test.invalid>",
"2testsort <e@test.invalid>"],
[ "2testsort <c@test.invalid>",
"2testsort <a@test.invalid>",
"2testsort <d@test.invalid>",
"2testsort <e@test.invalid>" ],
[ "3testsort <j@test.invalid>",
"3testsort <h@test.invalid>",
"3testsort <g@test.invalid>",
"3testsort <f@test.invalid>" ] ];
var expectedResults = [
["primary@test.invalid", "second@test.invalid"], // searching for primary/second returns
[
"second@test.invalid", // both the emails as the new search query
"primary@test.invalid",
], // looks in both the fields.
["test1@test.invalid", "test2@test.invalid"],
["thename@test.invalid", "name@test.invalid"],
["sortbasic <foo_b@test.invalid>", "sortbasic <foo_a@test.invalid>"],
[
"testsort <c@test.invalid>",
"testsort <a@test.invalid>",
"testsort <d@test.invalid>",
"testsort <e@test.invalid>",
"3testsort <j@test.invalid>",
"3testsort <h@test.invalid>",
"3testsort <g@test.invalid>",
"3testsort <f@test.invalid>",
"2testsort <c@test.invalid>",
"2testsort <a@test.invalid>",
"2testsort <d@test.invalid>",
"2testsort <e@test.invalid>",
],
[
"2testsort <c@test.invalid>",
"2testsort <a@test.invalid>",
"2testsort <d@test.invalid>",
"2testsort <e@test.invalid>",
],
[
"3testsort <j@test.invalid>",
"3testsort <h@test.invalid>",
"3testsort <g@test.invalid>",
"3testsort <f@test.invalid>",
],
];
// These are for subsequent searches - reducing the number of results.
var reductionSearches = [ "b", "bo", "boo2" ];
var reductionSearches = ["b", "bo", "boo2"];
var reductionExpectedResults = [ [ "bar1@test.invalid",
"bar2@test.invalid",
"boo1@test.invalid",
"boo2@test.invalid",
"sortbasic <foo_b@test.invalid>",
"sortbasic <foo_a@test.invalid>" ],
[ "boo1@test.invalid",
"boo2@test.invalid" ],
[ "boo2@test.invalid" ] ];
var reductionExpectedResults = [
[
"bar1@test.invalid",
"bar2@test.invalid",
"boo1@test.invalid",
"boo2@test.invalid",
"sortbasic <foo_b@test.invalid>",
"sortbasic <foo_a@test.invalid>",
],
["boo1@test.invalid", "boo2@test.invalid"],
["boo2@test.invalid"],
];
function acObserver() {}
@ -107,15 +162,18 @@ function run_test() {
let ab = MailServices.ab.getDirectory(kPABData.URI);
function createAndAddCard(element) {
var card = Cc["@mozilla.org/addressbook/cardproperty;1"]
.createInstance(Ci.nsIAbCard);
var card = Cc["@mozilla.org/addressbook/cardproperty;1"].createInstance(
Ci.nsIAbCard
);
card.primaryEmail = element.email;
if ("secondEmail" in element)
if ("secondEmail" in element) {
card.setProperty("SecondEmail", element.secondEmail);
}
card.displayName = element.displayName;
if ("popularityIndex" in element)
if ("popularityIndex" in element) {
card.setProperty("PopularityIndex", element.popularityIndex);
}
card.firstName = element.firstName;
ab.addCard(card);
@ -123,8 +181,9 @@ function run_test() {
cards.forEach(createAndAddCard);
var acs = Cc["@mozilla.org/autocomplete/search;1?name=addrbook"]
.getService(Ci.nsIAutoCompleteSearch);
var acs = Cc["@mozilla.org/autocomplete/search;1?name=addrbook"].getService(
Ci.nsIAutoCompleteSearch
);
var obs = new acObserver();
@ -132,7 +191,12 @@ function run_test() {
function checkSearch(element, index, array) {
print("Search #" + index + ": search=" + element);
acs.startSearch(element, JSON.stringify({ type: "addr_to", idKey: "" }), null, obs);
acs.startSearch(
element,
JSON.stringify({ type: "addr_to", idKey: "" }),
null,
obs
);
for (let i = 0; i < obs._result.matchCount; i++) {
print("... got " + i + ": " + obs._result.getValueAt(i));
@ -161,17 +225,31 @@ function run_test() {
var lastResult = null;
function checkReductionSearch(element, index, array) {
acs.startSearch(element, JSON.stringify({ type: "addr_to", idKey: "" }), lastResult, obs);
acs.startSearch(
element,
JSON.stringify({ type: "addr_to", idKey: "" }),
lastResult,
obs
);
Assert.equal(obs._search, acs);
Assert.equal(obs._result.searchString, element);
Assert.equal(obs._result.searchResult, ACR.RESULT_SUCCESS);
Assert.equal(obs._result.errorDescription, null);
Assert.equal(obs._result.matchCount, reductionExpectedResults[index].length);
Assert.equal(
obs._result.matchCount,
reductionExpectedResults[index].length
);
for (var i = 0; i < reductionExpectedResults[index].length; ++i) {
Assert.equal(obs._result.getValueAt(i), reductionExpectedResults[index][i]);
Assert.equal(obs._result.getLabelAt(i), reductionExpectedResults[index][i]);
Assert.equal(
obs._result.getValueAt(i),
reductionExpectedResults[index][i]
);
Assert.equal(
obs._result.getLabelAt(i),
reductionExpectedResults[index][i]
);
Assert.equal(obs._result.getCommentAt(i), "");
Assert.equal(obs._result.getStyleAt(i), "local-abook");
Assert.equal(obs._result.getImageAt(i), "");

Просмотреть файл

@ -6,30 +6,36 @@
var ACR = Ci.nsIAutoCompleteResult;
var results = [ { email: "d <ema@test.invalid>", dirName: kPABData.dirName },
{ email: "di <emai@test.invalid>", dirName: kPABData.dirName },
{ email: "dis <email@test.invalid>", dirName: kPABData.dirName },
{ email: "disp <e@test.invalid>", dirName: kPABData.dirName },
{ email: "displ <em@test.invalid>", dirName: kPABData.dirName },
{ email: "t <list>", dirName: kPABData.dirName },
{ email: "te <lis>", dirName: kPABData.dirName },
{ email: "tes <li>", dirName: kPABData.dirName },
// this contact has a nickname of "abcdef"
{ email: "test <l>", dirName: kPABData.dirName } ];
var results = [
{ email: "d <ema@test.invalid>", dirName: kPABData.dirName },
{ email: "di <emai@test.invalid>", dirName: kPABData.dirName },
{ email: "dis <email@test.invalid>", dirName: kPABData.dirName },
{ email: "disp <e@test.invalid>", dirName: kPABData.dirName },
{ email: "displ <em@test.invalid>", dirName: kPABData.dirName },
{ email: "t <list>", dirName: kPABData.dirName },
{ email: "te <lis>", dirName: kPABData.dirName },
{ email: "tes <li>", dirName: kPABData.dirName },
// this contact has a nickname of "abcdef"
{ email: "test <l>", dirName: kPABData.dirName },
];
var firstNames = [ { search: "f", expected: [4, 0, 1, 2, 3, 8] },
{ search: "fi", expected: [4, 0, 1, 3] },
{ search: "fir", expected: [4, 0, 1] },
{ search: "firs", expected: [0, 1] },
{ search: "first", expected: [1] } ];
var firstNames = [
{ search: "f", expected: [4, 0, 1, 2, 3, 8] },
{ search: "fi", expected: [4, 0, 1, 3] },
{ search: "fir", expected: [4, 0, 1] },
{ search: "firs", expected: [0, 1] },
{ search: "first", expected: [1] },
];
var lastNames = [ { search: "l", expected: [5, 6, 7, 8, 4, 0, 1, 2, 3] },
{ search: "la", expected: [4, 0, 2, 3] },
{ search: "las", expected: [4, 0, 3] },
{ search: "last", expected: [4, 0] },
{ search: "lastn", expected: [0] } ];
var lastNames = [
{ search: "l", expected: [5, 6, 7, 8, 4, 0, 1, 2, 3] },
{ search: "la", expected: [4, 0, 2, 3] },
{ search: "las", expected: [4, 0, 3] },
{ search: "last", expected: [4, 0] },
{ search: "lastn", expected: [0] },
];
var inputs = [ firstNames, lastNames];
var inputs = [firstNames, lastNames];
function acObserver() {}
@ -48,8 +54,9 @@ function run_test() {
// Test - Create a new search component
let acs = Cc["@mozilla.org/autocomplete/search;1?name=addrbook"]
.getService(Ci.nsIAutoCompleteSearch);
let acs = Cc["@mozilla.org/autocomplete/search;1?name=addrbook"].getService(
Ci.nsIAutoCompleteSearch
);
let obs = new acObserver();
@ -61,15 +68,26 @@ function run_test() {
// Now check multiple matches
function checkInputItem(element, index, array) {
print("Search #" + index + ": search=" + element.search);
acs.startSearch(element.search, JSON.stringify({ type: "addr_to" }), null, obs);
acs.startSearch(
element.search,
JSON.stringify({ type: "addr_to" }),
null,
obs
);
for (let i = 0; i < obs._result.matchCount; i++) {
print("... got " + i + ": " + obs._result.getValueAt(i));
}
for (let i = 0; i < element.expected.length; i++) {
print("... expected " + i + " (card " + element.expected[i] + "): " +
results[element.expected[i]].email);
print(
"... expected " +
i +
" (card " +
element.expected[i] +
"): " +
results[element.expected[i]].email
);
}
Assert.equal(obs._search, acs);
@ -80,8 +98,14 @@ function run_test() {
Assert.equal(obs._result.defaultIndex, 0);
for (let i = 0; i < element.expected.length; ++i) {
Assert.equal(obs._result.getValueAt(i), results[element.expected[i]].email);
Assert.equal(obs._result.getCommentAt(i), results[element.expected[i]].dirName);
Assert.equal(
obs._result.getValueAt(i),
results[element.expected[i]].email
);
Assert.equal(
obs._result.getCommentAt(i),
results[element.expected[i]].dirName
);
Assert.equal(obs._result.getStyleAt(i), "local-abook");
Assert.equal(obs._result.getImageAt(i), "");
@ -90,7 +114,10 @@ function run_test() {
// and hence future tests don't have to convert it.
if (element.expected[i] == 4) {
let result = obs._result.QueryInterface(Ci.nsIAbAutoCompleteResult);
Assert.equal(result.getCardAt(i).getProperty("PopularityIndex", -1), 10);
Assert.equal(
result.getCardAt(i).getProperty("PopularityIndex", -1),
10
);
}
}
}

Просмотреть файл

@ -6,94 +6,149 @@
var ACR = Ci.nsIAutoCompleteResult;
var cards = [
{ // 0
email: "jd.who@example.com", displayName: "John Doe (:xx)",
popularityIndex: 0, firstName: "John", value: "John Doe (:xx) <jd.who@example.com>",
{
// 0
email: "jd.who@example.com",
displayName: "John Doe (:xx)",
popularityIndex: 0,
firstName: "John",
value: "John Doe (:xx) <jd.who@example.com>",
},
{ // 1
email: "janey_who@example.com", displayName: "Jane Doe",
popularityIndex: 0, value: "Jane Doe <janey_who@example.com>",
{
// 1
email: "janey_who@example.com",
displayName: "Jane Doe",
popularityIndex: 0,
value: "Jane Doe <janey_who@example.com>",
},
{ // 2
email: "pf@example.com", displayName: "Paul \"Shitbreak\" Finch",
popularityIndex: 0, value: "Paul \"Shitbreak\" Finch <pf@example.com>",
{
// 2
email: "pf@example.com",
displayName: 'Paul "Shitbreak" Finch',
popularityIndex: 0,
value: 'Paul "Shitbreak" Finch <pf@example.com>',
},
{ // 3
email: "js@example.com", displayName: "Janine (Stifflers Mom)",
popularityIndex: 0, value: "Janine (Stifflers Mom) <js@example.com>",
{
// 3
email: "js@example.com",
displayName: "Janine (Stifflers Mom)",
popularityIndex: 0,
value: "Janine (Stifflers Mom) <js@example.com>",
},
{ // 4
email: "ex0@example.com", displayName: "Ajden",
popularityIndex: 0, value: "Ajden <ex0@example.com>",
{
// 4
email: "ex0@example.com",
displayName: "Ajden",
popularityIndex: 0,
value: "Ajden <ex0@example.com>",
},
{ // 5
email: "5@example.com", displayName: "Foxx",
popularityIndex: 0, value: "Foxx <5@example.com>",
{
// 5
email: "5@example.com",
displayName: "Foxx",
popularityIndex: 0,
value: "Foxx <5@example.com>",
},
{ // 6
email: "6@example.com", displayName: "thewho",
popularityIndex: 0, value: "thewho <6@example.com>",
{
// 6
email: "6@example.com",
displayName: "thewho",
popularityIndex: 0,
value: "thewho <6@example.com>",
},
{ // 7
email: "7@example.com", displayName: "fakeshit",
popularityIndex: 0, value: "fakeshit <7@example.com>",
{
// 7
email: "7@example.com",
displayName: "fakeshit",
popularityIndex: 0,
value: "fakeshit <7@example.com>",
},
{ // 8
email: "8@example.com", displayName: "mastiff",
popularityIndex: 0, value: "mastiff <8@example.com>",
{
// 8
email: "8@example.com",
displayName: "mastiff",
popularityIndex: 0,
value: "mastiff <8@example.com>",
},
{ // 9
email: "9@example.com", displayName: "anyjohn",
popularityIndex: 0, value: "anyjohn <9@example.com>",
{
// 9
email: "9@example.com",
displayName: "anyjohn",
popularityIndex: 0,
value: "anyjohn <9@example.com>",
},
{ // 10
email: "10@example.com", displayName: "däsh l18n",
popularityIndex: 0, value: "däsh l18n <10@example.com>",
{
// 10
email: "10@example.com",
displayName: "däsh l18n",
popularityIndex: 0,
value: "däsh l18n <10@example.com>",
},
{ // 11
email: "11@example.com", displayName: "paul mary",
popularityIndex: 0, firstName: "paul", lastName: "mary meyer",
{
// 11
email: "11@example.com",
displayName: "paul mary",
popularityIndex: 0,
firstName: "paul",
lastName: "mary meyer",
value: "paul mary <11@example.com>",
},
{ // 12
email: "12@example.com", displayName: "paul meyer",
popularityIndex: 0, firstName: "paul", lastName: "mary meyer",
{
// 12
email: "12@example.com",
displayName: "paul meyer",
popularityIndex: 0,
firstName: "paul",
lastName: "mary meyer",
value: "paul meyer <12@example.com>",
},
{ // 13
email: "13@example.com", displayName: "mr iron man (exp dev)",
popularityIndex: 0, firstName: "iron", lastName: "man",
{
// 13
email: "13@example.com",
displayName: "mr iron man (exp dev)",
popularityIndex: 0,
firstName: "iron",
lastName: "man",
value: "mr iron man (exp dev) <13@example.com>",
},
{ // 14
email: "14@example.com", displayName: "michael",
popularityIndex: 0, nickName: "short",
{
// 14
email: "14@example.com",
displayName: "michael",
popularityIndex: 0,
nickName: "short",
value: "michael <14@example.com>",
},
{ // 15
email: "15@example.com", displayName: "good boy",
popularityIndex: 0, nickName: "sh",
{
// 15
email: "15@example.com",
displayName: "good boy",
popularityIndex: 0,
nickName: "sh",
value: "good boy <15@example.com>",
},
{ // 16
email: "16@example.com", displayName: "sherlock holmes",
popularityIndex: 0, value: "sherlock holmes <16@example.com>",
{
// 16
email: "16@example.com",
displayName: "sherlock holmes",
popularityIndex: 0,
value: "sherlock holmes <16@example.com>",
},
];
@ -108,8 +163,8 @@ var inputs = [
{ search: "sh", expected: [15, 14, 2, 16, 10, 7] },
{ search: "st", expected: [3, 8] },
{ search: "paul mary", expected: [11, 12] },
{ search: "\"paul mary\"", expected: [11] },
{ search: "\"iron man\" mr \"exp dev\"", expected: [13] },
{ search: '"paul mary"', expected: [11] },
{ search: '"iron man" mr "exp dev"', expected: [13] },
{ search: "short", expected: [14] },
];
@ -135,16 +190,18 @@ function run_test() {
let ab = MailServices.ab.getDirectory(kPABData.URI);
function createAndAddCard(element) {
var card = Cc["@mozilla.org/addressbook/cardproperty;1"]
.createInstance(Ci.nsIAbCard);
var card = Cc["@mozilla.org/addressbook/cardproperty;1"].createInstance(
Ci.nsIAbCard
);
card.primaryEmail = element.email;
card.displayName = element.displayName;
card.setProperty("PopularityIndex", element.popularityIndex);
card.firstName = element.firstName;
card.lastName = element.lastName;
if ("nickName" in element)
if ("nickName" in element) {
card.setProperty("NickName", element.nickName);
}
ab.addCard(card);
}
@ -153,22 +210,34 @@ function run_test() {
// Test - duplicate elements
var acs = Cc["@mozilla.org/autocomplete/search;1?name=addrbook"]
.getService(Ci.nsIAutoCompleteSearch);
var acs = Cc["@mozilla.org/autocomplete/search;1?name=addrbook"].getService(
Ci.nsIAutoCompleteSearch
);
var obs = new acObserver();
function checkInputItem(element, index, array) {
print("Search #" + index + ": search=" + element.search);
acs.startSearch(element.search, JSON.stringify({ type: "addr_to" }), null, obs);
acs.startSearch(
element.search,
JSON.stringify({ type: "addr_to" }),
null,
obs
);
for (let i = 0; i < obs._result.matchCount; i++) {
print("... got " + i + ": " + obs._result.getValueAt(i));
}
for (let i = 0; i < element.expected.length; i++) {
print("... expected " + i + " (card " + element.expected[i] + "): " +
cards[element.expected[i]].value);
print(
"... expected " +
i +
" (card " +
element.expected[i] +
"): " +
cards[element.expected[i]].value
);
}
Assert.equal(obs._search, acs);

Просмотреть файл

@ -11,7 +11,7 @@ var ACR = Ci.nsIAutoCompleteResult;
// Note the expected arrays are in expected sort order as well.
var results = [
var results = [
{ email: "Tomas Doe <tomez.doe@foo.invalid>" }, // 0
{ email: "Tomas Doe <tomez.doe@foo2.invalid>" }, // 1
{ email: "Tomas Doe <tomez.doe@b.example.com>" }, // 2
@ -21,9 +21,9 @@ var results = [
var inputs = [
[
{ search: "t", expected: [2, 3, 0, 1, 4] },
{ search: "tom", expected: [0, 1, 2, 3, 4] },
{ search: "tomek", expected: [4] },
{ search: "t", expected: [2, 3, 0, 1, 4] },
{ search: "tom", expected: [0, 1, 2, 3, 4] },
{ search: "tomek", expected: [4] },
],
];
@ -41,31 +41,31 @@ acObserver.prototype = {
var PAB_CARD_DATA = [
{
"FirstName": "Tomas",
"LastName": "Doe",
"DisplayName": "Tomas Doe",
"NickName": "tom",
"PrimaryEmail": "tomez.doe@foo.invalid",
"SecondEmail": "tomez.doe@foo2.invalid",
"PreferDisplayName": true,
"PopularityIndex": 10,
FirstName: "Tomas",
LastName: "Doe",
DisplayName: "Tomas Doe",
NickName: "tom",
PrimaryEmail: "tomez.doe@foo.invalid",
SecondEmail: "tomez.doe@foo2.invalid",
PreferDisplayName: true,
PopularityIndex: 10,
},
{
"FirstName": "Tomas",
"LastName": "Doe",
"DisplayName": "Tomas Doe",
"PrimaryEmail": "tomez.doe@b.example.com",
"SecondEmail": "tomez.doe@a.example.com",
"PreferDisplayName": true,
"PopularityIndex": 200,
FirstName: "Tomas",
LastName: "Doe",
DisplayName: "Tomas Doe",
PrimaryEmail: "tomez.doe@b.example.com",
SecondEmail: "tomez.doe@a.example.com",
PreferDisplayName: true,
PopularityIndex: 200,
},
{
"FirstName": "Tomek",
"LastName": "Smith",
"DisplayName": "Tomek Smith",
"PrimaryEmail": "tomek@example.com",
"PreferDisplayName": true,
"PopularityIndex": 3,
FirstName: "Tomek",
LastName: "Smith",
DisplayName: "Tomek Smith",
PrimaryEmail: "tomek@example.com",
PreferDisplayName: true,
PopularityIndex: 3,
},
];
@ -83,8 +83,9 @@ function setupAddressBookData(aDirURI, aCardData, aMailListData) {
}
aCardData.forEach(function(cd) {
let card = Cc["@mozilla.org/addressbook/cardproperty;1"]
.createInstance(Ci.nsIAbCard);
let card = Cc["@mozilla.org/addressbook/cardproperty;1"].createInstance(
Ci.nsIAbCard
);
for (var prop in cd) {
card.setProperty(prop, cd[prop]);
}
@ -92,8 +93,9 @@ function setupAddressBookData(aDirURI, aCardData, aMailListData) {
});
aMailListData.forEach(function(ld) {
let list = Cc["@mozilla.org/addressbook/directoryproperty;1"]
.createInstance(Ci.nsIAbDirectory);
let list = Cc[
"@mozilla.org/addressbook/directoryproperty;1"
].createInstance(Ci.nsIAbDirectory);
list.isMailList = true;
for (var prop in ld) {
list[prop] = ld[prop];
@ -113,8 +115,9 @@ function run_test() {
// Test - Create a new search component
var acs = Cc["@mozilla.org/autocomplete/search;1?name=addrbook"]
.getService(Ci.nsIAutoCompleteSearch);
var acs = Cc["@mozilla.org/autocomplete/search;1?name=addrbook"].getService(
Ci.nsIAutoCompleteSearch
);
var obs = new acObserver();
@ -130,8 +133,14 @@ function run_test() {
print("... got " + i + ": " + obs._result.getValueAt(i));
}
for (let i = 0; i < element.expected.length; i++) {
print("... expected " + i + " (result " + element.expected[i] + "): " +
results[element.expected[i]].email);
print(
"... expected " +
i +
" (result " +
element.expected[i] +
"): " +
results[element.expected[i]].email
);
}
Assert.equal(obs._search, acs);
@ -142,8 +151,14 @@ function run_test() {
Assert.equal(obs._result.defaultIndex, 0);
for (let i = 0; i < element.expected.length; ++i) {
Assert.equal(obs._result.getValueAt(i), results[element.expected[i]].email);
Assert.equal(obs._result.getLabelAt(i), results[element.expected[i]].email);
Assert.equal(
obs._result.getValueAt(i),
results[element.expected[i]].email
);
Assert.equal(
obs._result.getLabelAt(i),
results[element.expected[i]].email
);
Assert.equal(obs._result.getCommentAt(i), "");
Assert.equal(obs._result.getStyleAt(i), "local-abook");
Assert.equal(obs._result.getImageAt(i), "");

Просмотреть файл

@ -12,25 +12,29 @@ var gAblSingle = new Array(numListenerOptions);
function abL() {}
abL.prototype = {
mReceived: 0,
mAutoRemoveItem: false,
mReceived: 0,
mAutoRemoveItem: false,
onItemAdded(parentItem, item) {
this.mReceived |= nsIAbListener.itemAdded;
if (this.mAutoRemoveItem)
if (this.mAutoRemoveItem) {
MailServices.ab.removeAddressBookListener(this);
}
},
onItemRemoved(parentItem, item) {
this.mReceived |=
(item == MailServices.ab ? nsIAbListener.directoryRemoved :
nsIAbListener.directoryItemRemoved);
if (this.mAutoRemoveItem)
item == MailServices.ab
? nsIAbListener.directoryRemoved
: nsIAbListener.directoryItemRemoved;
if (this.mAutoRemoveItem) {
MailServices.ab.removeAddressBookListener(this);
}
},
onItemPropertyChanged(item, property, oldValue, newValue) {
this.mReceived |= nsIAbListener.itemChanged;
if (this.mAutoRemoveItem)
if (this.mAutoRemoveItem) {
MailServices.ab.removeAddressBookListener(this);
}
},
};
@ -48,12 +52,12 @@ function run_test() {
// Test - Add a listener
gAblAll = new abL;
gAblAll = new abL();
MailServices.ab.addAddressBookListener(gAblAll, nsIAbListener.all);
for (i = 0; i < numListenerOptions; ++i) {
gAblSingle[i] = new abL;
gAblSingle[i] = new abL();
MailServices.ab.addAddressBookListener(gAblSingle[i], 1 << i);
}

Просмотреть файл

@ -14,27 +14,30 @@ var gAblSingle = new Array(numListenerOptions);
function abL() {}
abL.prototype = {
mReceived: 0,
mDirectory: null,
mAutoRemoveItem: false,
mReceived: 0,
mDirectory: null,
mAutoRemoveItem: false,
onItemAdded(parentItem, item) {
this.mReceived |= nsIAbListener.itemAdded;
this.mDirectory = item;
if (this.mAutoRemoveItem)
if (this.mAutoRemoveItem) {
MailServices.ab.removeAddressBookListener(this);
}
},
onItemRemoved(parentItem, item) {
this.mReceived |= nsIAbListener.directoryRemoved;
this.mDirectory = item;
if (this.mAutoRemoveItem)
if (this.mAutoRemoveItem) {
MailServices.ab.removeAddressBookListener(this);
}
},
onItemPropertyChanged(item, property, oldValue, newValue) {
this.mReceived |= nsIAbListener.itemChanged;
this.mDirectory = item;
if (this.mAutoRemoveItem)
if (this.mAutoRemoveItem) {
MailServices.ab.removeAddressBookListener(this);
}
},
};
@ -48,13 +51,18 @@ function checkDirs(aDirs, aDirArray) {
Assert.equal(MailServices.ab.getDirectory(dir.URI), dir);
if (loc == -1)
do_throw("Unexpected directory " + dir.URI + " found in address book list");
else
if (loc == -1) {
do_throw(
"Unexpected directory " + dir.URI + " found in address book list"
);
} else {
dirArray[loc] = null;
}
}
dirArray.forEach(function(value) { Assert.equal(value, null); });
dirArray.forEach(function(value) {
Assert.equal(value, null);
});
}
function addDirectory(dirName) {
@ -106,11 +114,11 @@ function run_test() {
var i;
// Set up listeners
gAblAll = new abL;
gAblAll = new abL();
MailServices.ab.addAddressBookListener(gAblAll, nsIAbListener.all);
for (i = 0; i < numListenerOptions; ++i) {
gAblSingle[i] = new abL;
gAblSingle[i] = new abL();
MailServices.ab.addAddressBookListener(gAblSingle[i], 1 << i);
}
@ -169,6 +177,7 @@ function run_test() {
MailServices.ab.removeAddressBookListener(gAblAll);
for (i = 0; i < numListenerOptions; ++i)
for (i = 0; i < numListenerOptions; ++i) {
MailServices.ab.removeAddressBookListener(gAblSingle[i]);
}
}

Просмотреть файл

@ -8,8 +8,7 @@
var gAbListener;
function abListener() {
}
function abListener() {}
abListener.prototype = {
mReceived: 0,
@ -62,7 +61,10 @@ function removeDirectory(directory) {
MailServices.ab.deleteAddressBook(directory.URI);
Assert.equal(gAbListener.mReceived, Ci.nsIAbListener.directoryRemoved);
Assert.equal(gAbListener.mDirectory, directory.QueryInterface(Ci.nsIAbDirectory));
Assert.equal(
gAbListener.mDirectory,
directory.QueryInterface(Ci.nsIAbDirectory)
);
gAbListener.reset();
}

Просмотреть файл

@ -23,17 +23,22 @@ function run_test() {
tempCard = childCards.getNext();
// We want the one with the right email...
if (tempCard instanceof Ci.nsIAbCard &&
tempCard.primaryEmail == "PrimaryEmail1@test.invalid")
if (
tempCard instanceof Ci.nsIAbCard &&
tempCard.primaryEmail == "PrimaryEmail1@test.invalid"
) {
fullCard = tempCard;
}
}
Assert.ok(fullCard != null);
// Test - VCard.
Assert.equal(fullCard.translateTo("vcard"),
"begin%3Avcard%0D%0Afn%3ADisplayName1%0D%0An%3ALastName1%3BFirstName1%0D%0Aorg%3AOrganization1%3BDepartment1%0D%0Aadr%3AWorkAddress21%3B%3BWorkAddress1%3BWorkCity1%3BWorkState1%3BWorkZipCode1%3BWorkCountry1%0D%0Aemail%3Binternet%3APrimaryEmail1%40test.invalid%0D%0Atitle%3AJobTitle1%0D%0Atel%3Bwork%3AWorkPhone1%0D%0Atel%3Bfax%3AFaxNumber1%0D%0Atel%3Bpager%3APagerNumber1%0D%0Atel%3Bhome%3AHomePhone1%0D%0Atel%3Bcell%3ACellularNumber1%0D%0Anote%3ANotes1%0D%0Aurl%3Ahttp%3A//WebPage21%0D%0Aversion%3A2.1%0D%0Aend%3Avcard%0D%0A%0D%0A");
Assert.equal(
fullCard.translateTo("vcard"),
"begin%3Avcard%0D%0Afn%3ADisplayName1%0D%0An%3ALastName1%3BFirstName1%0D%0Aorg%3AOrganization1%3BDepartment1%0D%0Aadr%3AWorkAddress21%3B%3BWorkAddress1%3BWorkCity1%3BWorkState1%3BWorkZipCode1%3BWorkCountry1%0D%0Aemail%3Binternet%3APrimaryEmail1%40test.invalid%0D%0Atitle%3AJobTitle1%0D%0Atel%3Bwork%3AWorkPhone1%0D%0Atel%3Bfax%3AFaxNumber1%0D%0Atel%3Bpager%3APagerNumber1%0D%0Atel%3Bhome%3AHomePhone1%0D%0Atel%3Bcell%3ACellularNumber1%0D%0Anote%3ANotes1%0D%0Aurl%3Ahttp%3A//WebPage21%0D%0Aversion%3A2.1%0D%0Aend%3Avcard%0D%0A%0D%0A"
);
// Test - XML
@ -44,9 +49,11 @@ function run_test() {
// is obviously less than ideal, and we should fix this in a follow-up patch
// in bug 761304
let tbXml = "<GeneratedName>\nDisplayName1</GeneratedName>\n<table><tr><td><section><labelrow><label>Display Name: </label><DisplayName>DisplayName1</DisplayName></labelrow><labelrow><label>Nickname: </label><NickName>NickName1</NickName></labelrow><PrimaryEmail>PrimaryEmail1@test.invalid</PrimaryEmail><SecondEmail>SecondEmail1\u00D0@test.invalid</SecondEmail></section></td></tr><tr><td><section><sectiontitle>Phone</sectiontitle><labelrow><label>Work: </label><WorkPhone>WorkPhone1</WorkPhone></labelrow><labelrow><label>Home: </label><HomePhone>HomePhone1</HomePhone></labelrow><labelrow><label>Fax: </label><FaxNumber>FaxNumber1</FaxNumber></labelrow><labelrow><label>Pager: </label><PagerNumber>PagerNumber1</PagerNumber></labelrow><labelrow><label>Mobile: </label><CellularNumber>CellularNumber1</CellularNumber></labelrow></section><section><sectiontitle>Other</sectiontitle><labelrow><label>Custom 1: </label><Custom1>Custom11</Custom1></labelrow><labelrow><label>Custom 2: </label><Custom2>Custom21</Custom2></labelrow><labelrow><label>Custom 3: </label><Custom3>Custom31</Custom3></labelrow><labelrow><label>Custom 4: </label><Custom4>Custom41</Custom4></labelrow><Notes>Notes1</Notes></section><section><sectiontitle>Chat</sectiontitle><labelrow><label>AIM: </label><_AimScreenName>ScreenName1</_AimScreenName></labelrow></section></td><td><section><sectiontitle>Home</sectiontitle><HomeAddress>HomeAddress11</HomeAddress><HomeAddress2>HomeAddress21</HomeAddress2><HomeCity>HomeCity1</HomeCity>, <HomeState>HomeState1</HomeState> <HomeZipCode>HomeZipCode1</HomeZipCode><HomeCountry>HomeCountry1</HomeCountry><WebPage2>http://WebPage11</WebPage2></section><section><sectiontitle>Work</sectiontitle><JobTitle>JobTitle1</JobTitle><Department>Department1</Department><Company>Organization1</Company><WorkAddress>WorkAddress1</WorkAddress><WorkAddress2>WorkAddress21</WorkAddress2><WorkCity>WorkCity1</WorkCity>, <WorkState>WorkState1</WorkState> <WorkZipCode>WorkZipCode1</WorkZipCode><WorkCountry>WorkCountry1</WorkCountry><WebPage1>http://WebPage21</WebPage1></section></td></tr></table>";
let tbXml =
"<GeneratedName>\nDisplayName1</GeneratedName>\n<table><tr><td><section><labelrow><label>Display Name: </label><DisplayName>DisplayName1</DisplayName></labelrow><labelrow><label>Nickname: </label><NickName>NickName1</NickName></labelrow><PrimaryEmail>PrimaryEmail1@test.invalid</PrimaryEmail><SecondEmail>SecondEmail1\u00D0@test.invalid</SecondEmail></section></td></tr><tr><td><section><sectiontitle>Phone</sectiontitle><labelrow><label>Work: </label><WorkPhone>WorkPhone1</WorkPhone></labelrow><labelrow><label>Home: </label><HomePhone>HomePhone1</HomePhone></labelrow><labelrow><label>Fax: </label><FaxNumber>FaxNumber1</FaxNumber></labelrow><labelrow><label>Pager: </label><PagerNumber>PagerNumber1</PagerNumber></labelrow><labelrow><label>Mobile: </label><CellularNumber>CellularNumber1</CellularNumber></labelrow></section><section><sectiontitle>Other</sectiontitle><labelrow><label>Custom 1: </label><Custom1>Custom11</Custom1></labelrow><labelrow><label>Custom 2: </label><Custom2>Custom21</Custom2></labelrow><labelrow><label>Custom 3: </label><Custom3>Custom31</Custom3></labelrow><labelrow><label>Custom 4: </label><Custom4>Custom41</Custom4></labelrow><Notes>Notes1</Notes></section><section><sectiontitle>Chat</sectiontitle><labelrow><label>AIM: </label><_AimScreenName>ScreenName1</_AimScreenName></labelrow></section></td><td><section><sectiontitle>Home</sectiontitle><HomeAddress>HomeAddress11</HomeAddress><HomeAddress2>HomeAddress21</HomeAddress2><HomeCity>HomeCity1</HomeCity>, <HomeState>HomeState1</HomeState> <HomeZipCode>HomeZipCode1</HomeZipCode><HomeCountry>HomeCountry1</HomeCountry><WebPage2>http://WebPage11</WebPage2></section><section><sectiontitle>Work</sectiontitle><JobTitle>JobTitle1</JobTitle><Department>Department1</Department><Company>Organization1</Company><WorkAddress>WorkAddress1</WorkAddress><WorkAddress2>WorkAddress21</WorkAddress2><WorkCity>WorkCity1</WorkCity>, <WorkState>WorkState1</WorkState> <WorkZipCode>WorkZipCode1</WorkZipCode><WorkCountry>WorkCountry1</WorkCountry><WebPage1>http://WebPage21</WebPage1></section></td></tr></table>";
let smXml = "<GeneratedName>\nDisplayName1</GeneratedName>\n<table><tr><td><section><labelrow><label>Display Name: </label><DisplayName>DisplayName1</DisplayName></labelrow><labelrow><label>Nickname: </label><NickName>NickName1</NickName></labelrow><PrimaryEmail>PrimaryEmail1@test.invalid</PrimaryEmail><SecondEmail>SecondEmail1\u00D0@test.invalid</SecondEmail><labelrow><label>Screen Name: </label><_AimScreenName>ScreenName1</_AimScreenName></labelrow></section></td></tr><tr><td><section><sectiontitle>Phone</sectiontitle><labelrow><label>Work: </label><WorkPhone>WorkPhone1</WorkPhone></labelrow><labelrow><label>Home: </label><HomePhone>HomePhone1</HomePhone></labelrow><labelrow><label>Fax: </label><FaxNumber>FaxNumber1</FaxNumber></labelrow><labelrow><label>Pager: </label><PagerNumber>PagerNumber1</PagerNumber></labelrow><labelrow><label>Mobile: </label><CellularNumber>CellularNumber1</CellularNumber></labelrow></section><section><sectiontitle>Other</sectiontitle><labelrow><label>Custom 1: </label><Custom1>Custom11</Custom1></labelrow><labelrow><label>Custom 2: </label><Custom2>Custom21</Custom2></labelrow><labelrow><label>Custom 3: </label><Custom3>Custom31</Custom3></labelrow><labelrow><label>Custom 4: </label><Custom4>Custom41</Custom4></labelrow><Notes>Notes1</Notes></section></td><td><section><sectiontitle>Home</sectiontitle><HomeAddress>HomeAddress11</HomeAddress><HomeAddress2>HomeAddress21</HomeAddress2><HomeCity>HomeCity1</HomeCity>, <HomeState>HomeState1</HomeState> <HomeZipCode>HomeZipCode1</HomeZipCode><HomeCountry>HomeCountry1</HomeCountry><WebPage2>http://WebPage11</WebPage2></section><section><sectiontitle>Work</sectiontitle><JobTitle>JobTitle1</JobTitle><Department>Department1</Department><Company>Organization1</Company><WorkAddress>WorkAddress1</WorkAddress><WorkAddress2>WorkAddress21</WorkAddress2><WorkCity>WorkCity1</WorkCity>, <WorkState>WorkState1</WorkState> <WorkZipCode>WorkZipCode1</WorkZipCode><WorkCountry>WorkCountry1</WorkCountry><WebPage1>http://WebPage21</WebPage1></section></td></tr></table>";
let smXml =
"<GeneratedName>\nDisplayName1</GeneratedName>\n<table><tr><td><section><labelrow><label>Display Name: </label><DisplayName>DisplayName1</DisplayName></labelrow><labelrow><label>Nickname: </label><NickName>NickName1</NickName></labelrow><PrimaryEmail>PrimaryEmail1@test.invalid</PrimaryEmail><SecondEmail>SecondEmail1\u00D0@test.invalid</SecondEmail><labelrow><label>Screen Name: </label><_AimScreenName>ScreenName1</_AimScreenName></labelrow></section></td></tr><tr><td><section><sectiontitle>Phone</sectiontitle><labelrow><label>Work: </label><WorkPhone>WorkPhone1</WorkPhone></labelrow><labelrow><label>Home: </label><HomePhone>HomePhone1</HomePhone></labelrow><labelrow><label>Fax: </label><FaxNumber>FaxNumber1</FaxNumber></labelrow><labelrow><label>Pager: </label><PagerNumber>PagerNumber1</PagerNumber></labelrow><labelrow><label>Mobile: </label><CellularNumber>CellularNumber1</CellularNumber></labelrow></section><section><sectiontitle>Other</sectiontitle><labelrow><label>Custom 1: </label><Custom1>Custom11</Custom1></labelrow><labelrow><label>Custom 2: </label><Custom2>Custom21</Custom2></labelrow><labelrow><label>Custom 3: </label><Custom3>Custom31</Custom3></labelrow><labelrow><label>Custom 4: </label><Custom4>Custom41</Custom4></labelrow><Notes>Notes1</Notes></section></td><td><section><sectiontitle>Home</sectiontitle><HomeAddress>HomeAddress11</HomeAddress><HomeAddress2>HomeAddress21</HomeAddress2><HomeCity>HomeCity1</HomeCity>, <HomeState>HomeState1</HomeState> <HomeZipCode>HomeZipCode1</HomeZipCode><HomeCountry>HomeCountry1</HomeCountry><WebPage2>http://WebPage11</WebPage2></section><section><sectiontitle>Work</sectiontitle><JobTitle>JobTitle1</JobTitle><Department>Department1</Department><Company>Organization1</Company><WorkAddress>WorkAddress1</WorkAddress><WorkAddress2>WorkAddress21</WorkAddress2><WorkCity>WorkCity1</WorkCity>, <WorkState>WorkState1</WorkState> <WorkZipCode>WorkZipCode1</WorkZipCode><WorkCountry>WorkCountry1</WorkCountry><WebPage1>http://WebPage21</WebPage1></section></td></tr></table>";
let XmlTrans = fullCard.translateTo("xml");
Assert.ok(XmlTrans == tbXml || XmlTrans == smXml);
@ -60,9 +67,11 @@ function run_test() {
// btoa is only available for xpcom components or via window.btoa, so we
// can't use it here.
let tbXmlBase64 = "PD94bWwgdmVyc2lvbj0iMS4wIj8+Cjw/eG1sLXN0eWxlc2hlZXQgdHlwZT0idGV4dC9jc3MiIGhyZWY9ImNocm9tZTovL21lc3NhZ2Vib2R5L2NvbnRlbnQvYWRkcmVzc2Jvb2svcHJpbnQuY3NzIj8+CjxkaXJlY3Rvcnk+Cjx0aXRsZSB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMTk5OS94aHRtbCI+QWRkcmVzcyBCb29rPC90aXRsZT4KPEdlbmVyYXRlZE5hbWU+CkRpc3BsYXlOYW1lMTwvR2VuZXJhdGVkTmFtZT4KPHRhYmxlPjx0cj48dGQ+PHNlY3Rpb24+PGxhYmVscm93PjxsYWJlbD5EaXNwbGF5IE5hbWU6IDwvbGFiZWw+PERpc3BsYXlOYW1lPkRpc3BsYXlOYW1lMTwvRGlzcGxheU5hbWU+PC9sYWJlbHJvdz48bGFiZWxyb3c+PGxhYmVsPk5pY2tuYW1lOiA8L2xhYmVsPjxOaWNrTmFtZT5OaWNrTmFtZTE8L05pY2tOYW1lPjwvbGFiZWxyb3c+PFByaW1hcnlFbWFpbD5QcmltYXJ5RW1haWwxQHRlc3QuaW52YWxpZDwvUHJpbWFyeUVtYWlsPjxTZWNvbmRFbWFpbD5TZWNvbmRFbWFpbDHDkEB0ZXN0LmludmFsaWQ8L1NlY29uZEVtYWlsPjwvc2VjdGlvbj48L3RkPjwvdHI+PHRyPjx0ZD48c2VjdGlvbj48c2VjdGlvbnRpdGxlPlBob25lPC9zZWN0aW9udGl0bGU+PGxhYmVscm93PjxsYWJlbD5Xb3JrOiA8L2xhYmVsPjxXb3JrUGhvbmU+V29ya1Bob25lMTwvV29ya1Bob25lPjwvbGFiZWxyb3c+PGxhYmVscm93PjxsYWJlbD5Ib21lOiA8L2xhYmVsPjxIb21lUGhvbmU+SG9tZVBob25lMTwvSG9tZVBob25lPjwvbGFiZWxyb3c+PGxhYmVscm93PjxsYWJlbD5GYXg6IDwvbGFiZWw+PEZheE51bWJlcj5GYXhOdW1iZXIxPC9GYXhOdW1iZXI+PC9sYWJlbHJvdz48bGFiZWxyb3c+PGxhYmVsPlBhZ2VyOiA8L2xhYmVsPjxQYWdlck51bWJlcj5QYWdlck51bWJlcjE8L1BhZ2VyTnVtYmVyPjwvbGFiZWxyb3c+PGxhYmVscm93PjxsYWJlbD5Nb2JpbGU6IDwvbGFiZWw+PENlbGx1bGFyTnVtYmVyPkNlbGx1bGFyTnVtYmVyMTwvQ2VsbHVsYXJOdW1iZXI+PC9sYWJlbHJvdz48L3NlY3Rpb24+PHNlY3Rpb24+PHNlY3Rpb250aXRsZT5PdGhlcjwvc2VjdGlvbnRpdGxlPjxsYWJlbHJvdz48bGFiZWw+Q3VzdG9tIDE6IDwvbGFiZWw+PEN1c3RvbTE+Q3VzdG9tMTE8L0N1c3RvbTE+PC9sYWJlbHJvdz48bGFiZWxyb3c+PGxhYmVsPkN1c3RvbSAyOiA8L2xhYmVsPjxDdXN0b20yPkN1c3RvbTIxPC9DdXN0b20yPjwvbGFiZWxyb3c+PGxhYmVscm93PjxsYWJlbD5DdXN0b20gMzogPC9sYWJlbD48Q3VzdG9tMz5DdXN0b20zMTwvQ3VzdG9tMz48L2xhYmVscm93PjxsYWJlbHJvdz48bGFiZWw+Q3VzdG9tIDQ6IDwvbGFiZWw+PEN1c3RvbTQ+Q3VzdG9tNDE8L0N1c3RvbTQ+PC9sYWJlbHJvdz48Tm90ZXM+Tm90ZXMxPC9Ob3Rlcz48L3NlY3Rpb24+PHNlY3Rpb24+PHNlY3Rpb250aXRsZT5DaGF0PC9zZWN0aW9udGl0bGU+PGxhYmVscm93PjxsYWJlbD5BSU06IDwvbGFiZWw+PF9BaW1TY3JlZW5OYW1lPlNjcmVlbk5hbWUxPC9fQWltU2NyZWVuTmFtZT48L2xhYmVscm93Pjwvc2VjdGlvbj48L3RkPjx0ZD48c2VjdGlvbj48c2VjdGlvbnRpdGxlPkhvbWU8L3NlY3Rpb250aXRsZT48SG9tZUFkZHJlc3M+SG9tZUFkZHJlc3MxMTwvSG9tZUFkZHJlc3M+PEhvbWVBZGRyZXNzMj5Ib21lQWRkcmVzczIxPC9Ib21lQWRkcmVzczI+PEhvbWVDaXR5PkhvbWVDaXR5MTwvSG9tZUNpdHk+LCA8SG9tZVN0YXRlPkhvbWVTdGF0ZTE8L0hvbWVTdGF0ZT4gPEhvbWVaaXBDb2RlPkhvbWVaaXBDb2RlMTwvSG9tZVppcENvZGU+PEhvbWVDb3VudHJ5PkhvbWVDb3VudHJ5MTwvSG9tZUNvdW50cnk+PFdlYlBhZ2UyPmh0dHA6Ly9XZWJQYWdlMTE8L1dlYlBhZ2UyPjwvc2VjdGlvbj48c2VjdGlvbj48c2VjdGlvbnRpdGxlPldvcms8L3NlY3Rpb250aXRsZT48Sm9iVGl0bGU+Sm9iVGl0bGUxPC9Kb2JUaXRsZT48RGVwYXJ0bWVudD5EZXBhcnRtZW50MTwvRGVwYXJ0bWVudD48Q29tcGFueT5Pcmdhbml6YXRpb24xPC9Db21wYW55PjxXb3JrQWRkcmVzcz5Xb3JrQWRkcmVzczE8L1dvcmtBZGRyZXNzPjxXb3JrQWRkcmVzczI+V29ya0FkZHJlc3MyMTwvV29ya0FkZHJlc3MyPjxXb3JrQ2l0eT5Xb3JrQ2l0eTE8L1dvcmtDaXR5PiwgPFdvcmtTdGF0ZT5Xb3JrU3RhdGUxPC9Xb3JrU3RhdGU+IDxXb3JrWmlwQ29kZT5Xb3JrWmlwQ29kZTE8L1dvcmtaaXBDb2RlPjxXb3JrQ291bnRyeT5Xb3JrQ291bnRyeTE8L1dvcmtDb3VudHJ5PjxXZWJQYWdlMT5odHRwOi8vV2ViUGFnZTIxPC9XZWJQYWdlMT48L3NlY3Rpb24+PC90ZD48L3RyPjwvdGFibGU+PC9kaXJlY3Rvcnk+Cg==";
let tbXmlBase64 =
"PD94bWwgdmVyc2lvbj0iMS4wIj8+Cjw/eG1sLXN0eWxlc2hlZXQgdHlwZT0idGV4dC9jc3MiIGhyZWY9ImNocm9tZTovL21lc3NhZ2Vib2R5L2NvbnRlbnQvYWRkcmVzc2Jvb2svcHJpbnQuY3NzIj8+CjxkaXJlY3Rvcnk+Cjx0aXRsZSB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMTk5OS94aHRtbCI+QWRkcmVzcyBCb29rPC90aXRsZT4KPEdlbmVyYXRlZE5hbWU+CkRpc3BsYXlOYW1lMTwvR2VuZXJhdGVkTmFtZT4KPHRhYmxlPjx0cj48dGQ+PHNlY3Rpb24+PGxhYmVscm93PjxsYWJlbD5EaXNwbGF5IE5hbWU6IDwvbGFiZWw+PERpc3BsYXlOYW1lPkRpc3BsYXlOYW1lMTwvRGlzcGxheU5hbWU+PC9sYWJlbHJvdz48bGFiZWxyb3c+PGxhYmVsPk5pY2tuYW1lOiA8L2xhYmVsPjxOaWNrTmFtZT5OaWNrTmFtZTE8L05pY2tOYW1lPjwvbGFiZWxyb3c+PFByaW1hcnlFbWFpbD5QcmltYXJ5RW1haWwxQHRlc3QuaW52YWxpZDwvUHJpbWFyeUVtYWlsPjxTZWNvbmRFbWFpbD5TZWNvbmRFbWFpbDHDkEB0ZXN0LmludmFsaWQ8L1NlY29uZEVtYWlsPjwvc2VjdGlvbj48L3RkPjwvdHI+PHRyPjx0ZD48c2VjdGlvbj48c2VjdGlvbnRpdGxlPlBob25lPC9zZWN0aW9udGl0bGU+PGxhYmVscm93PjxsYWJlbD5Xb3JrOiA8L2xhYmVsPjxXb3JrUGhvbmU+V29ya1Bob25lMTwvV29ya1Bob25lPjwvbGFiZWxyb3c+PGxhYmVscm93PjxsYWJlbD5Ib21lOiA8L2xhYmVsPjxIb21lUGhvbmU+SG9tZVBob25lMTwvSG9tZVBob25lPjwvbGFiZWxyb3c+PGxhYmVscm93PjxsYWJlbD5GYXg6IDwvbGFiZWw+PEZheE51bWJlcj5GYXhOdW1iZXIxPC9GYXhOdW1iZXI+PC9sYWJlbHJvdz48bGFiZWxyb3c+PGxhYmVsPlBhZ2VyOiA8L2xhYmVsPjxQYWdlck51bWJlcj5QYWdlck51bWJlcjE8L1BhZ2VyTnVtYmVyPjwvbGFiZWxyb3c+PGxhYmVscm93PjxsYWJlbD5Nb2JpbGU6IDwvbGFiZWw+PENlbGx1bGFyTnVtYmVyPkNlbGx1bGFyTnVtYmVyMTwvQ2VsbHVsYXJOdW1iZXI+PC9sYWJlbHJvdz48L3NlY3Rpb24+PHNlY3Rpb24+PHNlY3Rpb250aXRsZT5PdGhlcjwvc2VjdGlvbnRpdGxlPjxsYWJlbHJvdz48bGFiZWw+Q3VzdG9tIDE6IDwvbGFiZWw+PEN1c3RvbTE+Q3VzdG9tMTE8L0N1c3RvbTE+PC9sYWJlbHJvdz48bGFiZWxyb3c+PGxhYmVsPkN1c3RvbSAyOiA8L2xhYmVsPjxDdXN0b20yPkN1c3RvbTIxPC9DdXN0b20yPjwvbGFiZWxyb3c+PGxhYmVscm93PjxsYWJlbD5DdXN0b20gMzogPC9sYWJlbD48Q3VzdG9tMz5DdXN0b20zMTwvQ3VzdG9tMz48L2xhYmVscm93PjxsYWJlbHJvdz48bGFiZWw+Q3VzdG9tIDQ6IDwvbGFiZWw+PEN1c3RvbTQ+Q3VzdG9tNDE8L0N1c3RvbTQ+PC9sYWJlbHJvdz48Tm90ZXM+Tm90ZXMxPC9Ob3Rlcz48L3NlY3Rpb24+PHNlY3Rpb24+PHNlY3Rpb250aXRsZT5DaGF0PC9zZWN0aW9udGl0bGU+PGxhYmVscm93PjxsYWJlbD5BSU06IDwvbGFiZWw+PF9BaW1TY3JlZW5OYW1lPlNjcmVlbk5hbWUxPC9fQWltU2NyZWVuTmFtZT48L2xhYmVscm93Pjwvc2VjdGlvbj48L3RkPjx0ZD48c2VjdGlvbj48c2VjdGlvbnRpdGxlPkhvbWU8L3NlY3Rpb250aXRsZT48SG9tZUFkZHJlc3M+SG9tZUFkZHJlc3MxMTwvSG9tZUFkZHJlc3M+PEhvbWVBZGRyZXNzMj5Ib21lQWRkcmVzczIxPC9Ib21lQWRkcmVzczI+PEhvbWVDaXR5PkhvbWVDaXR5MTwvSG9tZUNpdHk+LCA8SG9tZVN0YXRlPkhvbWVTdGF0ZTE8L0hvbWVTdGF0ZT4gPEhvbWVaaXBDb2RlPkhvbWVaaXBDb2RlMTwvSG9tZVppcENvZGU+PEhvbWVDb3VudHJ5PkhvbWVDb3VudHJ5MTwvSG9tZUNvdW50cnk+PFdlYlBhZ2UyPmh0dHA6Ly9XZWJQYWdlMTE8L1dlYlBhZ2UyPjwvc2VjdGlvbj48c2VjdGlvbj48c2VjdGlvbnRpdGxlPldvcms8L3NlY3Rpb250aXRsZT48Sm9iVGl0bGU+Sm9iVGl0bGUxPC9Kb2JUaXRsZT48RGVwYXJ0bWVudD5EZXBhcnRtZW50MTwvRGVwYXJ0bWVudD48Q29tcGFueT5Pcmdhbml6YXRpb24xPC9Db21wYW55PjxXb3JrQWRkcmVzcz5Xb3JrQWRkcmVzczE8L1dvcmtBZGRyZXNzPjxXb3JrQWRkcmVzczI+V29ya0FkZHJlc3MyMTwvV29ya0FkZHJlc3MyPjxXb3JrQ2l0eT5Xb3JrQ2l0eTE8L1dvcmtDaXR5PiwgPFdvcmtTdGF0ZT5Xb3JrU3RhdGUxPC9Xb3JrU3RhdGU+IDxXb3JrWmlwQ29kZT5Xb3JrWmlwQ29kZTE8L1dvcmtaaXBDb2RlPjxXb3JrQ291bnRyeT5Xb3JrQ291bnRyeTE8L1dvcmtDb3VudHJ5PjxXZWJQYWdlMT5odHRwOi8vV2ViUGFnZTIxPC9XZWJQYWdlMT48L3NlY3Rpb24+PC90ZD48L3RyPjwvdGFibGU+PC9kaXJlY3Rvcnk+Cg==";
let smXmlBase64 = "PD94bWwgdmVyc2lvbj0iMS4wIj8+Cjw/eG1sLXN0eWxlc2hlZXQgdHlwZT0idGV4dC9jc3MiIGhyZWY9ImNocm9tZTovL21lc3NhZ2Vib2R5L2NvbnRlbnQvYWRkcmVzc2Jvb2svcHJpbnQuY3NzIj8+CjxkaXJlY3Rvcnk+Cjx0aXRsZSB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMTk5OS94aHRtbCI+QWRkcmVzcyBCb29rPC90aXRsZT4KPEdlbmVyYXRlZE5hbWU+CkRpc3BsYXlOYW1lMTwvR2VuZXJhdGVkTmFtZT4KPHRhYmxlPjx0cj48dGQ+PHNlY3Rpb24+PGxhYmVscm93PjxsYWJlbD5EaXNwbGF5IE5hbWU6IDwvbGFiZWw+PERpc3BsYXlOYW1lPkRpc3BsYXlOYW1lMTwvRGlzcGxheU5hbWU+PC9sYWJlbHJvdz48bGFiZWxyb3c+PGxhYmVsPk5pY2tuYW1lOiA8L2xhYmVsPjxOaWNrTmFtZT5OaWNrTmFtZTE8L05pY2tOYW1lPjwvbGFiZWxyb3c+PFByaW1hcnlFbWFpbD5QcmltYXJ5RW1haWwxQHRlc3QuaW52YWxpZDwvUHJpbWFyeUVtYWlsPjxTZWNvbmRFbWFpbD5TZWNvbmRFbWFpbDHDkEB0ZXN0LmludmFsaWQ8L1NlY29uZEVtYWlsPjxsYWJlbHJvdz48bGFiZWw+U2NyZWVuIE5hbWU6IDwvbGFiZWw+PF9BaW1TY3JlZW5OYW1lPlNjcmVlbk5hbWUxPC9fQWltU2NyZWVuTmFtZT48L2xhYmVscm93Pjwvc2VjdGlvbj48L3RkPjwvdHI+PHRyPjx0ZD48c2VjdGlvbj48c2VjdGlvbnRpdGxlPlBob25lPC9zZWN0aW9udGl0bGU+PGxhYmVscm93PjxsYWJlbD5Xb3JrOiA8L2xhYmVsPjxXb3JrUGhvbmU+V29ya1Bob25lMTwvV29ya1Bob25lPjwvbGFiZWxyb3c+PGxhYmVscm93PjxsYWJlbD5Ib21lOiA8L2xhYmVsPjxIb21lUGhvbmU+SG9tZVBob25lMTwvSG9tZVBob25lPjwvbGFiZWxyb3c+PGxhYmVscm93PjxsYWJlbD5GYXg6IDwvbGFiZWw+PEZheE51bWJlcj5GYXhOdW1iZXIxPC9GYXhOdW1iZXI+PC9sYWJlbHJvdz48bGFiZWxyb3c+PGxhYmVsPlBhZ2VyOiA8L2xhYmVsPjxQYWdlck51bWJlcj5QYWdlck51bWJlcjE8L1BhZ2VyTnVtYmVyPjwvbGFiZWxyb3c+PGxhYmVscm93PjxsYWJlbD5Nb2JpbGU6IDwvbGFiZWw+PENlbGx1bGFyTnVtYmVyPkNlbGx1bGFyTnVtYmVyMTwvQ2VsbHVsYXJOdW1iZXI+PC9sYWJlbHJvdz48L3NlY3Rpb24+PHNlY3Rpb24+PHNlY3Rpb250aXRsZT5PdGhlcjwvc2VjdGlvbnRpdGxlPjxsYWJlbHJvdz48bGFiZWw+Q3VzdG9tIDE6IDwvbGFiZWw+PEN1c3RvbTE+Q3VzdG9tMTE8L0N1c3RvbTE+PC9sYWJlbHJvdz48bGFiZWxyb3c+PGxhYmVsPkN1c3RvbSAyOiA8L2xhYmVsPjxDdXN0b20yPkN1c3RvbTIxPC9DdXN0b20yPjwvbGFiZWxyb3c+PGxhYmVscm93PjxsYWJlbD5DdXN0b20gMzogPC9sYWJlbD48Q3VzdG9tMz5DdXN0b20zMTwvQ3VzdG9tMz48L2xhYmVscm93PjxsYWJlbHJvdz48bGFiZWw+Q3VzdG9tIDQ6IDwvbGFiZWw+PEN1c3RvbTQ+Q3VzdG9tNDE8L0N1c3RvbTQ+PC9sYWJlbHJvdz48Tm90ZXM+Tm90ZXMxPC9Ob3Rlcz48L3NlY3Rpb24+PC90ZD48dGQ+PHNlY3Rpb24+PHNlY3Rpb250aXRsZT5Ib21lPC9zZWN0aW9udGl0bGU+PEhvbWVBZGRyZXNzPkhvbWVBZGRyZXNzMTE8L0hvbWVBZGRyZXNzPjxIb21lQWRkcmVzczI+SG9tZUFkZHJlc3MyMTwvSG9tZUFkZHJlc3MyPjxIb21lQ2l0eT5Ib21lQ2l0eTE8L0hvbWVDaXR5PiwgPEhvbWVTdGF0ZT5Ib21lU3RhdGUxPC9Ib21lU3RhdGU+IDxIb21lWmlwQ29kZT5Ib21lWmlwQ29kZTE8L0hvbWVaaXBDb2RlPjxIb21lQ291bnRyeT5Ib21lQ291bnRyeTE8L0hvbWVDb3VudHJ5PjxXZWJQYWdlMj5odHRwOi8vV2ViUGFnZTExPC9XZWJQYWdlMj48L3NlY3Rpb24+PHNlY3Rpb24+PHNlY3Rpb250aXRsZT5Xb3JrPC9zZWN0aW9udGl0bGU+PEpvYlRpdGxlPkpvYlRpdGxlMTwvSm9iVGl0bGU+PERlcGFydG1lbnQ+RGVwYXJ0bWVudDE8L0RlcGFydG1lbnQ+PENvbXBhbnk+T3JnYW5pemF0aW9uMTwvQ29tcGFueT48V29ya0FkZHJlc3M+V29ya0FkZHJlc3MxPC9Xb3JrQWRkcmVzcz48V29ya0FkZHJlc3MyPldvcmtBZGRyZXNzMjE8L1dvcmtBZGRyZXNzMj48V29ya0NpdHk+V29ya0NpdHkxPC9Xb3JrQ2l0eT4sIDxXb3JrU3RhdGU+V29ya1N0YXRlMTwvV29ya1N0YXRlPiA8V29ya1ppcENvZGU+V29ya1ppcENvZGUxPC9Xb3JrWmlwQ29kZT48V29ya0NvdW50cnk+V29ya0NvdW50cnkxPC9Xb3JrQ291bnRyeT48V2ViUGFnZTE+aHR0cDovL1dlYlBhZ2UyMTwvV2ViUGFnZTE+PC9zZWN0aW9uPjwvdGQ+PC90cj48L3RhYmxlPjwvZGlyZWN0b3J5Pgo=";
let smXmlBase64 =
"PD94bWwgdmVyc2lvbj0iMS4wIj8+Cjw/eG1sLXN0eWxlc2hlZXQgdHlwZT0idGV4dC9jc3MiIGhyZWY9ImNocm9tZTovL21lc3NhZ2Vib2R5L2NvbnRlbnQvYWRkcmVzc2Jvb2svcHJpbnQuY3NzIj8+CjxkaXJlY3Rvcnk+Cjx0aXRsZSB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMTk5OS94aHRtbCI+QWRkcmVzcyBCb29rPC90aXRsZT4KPEdlbmVyYXRlZE5hbWU+CkRpc3BsYXlOYW1lMTwvR2VuZXJhdGVkTmFtZT4KPHRhYmxlPjx0cj48dGQ+PHNlY3Rpb24+PGxhYmVscm93PjxsYWJlbD5EaXNwbGF5IE5hbWU6IDwvbGFiZWw+PERpc3BsYXlOYW1lPkRpc3BsYXlOYW1lMTwvRGlzcGxheU5hbWU+PC9sYWJlbHJvdz48bGFiZWxyb3c+PGxhYmVsPk5pY2tuYW1lOiA8L2xhYmVsPjxOaWNrTmFtZT5OaWNrTmFtZTE8L05pY2tOYW1lPjwvbGFiZWxyb3c+PFByaW1hcnlFbWFpbD5QcmltYXJ5RW1haWwxQHRlc3QuaW52YWxpZDwvUHJpbWFyeUVtYWlsPjxTZWNvbmRFbWFpbD5TZWNvbmRFbWFpbDHDkEB0ZXN0LmludmFsaWQ8L1NlY29uZEVtYWlsPjxsYWJlbHJvdz48bGFiZWw+U2NyZWVuIE5hbWU6IDwvbGFiZWw+PF9BaW1TY3JlZW5OYW1lPlNjcmVlbk5hbWUxPC9fQWltU2NyZWVuTmFtZT48L2xhYmVscm93Pjwvc2VjdGlvbj48L3RkPjwvdHI+PHRyPjx0ZD48c2VjdGlvbj48c2VjdGlvbnRpdGxlPlBob25lPC9zZWN0aW9udGl0bGU+PGxhYmVscm93PjxsYWJlbD5Xb3JrOiA8L2xhYmVsPjxXb3JrUGhvbmU+V29ya1Bob25lMTwvV29ya1Bob25lPjwvbGFiZWxyb3c+PGxhYmVscm93PjxsYWJlbD5Ib21lOiA8L2xhYmVsPjxIb21lUGhvbmU+SG9tZVBob25lMTwvSG9tZVBob25lPjwvbGFiZWxyb3c+PGxhYmVscm93PjxsYWJlbD5GYXg6IDwvbGFiZWw+PEZheE51bWJlcj5GYXhOdW1iZXIxPC9GYXhOdW1iZXI+PC9sYWJlbHJvdz48bGFiZWxyb3c+PGxhYmVsPlBhZ2VyOiA8L2xhYmVsPjxQYWdlck51bWJlcj5QYWdlck51bWJlcjE8L1BhZ2VyTnVtYmVyPjwvbGFiZWxyb3c+PGxhYmVscm93PjxsYWJlbD5Nb2JpbGU6IDwvbGFiZWw+PENlbGx1bGFyTnVtYmVyPkNlbGx1bGFyTnVtYmVyMTwvQ2VsbHVsYXJOdW1iZXI+PC9sYWJlbHJvdz48L3NlY3Rpb24+PHNlY3Rpb24+PHNlY3Rpb250aXRsZT5PdGhlcjwvc2VjdGlvbnRpdGxlPjxsYWJlbHJvdz48bGFiZWw+Q3VzdG9tIDE6IDwvbGFiZWw+PEN1c3RvbTE+Q3VzdG9tMTE8L0N1c3RvbTE+PC9sYWJlbHJvdz48bGFiZWxyb3c+PGxhYmVsPkN1c3RvbSAyOiA8L2xhYmVsPjxDdXN0b20yPkN1c3RvbTIxPC9DdXN0b20yPjwvbGFiZWxyb3c+PGxhYmVscm93PjxsYWJlbD5DdXN0b20gMzogPC9sYWJlbD48Q3VzdG9tMz5DdXN0b20zMTwvQ3VzdG9tMz48L2xhYmVscm93PjxsYWJlbHJvdz48bGFiZWw+Q3VzdG9tIDQ6IDwvbGFiZWw+PEN1c3RvbTQ+Q3VzdG9tNDE8L0N1c3RvbTQ+PC9sYWJlbHJvdz48Tm90ZXM+Tm90ZXMxPC9Ob3Rlcz48L3NlY3Rpb24+PC90ZD48dGQ+PHNlY3Rpb24+PHNlY3Rpb250aXRsZT5Ib21lPC9zZWN0aW9udGl0bGU+PEhvbWVBZGRyZXNzPkhvbWVBZGRyZXNzMTE8L0hvbWVBZGRyZXNzPjxIb21lQWRkcmVzczI+SG9tZUFkZHJlc3MyMTwvSG9tZUFkZHJlc3MyPjxIb21lQ2l0eT5Ib21lQ2l0eTE8L0hvbWVDaXR5PiwgPEhvbWVTdGF0ZT5Ib21lU3RhdGUxPC9Ib21lU3RhdGU+IDxIb21lWmlwQ29kZT5Ib21lWmlwQ29kZTE8L0hvbWVaaXBDb2RlPjxIb21lQ291bnRyeT5Ib21lQ291bnRyeTE8L0hvbWVDb3VudHJ5PjxXZWJQYWdlMj5odHRwOi8vV2ViUGFnZTExPC9XZWJQYWdlMj48L3NlY3Rpb24+PHNlY3Rpb24+PHNlY3Rpb250aXRsZT5Xb3JrPC9zZWN0aW9udGl0bGU+PEpvYlRpdGxlPkpvYlRpdGxlMTwvSm9iVGl0bGU+PERlcGFydG1lbnQ+RGVwYXJ0bWVudDE8L0RlcGFydG1lbnQ+PENvbXBhbnk+T3JnYW5pemF0aW9uMTwvQ29tcGFueT48V29ya0FkZHJlc3M+V29ya0FkZHJlc3MxPC9Xb3JrQWRkcmVzcz48V29ya0FkZHJlc3MyPldvcmtBZGRyZXNzMjE8L1dvcmtBZGRyZXNzMj48V29ya0NpdHk+V29ya0NpdHkxPC9Xb3JrQ2l0eT4sIDxXb3JrU3RhdGU+V29ya1N0YXRlMTwvV29ya1N0YXRlPiA8V29ya1ppcENvZGU+V29ya1ppcENvZGUxPC9Xb3JrWmlwQ29kZT48V29ya0NvdW50cnk+V29ya0NvdW50cnkxPC9Xb3JrQ291bnRyeT48V2ViUGFnZTE+aHR0cDovL1dlYlBhZ2UyMTwvV2ViUGFnZTE+PC9zZWN0aW9uPjwvdGQ+PC90cj48L3RhYmxlPjwvZGlyZWN0b3J5Pgo=";
let XmlBase64Trans = fullCard.translateTo("base64xml");

Просмотреть файл

@ -40,7 +40,9 @@ add_task(async function existingContactUID() {
add_task(async function newContactUID() {
let book = newAddressBookFile();
let contact = Cc["@mozilla.org/addressbook/cardproperty;1"].createInstance(Ci.nsIAbCard);
let contact = Cc["@mozilla.org/addressbook/cardproperty;1"].createInstance(
Ci.nsIAbCard
);
let newContact = book.addCard(contact);
equal(36, newContact.UID.length, "New contact has a UID");
@ -59,7 +61,9 @@ add_task(async function newContactUID() {
add_task(async function newContactWithUID() {
let book = newAddressBookFile();
let contact = Cc["@mozilla.org/addressbook/cardproperty;1"].createInstance(Ci.nsIAbCard);
let contact = Cc["@mozilla.org/addressbook/cardproperty;1"].createInstance(
Ci.nsIAbCard
);
contact.UID = "I'm a UID!";
let newContact = book.addCard(contact);
equal("I'm a UID!", newContact.UID, "New contact has the UID we set");
@ -85,7 +89,11 @@ add_task(async function existingListUID1() {
let directory = MailServices.ab.getDirectory(card.mailListURI);
equal(36, directory.UID.length, "Existing list's directory has a UID");
equal(card.UID, directory.UID, "Existing list's card and directory UIDs match");
equal(
card.UID,
directory.UID,
"Existing list's card and directory UIDs match"
);
await checkFileForUID(card.UID, book.fileName);
});
@ -100,7 +108,11 @@ add_task(async function existingListUID2() {
let card = [...book.childCards].find(c => c.isMailList);
equal(36, card.UID.length, "Existing list's card has a UID");
equal(card.UID, directory.UID, "Existing list's card and directory UIDs match");
equal(
card.UID,
directory.UID,
"Existing list's card and directory UIDs match"
);
await checkFileForUID(card.UID, book.fileName);
});
@ -109,14 +121,25 @@ add_task(async function existingListUID2() {
add_task(async function newListUID() {
let book = newAddressBookFile();
let list = Cc["@mozilla.org/addressbook/directoryproperty;1"].createInstance(Ci.nsIAbDirectory);
let list = Cc["@mozilla.org/addressbook/directoryproperty;1"].createInstance(
Ci.nsIAbDirectory
);
list = book.addMailList(list);
equal(36, list.UID.length, "New list's directory has a UID");
equal(list.UID, MailServices.ab.getDirectory(list.URI).UID, "New reference to list's directory has the same UID");
equal(
list.UID,
MailServices.ab.getDirectory(list.URI).UID,
"New reference to list's directory has the same UID"
);
let bookCards = [...book.childNodes];
ok(!!bookCards.find(c => c.UID == list.UID, "New reference to list has the same UID"));
ok(
!!bookCards.find(
c => c.UID == list.UID,
"New reference to list has the same UID"
)
);
await checkFileForUID(list.UID, book.fileName);
});
@ -124,14 +147,23 @@ add_task(async function newListUID() {
// 3 seems to be the lowest number that works here. I don't know why.
var count = 3;
function newAddressBookFile() {
MailServices.ab.newAddressBook(`book${count}`, `moz-abmdbdirectory://abook-${count}.mab`, 2);
MailServices.ab.newAddressBook(
`book${count}`,
`moz-abmdbdirectory://abook-${count}.mab`,
2
);
let testAB = do_get_file("data/existing.mab");
testAB.copyTo(profD, `abook-${count}.mab`);
Services.prefs.setCharPref(`ldap_2.servers.book${count}.filename`, `abook-${count}.mab`);
Services.prefs.setCharPref(
`ldap_2.servers.book${count}.filename`,
`abook-${count}.mab`
);
let book = MailServices.ab.getDirectory(`moz-abmdbdirectory://abook-${count}.mab`);
let book = MailServices.ab.getDirectory(
`moz-abmdbdirectory://abook-${count}.mab`
);
equal(2, [...book.childCards].length);
count++;

Просмотреть файл

@ -13,8 +13,9 @@ function check_directory(directory) {
var testModification = !directory.readOnly;
dump("Testing " + prefId);
if (testModification)
if (testModification) {
dump(" (with modifications)");
}
dump("...\n");
// Question 1: Is the UUID the preference ID?
@ -22,7 +23,8 @@ function check_directory(directory) {
// Now we need to run through the cards, checking that each card meets the
// requirements.
var seenIds = [], cards = [];
var seenIds = [],
cards = [];
var enumerator = directory.childCards;
while (enumerator.hasMoreElements()) {
let card = enumerator.getNext().QueryInterface(Ci.nsIAbCard);
@ -60,12 +62,14 @@ function check_directory(directory) {
}
// The remaining tests deal with modification of address books.
if (!testModification)
if (!testModification) {
return;
}
// Question 4: Does adding a new card properly set the UUID?
var newCard = Cc["@mozilla.org/addressbook/cardproperty;1"]
.createInstance(Ci.nsIAbCard);
var newCard = Cc["@mozilla.org/addressbook/cardproperty;1"].createInstance(
Ci.nsIAbCard
);
newCard.displayName = "Test User";
newCard.primaryEmail = "user1@test.invalid";
newCard.firstName = "Test";
@ -103,8 +107,9 @@ function run_test() {
loadABFile("data/cardForEmail", kPABData.fileName);
// Step 1: What is the ID of an empty card?
var newCard = Cc["@mozilla.org/addressbook/cardproperty;1"]
.createInstance(Ci.nsIAbCard);
var newCard = Cc["@mozilla.org/addressbook/cardproperty;1"].createInstance(
Ci.nsIAbCard
);
Assert.equal(newCard.uuid, "");
Assert.equal(newCard.directoryId, "");
Assert.equal(newCard.localId, "");

Просмотреть файл

@ -16,7 +16,7 @@ const formatDYM = 6;
const formatMIN = 1;
const formatMAX = 6;
var {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm");
var { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm");
var gSearchDateFormat = 0;
var gSearchDateSeparator;
@ -29,12 +29,15 @@ var gSearchDateLeadingZeros;
*/
function initLocaleShortDateFormat() {
try {
const dateFormatter = new Services.intl.DateTimeFormat(undefined,
{ dateStyle: "short" });
const dateFormatter = new Services.intl.DateTimeFormat(undefined, {
dateStyle: "short",
});
var aDate = new Date(1999, 11, 2);
// Short formats can be space-separated, like 02 Dec 1999.
var dateString = dateFormatter.format(aDate).replace(" 2", "2")
.replace(/ /g, "/");
var dateString = dateFormatter
.format(aDate)
.replace(" 2", "2")
.replace(/ /g, "/");
// find out the separator
var possibleSeparators = "/-.";
@ -48,8 +51,11 @@ function initLocaleShortDateFormat() {
}
// check the format option
if (arrayOfStrings.length != 3) { // no successful split
Cu.reportError(`initLocaleShortDateFormat: could not analyze date format of ${dateString}, defaulting to yyyy/mm/dd`);
if (arrayOfStrings.length != 3) {
// no successful split
Cu.reportError(
`initLocaleShortDateFormat: could not analyze date format of ${dateString}, defaulting to yyyy/mm/dd`
);
} else {
// The date will contain a zero if the system settings include leading zeros.
gSearchDateLeadingZeros = dateString.includes("0");
@ -62,7 +68,8 @@ function initLocaleShortDateFormat() {
} else if (arrayOfStrings[1] == 2) {
// 12.02.1999 or 1999.02.12
gSearchDateFormat = arrayOfStrings[0] == "1999" ? formatYDM : formatMDY;
} else { // implies arrayOfStrings[2] == 2
} else {
// implies arrayOfStrings[2] == 2
// 12.1999.02 or 1999.12.02
gSearchDateFormat = arrayOfStrings[0] == "1999" ? formatYMD : formatMYD;
}
@ -74,14 +81,16 @@ function initLocaleShortDateFormat() {
}
function initializeSearchDateFormat() {
if (gSearchDateFormat > 0)
if (gSearchDateFormat > 0) {
return;
}
// get a search date format option and a separator
try {
gSearchDateFormat =
Services.prefs.getComplexValue("mailnews.search_date_format",
Ci.nsIPrefLocalizedString).data;
gSearchDateFormat = Services.prefs.getComplexValue(
"mailnews.search_date_format",
Ci.nsIPrefLocalizedString
).data;
gSearchDateFormat = parseInt(gSearchDateFormat);
@ -90,17 +99,20 @@ function initializeSearchDateFormat() {
initLocaleShortDateFormat();
} else {
// initialize the search date format based on preferences
if (gSearchDateFormat < formatMIN || gSearchDateFormat > formatMAX)
if (gSearchDateFormat < formatMIN || gSearchDateFormat > formatMAX) {
gSearchDateFormat = formatYMD;
}
gSearchDateSeparator =
Services.prefs.getComplexValue("mailnews.search_date_separator",
Ci.nsIPrefLocalizedString).data;
gSearchDateSeparator = Services.prefs.getComplexValue(
"mailnews.search_date_separator",
Ci.nsIPrefLocalizedString
).data;
gSearchDateLeadingZeros =
(Services.prefs.getComplexValue(
"mailnews.search_date_leading_zeros",
Ci.nsIPrefLocalizedString).data == "true");
Services.prefs.getComplexValue(
"mailnews.search_date_leading_zeros",
Ci.nsIPrefLocalizedString
).data == "true";
}
} catch (e) {
Cu.reportError("initializeSearchDateFormat: caught an exception: " + e);
@ -128,12 +140,14 @@ function convertDateToString(time) {
initializeSearchDateFormat();
var year = time.getFullYear();
var month = time.getMonth() + 1; // since js month is 0-11
if (gSearchDateLeadingZeros && month < 10)
var month = time.getMonth() + 1; // since js month is 0-11
if (gSearchDateLeadingZeros && month < 10) {
month = "0" + month;
var date = time.getDate(); // day
if (gSearchDateLeadingZeros && date < 10)
}
var date = time.getDate(); // day
if (gSearchDateLeadingZeros && date < 10) {
date = "0" + date;
}
var dateStr;
var sep = gSearchDateSeparator;
@ -146,7 +160,7 @@ function convertDateToString(time) {
dateStr = year + sep + date + sep + month;
break;
case formatMDY:
dateStr = month + sep + date + sep + year;
dateStr = month + sep + date + sep + year;
break;
case formatMYD:
dateStr = month + sep + year + sep + date;
@ -212,5 +226,5 @@ function convertStringToPRTime(str) {
// JavaScript time is in milliseconds, PRTime is in microseconds
// so multiply by 1000 when converting
return (time.getTime() * 1000);
return time.getTime() * 1000;
}

Разница между файлами не показана из-за своего большого размера Загрузить разницу

Просмотреть файл

@ -4,8 +4,8 @@
/* import-globals-from retention.js */
var {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm");
var {Gloda} = ChromeUtils.import("resource:///modules/gloda/gloda.js");
var { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm");
var { Gloda } = ChromeUtils.import("resource:///modules/gloda/gloda.js");
var gMsgFolder;
var gLockedPref = null;
@ -25,29 +25,33 @@ var gFolderPropsSink = {
setFolderTypeDescription(folderDescription) {
var folderTypeLabel = document.getElementById("folderDescription.text");
if (folderTypeLabel)
if (folderTypeLabel) {
folderTypeLabel.setAttribute("value", folderDescription);
}
},
setFolderPermissions(folderPermissions) {
var permissionsLabel = document.getElementById("folderPermissions.text");
var descTextNode = document.createTextNode(folderPermissions);
var descTextNode = document.createTextNode(folderPermissions);
permissionsLabel.appendChild(descTextNode);
},
serverDoesntSupportACL() {
var typeLabel = document.getElementById("folderTypeLabel");
if (typeLabel)
if (typeLabel) {
typeLabel.setAttribute("hidden", "true");
}
var permissionsLabel = document.getElementById("permissionsDescLabel");
if (permissionsLabel)
if (permissionsLabel) {
permissionsLabel.setAttribute("hidden", "true");
}
},
setQuotaStatus(folderQuotaStatus) {
var quotaStatusLabel = document.getElementById("folderQuotaStatus");
if (quotaStatusLabel)
if (quotaStatusLabel) {
quotaStatusLabel.setAttribute("value", folderQuotaStatus);
}
},
showQuotaData(showData) {
@ -62,26 +66,38 @@ var gFolderPropsSink = {
setQuotaData(root, usedKB, maxKB) {
var quotaRoot = document.getElementById("quotaRoot");
if (quotaRoot)
if (quotaRoot) {
quotaRoot.setAttribute("value", '"' + root + '"');
}
var percentage = (maxKB != 0) ? Math.round(usedKB / maxKB * 100) : 0;
var percentage = maxKB != 0 ? Math.round((usedKB / maxKB) * 100) : 0;
var quotaPercentageBar = document.getElementById("quotaPercentageBar");
if (quotaPercentageBar)
if (quotaPercentageBar) {
quotaPercentageBar.setAttribute("value", percentage);
}
var bundle = document.getElementById("bundle_messenger");
if (bundle) {
var usedFreeCaption = bundle.getFormattedString("quotaUsedFree", [usedKB, maxKB], 2);
var usedFreeCaption = bundle.getFormattedString(
"quotaUsedFree",
[usedKB, maxKB],
2
);
var quotaCaption = document.getElementById("quotaUsedFree");
if (quotaCaption)
if (quotaCaption) {
quotaCaption.setAttribute("value", usedFreeCaption);
}
var percentUsedCaption = bundle.getFormattedString("quotaPercentUsed", [percentage], 1);
var percentUsedCaption = bundle.getFormattedString(
"quotaPercentUsed",
[percentage],
1
);
var percentUsed = document.getElementById("quotaPercentUsed");
if (percentUsed)
if (percentUsed) {
percentUsed.setAttribute("value", percentUsedCaption);
}
}
},
};
@ -99,24 +115,33 @@ function folderPropsOKButton(event) {
// Log to the Error Console the charset value for the folder
// if it is unknown to us. Value will be preserved by the menu-item.
if (folderCharsetList.selectedIndex == -1) {
Cu.reportError("Unknown folder encoding; folder=" +
gMsgFolder.name + ", charset=" + gMsgFolder.charset);
Cu.reportError(
"Unknown folder encoding; folder=" +
gMsgFolder.name +
", charset=" +
gMsgFolder.charset
);
}
gMsgFolder.charset = folderCharsetList.getAttribute("value");
gMsgFolder.charsetOverride = document.getElementById("folderCharsetOverride")
.checked;
gMsgFolder.charsetOverride = document.getElementById(
"folderCharsetOverride"
).checked;
if (document.getElementById("offline.selectForOfflineFolder").checked ||
document.getElementById("offline.selectForOfflineNewsgroup").checked)
if (
document.getElementById("offline.selectForOfflineFolder").checked ||
document.getElementById("offline.selectForOfflineNewsgroup").checked
) {
gMsgFolder.setFlag(Ci.nsMsgFolderFlags.Offline);
else
} else {
gMsgFolder.clearFlag(Ci.nsMsgFolderFlags.Offline);
}
if (document.getElementById("folderCheckForNewMessages").checked)
if (document.getElementById("folderCheckForNewMessages").checked) {
gMsgFolder.setFlag(Ci.nsMsgFolderFlags.CheckNew);
else
} else {
gMsgFolder.clearFlag(Ci.nsMsgFolderFlags.CheckNew);
}
let glodaCheckbox = document.getElementById("folderIncludeInGlobalSearch");
if (!glodaCheckbox.hidden) {
@ -125,20 +150,29 @@ function folderPropsOKButton(event) {
// have a priority set.
Gloda.resetFolderIndexingPriority(gMsgFolder, true);
} else {
Gloda.setFolderIndexingPriority(gMsgFolder,
Gloda.getFolderForFolder(gMsgFolder).kIndexingNeverPriority);
Gloda.setFolderIndexingPriority(
gMsgFolder,
Gloda.getFolderForFolder(gMsgFolder).kIndexingNeverPriority
);
}
}
var retentionSettings = saveCommonRetentionSettings(gMsgFolder.retentionSettings);
retentionSettings.useServerDefaults = document.getElementById("retention.useDefault").checked;
var retentionSettings = saveCommonRetentionSettings(
gMsgFolder.retentionSettings
);
retentionSettings.useServerDefaults = document.getElementById(
"retention.useDefault"
).checked;
gMsgFolder.retentionSettings = retentionSettings;
}
try {
// This throws an exception when an illegal folder name was entered.
top.okCallback(document.getElementById("name").value, window.arguments[0].name,
gMsgFolder.URI);
top.okCallback(
document.getElementById("name").value,
window.arguments[0].name,
gMsgFolder.URI
);
} catch (e) {
event.preventDefault();
}
@ -192,24 +226,39 @@ function folderPropsOnLoad() {
// Decode the displayed mailbox:// URL as it's useful primarily for debugging,
// whereas imap and news urls are sent around.
locationTextbox.value = (serverType == "imap" || serverType == "nntp") ?
gMsgFolder.folderURL : decodeURI(gMsgFolder.folderURL);
locationTextbox.value =
serverType == "imap" || serverType == "nntp"
? gMsgFolder.folderURL
: decodeURI(gMsgFolder.folderURL);
if (gMsgFolder.canRename)
if (gMsgFolder.canRename) {
document.getElementById("name").removeAttribute("readonly");
}
if (gMsgFolder.getFlag(Ci.nsMsgFolderFlags.Offline)) {
if (serverType == "imap" || serverType == "pop3")
document.getElementById("offline.selectForOfflineFolder").checked = true;
if (serverType == "imap" || serverType == "pop3") {
document.getElementById(
"offline.selectForOfflineFolder"
).checked = true;
}
if (serverType == "nntp")
document.getElementById("offline.selectForOfflineNewsgroup").checked = true;
if (serverType == "nntp") {
document.getElementById(
"offline.selectForOfflineNewsgroup"
).checked = true;
}
} else {
if (serverType == "imap" || serverType == "pop3")
document.getElementById("offline.selectForOfflineFolder").checked = false;
if (serverType == "imap" || serverType == "pop3") {
document.getElementById(
"offline.selectForOfflineFolder"
).checked = false;
}
if (serverType == "nntp")
document.getElementById("offline.selectForOfflineNewsgroup").checked = false;
if (serverType == "nntp") {
document.getElementById(
"offline.selectForOfflineNewsgroup"
).checked = false;
}
}
// select the menu item
@ -217,18 +266,24 @@ function folderPropsOnLoad() {
folderCharsetList.value = gMsgFolder.charset;
// set override checkbox
document.getElementById("folderCharsetOverride").checked = gMsgFolder.charsetOverride;
document.getElementById("folderCharsetOverride").checked =
gMsgFolder.charsetOverride;
// set check for new mail checkbox
document.getElementById("folderCheckForNewMessages").checked =
gMsgFolder.getFlag(Ci.nsMsgFolderFlags.CheckNew);
document.getElementById(
"folderCheckForNewMessages"
).checked = gMsgFolder.getFlag(Ci.nsMsgFolderFlags.CheckNew);
// if gloda indexing is off, hide the related checkbox
var glodaCheckbox = document.getElementById("folderIncludeInGlobalSearch");
var glodaEnabled = Services.prefs
.getBoolPref("mailnews.database.global.indexer.enabled");
if (!glodaEnabled || (gMsgFolder.flags & (Ci.nsMsgFolderFlags.Queue |
Ci.nsMsgFolderFlags.Newsgroup))) {
var glodaEnabled = Services.prefs.getBoolPref(
"mailnews.database.global.indexer.enabled"
);
if (
!glodaEnabled ||
gMsgFolder.flags &
(Ci.nsMsgFolderFlags.Queue | Ci.nsMsgFolderFlags.Newsgroup)
) {
glodaCheckbox.hidden = true;
} else {
// otherwise, the user can choose whether this file gets indexed
@ -240,31 +295,35 @@ function folderPropsOnLoad() {
if (serverType == "imap") {
var imapFolder = gMsgFolder.QueryInterface(Ci.nsIMsgImapMailFolder);
if (imapFolder)
if (imapFolder) {
imapFolder.fillInFolderProps(gFolderPropsSink);
}
}
var retentionSettings = gMsgFolder.retentionSettings;
initCommonRetentionSettings(retentionSettings);
document.getElementById("retention.useDefault").checked = retentionSettings.useServerDefaults;
document.getElementById("retention.useDefault").checked =
retentionSettings.useServerDefaults;
// set folder sizes
let numberOfMsgs = gMsgFolder.getTotalMessages(false);
if (numberOfMsgs >= 0)
if (numberOfMsgs >= 0) {
document.getElementById("numberOfMessages").value = numberOfMsgs;
}
try {
let sizeOnDisk = Cc["@mozilla.org/messenger;1"]
.createInstance(Ci.nsIMessenger)
.formatFileSize(gMsgFolder.sizeOnDisk, true);
.createInstance(Ci.nsIMessenger)
.formatFileSize(gMsgFolder.sizeOnDisk, true);
document.getElementById("sizeOnDisk").value = sizeOnDisk;
} catch (e) {}
// select the initial tab
if (window.arguments[0].tabID) {
try {
document.getElementById("folderPropTabBox").selectedTab =
document.getElementById(window.arguments[0].tabID);
document.getElementById(
"folderPropTabBox"
).selectedTab = document.getElementById(window.arguments[0].tabID);
} catch (ex) {}
}
onCheckKeepMsg();
@ -277,8 +336,9 @@ function hideShowControls(serverType) {
for (var i = 0; i < len; i++) {
var control = controls[i];
var hideFor = control.getAttribute("hidefor");
if (!hideFor)
if (!hideFor) {
throw new Error("hidefor empty");
}
// hide unsupported server type
// adding support for hiding multiple server types using hideFor="server1,server2"
@ -300,21 +360,29 @@ function hideShowControls(serverType) {
if (imapFolder) {
var privilegesButton = document.getElementById("imap.FolderPrivileges");
if (privilegesButton) {
if (!imapFolder.hasAdminUrl)
if (!imapFolder.hasAdminUrl) {
privilegesButton.setAttribute("hidden", "true");
}
}
}
} catch (ex) {}
if (gMsgFolder) {
// Hide "check for new mail" checkbox if this is an Inbox.
if (gMsgFolder.getFlag(Ci.nsMsgFolderFlags.Inbox))
if (gMsgFolder.getFlag(Ci.nsMsgFolderFlags.Inbox)) {
document.getElementById("folderCheckForNewMessages").hidden = true;
}
// Retention policy doesn't apply to Drafts/Templates/Outbox.
if (gMsgFolder.isSpecialFolder(Ci.nsMsgFolderFlags.Drafts |
Ci.nsMsgFolderFlags.Templates |
Ci.nsMsgFolderFlags.Queue, true))
if (
gMsgFolder.isSpecialFolder(
Ci.nsMsgFolderFlags.Drafts |
Ci.nsMsgFolderFlags.Templates |
Ci.nsMsgFolderFlags.Queue,
true
)
) {
document.getElementById("Retention").hidden = true;
}
}
}
@ -325,13 +393,13 @@ function onOfflineFolderDownload() {
function onFolderPrivileges() {
var imapFolder = gMsgFolder.QueryInterface(Ci.nsIMsgImapMailFolder);
if (imapFolder)
if (imapFolder) {
imapFolder.folderPrivileges(window.arguments[0].msgWindow);
}
// let's try closing the modal dialog to see if it fixes the various problems running this url
window.close();
}
function onUseDefaultRetentionSettings() {
var useDefault = document.getElementById("retention.useDefault").checked;
document.getElementById("retention.keepMsg").disabled = useDefault;
@ -341,9 +409,9 @@ function onUseDefaultRetentionSettings() {
var keepMsg = document.getElementById("retention.keepMsg").value;
const nsIMsgRetentionSettings = Ci.nsIMsgRetentionSettings;
document.getElementById("retention.keepOldMsgMin").disabled =
useDefault || (keepMsg != nsIMsgRetentionSettings.nsMsgRetainByAge);
useDefault || keepMsg != nsIMsgRetentionSettings.nsMsgRetainByAge;
document.getElementById("retention.keepNewMsgMin").disabled =
useDefault || (keepMsg != nsIMsgRetentionSettings.nsMsgRetainByNumHeaders);
useDefault || keepMsg != nsIMsgRetentionSettings.nsMsgRetainByNumHeaders;
}
function RebuildSummaryInformation() {

Просмотреть файл

@ -73,10 +73,12 @@ PROTO_TREE_VIEW.prototype = {
hasNextSibling(aIndex, aNextIndex) {
let targetLevel = this._rowMap[aIndex].level;
for (let i = aNextIndex + 1; i < this._rowMap.length; i++) {
if (this._rowMap[i].level == targetLevel)
if (this._rowMap[i].level == targetLevel) {
return true;
if (this._rowMap[i].level < targetLevel)
}
if (this._rowMap[i].level < targetLevel) {
return false;
}
}
return false;
},
@ -157,8 +159,9 @@ PROTO_TREE_VIEW.prototype = {
// Remove us from the persist map
let index = this._persistOpenMap.indexOf(this._rowMap[aIndex].id);
if (index != -1)
if (index != -1) {
this._persistOpenMap.splice(index, 1);
}
// Notify the tree of changes
if (this._tree) {
@ -174,17 +177,20 @@ PROTO_TREE_VIEW.prototype = {
// Add this container to the persist map
let id = this._rowMap[aIndex].id;
if (!this._persistOpenMap.includes(id))
if (!this._persistOpenMap.includes(id)) {
this._persistOpenMap.push(id);
}
// Notify the tree of changes
if (this._tree)
if (this._tree) {
this._tree.rowCountChanged(aIndex + 1, this._rowMap.length - oldCount);
}
}
// Invalidate the toggled row, so that the open/closed marker changes
if (this._tree)
if (this._tree) {
this._tree.invalidateRow(aIndex);
}
},
// We don't implement any of these at the moment
@ -194,7 +200,9 @@ PROTO_TREE_VIEW.prototype = {
setCellText(aRow, aCol, aValue) {},
setCellValue(aRow, aCol, aValue) {},
getCellValue(aRow, aCol) {},
getColumnProperties(aCol) { return ""; },
getColumnProperties(aCol) {
return "";
},
getImageSrc(aRow, aCol) {},
getProgressMode(aRow, aCol) {},
cycleCell(aRow, aCol) {},
@ -216,8 +224,9 @@ PROTO_TREE_VIEW.prototype = {
_restoreOpenStates() {
// Note that as we iterate through here, .length may grow
for (let i = 0; i < this._rowMap.length; i++) {
if (this._persistOpenMap.includes(this._rowMap[i].id))
if (this._persistOpenMap.includes(this._rowMap[i].id)) {
this.toggleOpenState(i);
}
}
},

Просмотреть файл

@ -2,31 +2,33 @@
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
/* functions use for junk processing commands
*
* TODO: These functions make the false assumption that a view only contains
* a single folder. This is not true for XF saved searches.
*
* globals prerequisites used:
*
* window.MsgStatusFeedback
*
* One of:
* GetSelectedIndices(view) (in suite)
* gFolderDisplay (in mail)
*
* messenger
* gDBView
* MsgJunkMailInfo(aCheckFirstUse)
* msgWindow
*/
/* functions use for junk processing commands
*
* TODO: These functions make the false assumption that a view only contains
* a single folder. This is not true for XF saved searches.
*
* globals prerequisites used:
*
* window.MsgStatusFeedback
*
* One of:
* GetSelectedIndices(view) (in suite)
* gFolderDisplay (in mail)
*
* messenger
* gDBView
* MsgJunkMailInfo(aCheckFirstUse)
* msgWindow
*/
/* globals ClearMessagePane, gDBView, gFolderDisplay, MarkSelectedMessagesRead, messenger,
MsgJunkMailInfo, msgWindow, nsMsgViewIndex_None */
var {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm");
var {MailServices} = ChromeUtils.import("resource:///modules/MailServices.jsm");
var {MailUtils} = ChromeUtils.import("resource:///modules/MailUtils.jsm");
var { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm");
var { MailServices } = ChromeUtils.import(
"resource:///modules/MailServices.jsm"
);
var { MailUtils } = ChromeUtils.import("resource:///modules/MailUtils.jsm");
/*
* determineActionsForJunkMsgs
@ -55,8 +57,7 @@ function determineActionsForJunkMsgs(aFolder) {
// move only when the corresponding setting is activated
// and the currently viewed folder is not the junk folder.
if (spamSettings.moveOnSpam &&
!aFolder.getFlag(Ci.nsMsgFolderFlags.Junk)) {
if (spamSettings.moveOnSpam && !aFolder.getFlag(Ci.nsMsgFolderFlags.Junk)) {
var spamFolderURI = spamSettings.spamFolderURI;
if (!spamFolderURI) {
// XXX TODO
@ -86,31 +87,60 @@ function determineActionsForJunkMsgs(aFolder) {
* nsIArray containing headers (nsIMsgDBHdr) of new good messages
*/
function performActionsOnJunkMsgs(aFolder, aJunkMsgHdrs, aGoodMsgHdrs) {
if (aFolder instanceof Ci.nsIMsgImapMailFolder) { // need to update IMAP custom flags
if (aFolder instanceof Ci.nsIMsgImapMailFolder) {
// need to update IMAP custom flags
if (aJunkMsgHdrs.length) {
var junkMsgKeys = [];
for (let i = 0; i < aJunkMsgHdrs.length; i++)
junkMsgKeys[i] = aJunkMsgHdrs.queryElementAt(i, Ci.nsIMsgDBHdr).messageKey;
aFolder.storeCustomKeywords(null, "Junk", "NonJunk", junkMsgKeys, junkMsgKeys.length);
for (let i = 0; i < aJunkMsgHdrs.length; i++) {
junkMsgKeys[i] = aJunkMsgHdrs.queryElementAt(
i,
Ci.nsIMsgDBHdr
).messageKey;
}
aFolder.storeCustomKeywords(
null,
"Junk",
"NonJunk",
junkMsgKeys,
junkMsgKeys.length
);
}
if (aGoodMsgHdrs.length) {
let goodMsgKeys = [];
for (let i = 0; i < aGoodMsgHdrs.length; i++)
goodMsgKeys[i] = aGoodMsgHdrs.queryElementAt(i, Ci.nsIMsgDBHdr).messageKey;
aFolder.storeCustomKeywords(null, "NonJunk", "Junk", goodMsgKeys, goodMsgKeys.length);
for (let i = 0; i < aGoodMsgHdrs.length; i++) {
goodMsgKeys[i] = aGoodMsgHdrs.queryElementAt(
i,
Ci.nsIMsgDBHdr
).messageKey;
}
aFolder.storeCustomKeywords(
null,
"NonJunk",
"Junk",
goodMsgKeys,
goodMsgKeys.length
);
}
}
if (aJunkMsgHdrs.length) {
var actionParams = determineActionsForJunkMsgs(aFolder);
if (actionParams.markRead)
if (actionParams.markRead) {
aFolder.markMessagesRead(aJunkMsgHdrs, true);
}
if (actionParams.junkTargetFolder)
MailServices.copy
.CopyMessages(aFolder, aJunkMsgHdrs, actionParams.junkTargetFolder,
true /* isMove */, null, msgWindow, true /* allow undo */);
if (actionParams.junkTargetFolder) {
MailServices.copy.CopyMessages(
aFolder,
aJunkMsgHdrs,
actionParams.junkTargetFolder,
true /* isMove */,
null,
msgWindow,
true /* allow undo */
);
}
}
}
@ -128,10 +158,12 @@ function performActionsOnJunkMsgs(aFolder, aJunkMsgHdrs, aGoodMsgHdrs) {
function MessageClassifier(aFolder, aTotalMessages) {
this.mFolder = aFolder;
this.mJunkMsgHdrs = Cc["@mozilla.org/array;1"]
.createInstance(Ci.nsIMutableArray);
this.mGoodMsgHdrs = Cc["@mozilla.org/array;1"]
.createInstance(Ci.nsIMutableArray);
this.mJunkMsgHdrs = Cc["@mozilla.org/array;1"].createInstance(
Ci.nsIMutableArray
);
this.mGoodMsgHdrs = Cc["@mozilla.org/array;1"].createInstance(
Ci.nsIMutableArray
);
this.mMessages = {};
this.mMessageQueue = [];
this.mTotalMessages = aTotalMessages;
@ -154,21 +186,28 @@ MessageClassifier.prototype = {
*/
analyzeMessage(aMsgHdr, aSpamSettings) {
var junkscoreorigin = aMsgHdr.getStringProperty("junkscoreorigin");
if (junkscoreorigin == "user") // don't override user-set junk status
if (junkscoreorigin == "user") {
// don't override user-set junk status
return;
}
// check whitelisting
if (aSpamSettings.checkWhiteList(aMsgHdr)) {
// message is ham from whitelist
var db = aMsgHdr.folder.msgDatabase;
db.setStringProperty(aMsgHdr.messageKey, "junkscore",
Ci.nsIJunkMailPlugin.IS_HAM_SCORE);
db.setStringProperty(
aMsgHdr.messageKey,
"junkscore",
Ci.nsIJunkMailPlugin.IS_HAM_SCORE
);
db.setStringProperty(aMsgHdr.messageKey, "junkscoreorigin", "whitelist");
this.mGoodMsgHdrs.appendElement(aMsgHdr);
return;
}
var messageURI = aMsgHdr.folder.generateMessageURI(aMsgHdr.messageKey) + "?fetchCompleteMessage=true";
var messageURI =
aMsgHdr.folder.generateMessageURI(aMsgHdr.messageKey) +
"?fetchCompleteMessage=true";
this.mMessages[messageURI] = aMsgHdr;
if (this.firstMessage) {
this.firstMessage = false;
@ -192,11 +231,14 @@ MessageClassifier.prototype = {
* 0 - 100 indicator of junk likelihood, with 100 meaning probably junk
*/
onMessageClassified(aClassifiedMsgURI, aClassification, aJunkPercent) {
if (!aClassifiedMsgURI)
return; // ignore end of batch
if (!aClassifiedMsgURI) {
return;
} // ignore end of batch
var nsIJunkMailPlugin = Ci.nsIJunkMailPlugin;
var score = (aClassification == nsIJunkMailPlugin.JUNK) ?
nsIJunkMailPlugin.IS_SPAM_SCORE : nsIJunkMailPlugin.IS_HAM_SCORE;
var score =
aClassification == nsIJunkMailPlugin.JUNK
? nsIJunkMailPlugin.IS_SPAM_SCORE
: nsIJunkMailPlugin.IS_HAM_SCORE;
const statusDisplayInterval = 1000; // milliseconds between status updates
// set these props via the db (instead of the message header
@ -208,10 +250,11 @@ MessageClassifier.prototype = {
db.setStringProperty(msgHdr.messageKey, "junkscoreorigin", "plugin");
db.setStringProperty(msgHdr.messageKey, "junkpercent", aJunkPercent);
if (aClassification == nsIJunkMailPlugin.JUNK)
if (aClassification == nsIJunkMailPlugin.JUNK) {
this.mJunkMsgHdrs.appendElement(msgHdr);
else if (aClassification == nsIJunkMailPlugin.GOOD)
} else if (aClassification == nsIJunkMailPlugin.GOOD) {
this.mGoodMsgHdrs.appendElement(msgHdr);
}
var nextMsgURI = this.mMessageQueue.shift();
if (nextMsgURI) {
@ -219,21 +262,31 @@ MessageClassifier.prototype = {
if (Date.now() > this.lastStatusTime + statusDisplayInterval) {
this.lastStatusTime = Date.now();
var percentDone = 0;
if (this.mTotalMessages)
percentDone = Math.round(this.mProcessedMessages * 100 / this.mTotalMessages);
if (this.mTotalMessages) {
percentDone = Math.round(
(this.mProcessedMessages * 100) / this.mTotalMessages
);
}
var percentStr = percentDone + "%";
window.MsgStatusFeedback.showStatusString(
document.getElementById("bundle_messenger")
.getFormattedString("junkAnalysisPercentComplete",
[percentStr]));
document
.getElementById("bundle_messenger")
.getFormattedString("junkAnalysisPercentComplete", [percentStr])
);
}
MailServices.junk.classifyMessage(nextMsgURI, msgWindow, this);
} else {
window.MsgStatusFeedback.showStatusString(
document.getElementById("bundle_messenger")
.getString("processingJunkMessages"));
performActionsOnJunkMsgs(this.mFolder, this.mJunkMsgHdrs, this.mGoodMsgHdrs);
document
.getElementById("bundle_messenger")
.getString("processingJunkMessages")
);
performActionsOnJunkMsgs(
this.mFolder,
this.mJunkMsgHdrs,
this.mGoodMsgHdrs
);
window.MsgStatusFeedback.showStatusString("");
}
},
@ -244,14 +297,18 @@ MessageClassifier.prototype = {
*
* Filter all messages in the current folder for junk
*/
function filterFolderForJunk() { processFolderForJunk(true); }
function filterFolderForJunk() {
processFolderForJunk(true);
}
/*
* analyzeMessagesForJunk
*
* Filter selected messages in the current folder for junk
*/
function analyzeMessagesForJunk() { processFolderForJunk(false); }
function analyzeMessagesForJunk() {
processFolderForJunk(false);
}
/*
* processFolderForJunk
@ -269,15 +326,18 @@ function processFolderForJunk(aAll) {
gDBView.doCommand(Ci.nsMsgViewCommandType.expandAll);
var treeView = gDBView.QueryInterface(Ci.nsITreeView);
var count = treeView.rowCount;
if (!count)
if (!count) {
return;
}
} else {
// suite uses GetSelectedIndices, mail uses gFolderDisplay.selectedMessages
indices = typeof window.GetSelectedIndices != "undefined" ?
window.GetSelectedIndices(gDBView) :
gFolderDisplay.selectedIndices;
if (!indices || !indices.length)
indices =
typeof window.GetSelectedIndices != "undefined"
? window.GetSelectedIndices(gDBView)
: gFolderDisplay.selectedIndices;
if (!indices || !indices.length) {
return;
}
}
var totalMessages = aAll ? count : indices.length;
@ -292,10 +352,13 @@ function processFolderForJunk(aAll) {
continue;
}
}
if (!tmpMsgURI)
if (!tmpMsgURI) {
return;
}
var tmpMsgHdr = messenger.messageServiceFromURI(tmpMsgURI).messageURIToMsgHdr(tmpMsgURI);
var tmpMsgHdr = messenger
.messageServiceFromURI(tmpMsgURI)
.messageURIToMsgHdr(tmpMsgURI);
var spamSettings = tmpMsgHdr.folder.server.spamSettings;
// create a classifier instance to classify messages in the folder.
@ -305,16 +368,22 @@ function processFolderForJunk(aAll) {
let index = aAll ? i : indices[i];
try {
var msgURI = gDBView.getURIForViewIndex(index);
var msgHdr = messenger.messageServiceFromURI(msgURI).messageURIToMsgHdr(msgURI);
var msgHdr = messenger
.messageServiceFromURI(msgURI)
.messageURIToMsgHdr(msgURI);
msgClassifier.analyzeMessage(msgHdr, spamSettings);
} catch (ex) {
// blow off errors here - dummy headers will fail
}
}
if (msgClassifier.firstMessage) // the async plugin was not used, maybe all whitelisted?
performActionsOnJunkMsgs(msgClassifier.mFolder,
msgClassifier.mJunkMsgHdrs,
msgClassifier.mGoodMsgHdrs);
if (msgClassifier.firstMessage) {
// the async plugin was not used, maybe all whitelisted?
performActionsOnJunkMsgs(
msgClassifier.mFolder,
msgClassifier.mJunkMsgHdrs,
msgClassifier.mGoodMsgHdrs
);
}
}
function JunkSelectedMessages(setAsJunk) {
@ -326,11 +395,16 @@ function JunkSelectedMessages(setAsJunk) {
// Note that this behaviour should match the one in the back end for marking
// as junk via clicking the 'junk' column.
if (setAsJunk && Services.prefs.getBoolPref("mailnews.ui.junk.manualMarkAsJunkMarksRead"))
if (
setAsJunk &&
Services.prefs.getBoolPref("mailnews.ui.junk.manualMarkAsJunkMarksRead")
) {
MarkSelectedMessagesRead(true);
}
gDBView.doCommand(setAsJunk ? Ci.nsMsgViewCommandType.junk
: Ci.nsMsgViewCommandType.unjunk);
gDBView.doCommand(
setAsJunk ? Ci.nsMsgViewCommandType.junk : Ci.nsMsgViewCommandType.unjunk
);
}
/**
@ -345,18 +419,28 @@ function deleteJunkInFolder() {
// use direct folder commands if possible so we don't mess with the selection
let selectedFolder = gFolderDisplay.displayedFolder;
if (!selectedFolder.getFlag(Ci.nsMsgFolderFlags.Virtual)) {
var junkMsgHdrs = Cc["@mozilla.org/array;1"]
.createInstance(Ci.nsIMutableArray);
var junkMsgHdrs = Cc["@mozilla.org/array;1"].createInstance(
Ci.nsIMutableArray
);
var enumerator = gDBView.msgFolder.messages;
while (enumerator.hasMoreElements()) {
let msgHdr = enumerator.getNext().QueryInterface(Ci.nsIMsgDBHdr);
let junkScore = msgHdr.getStringProperty("junkscore");
if (junkScore == Ci.nsIJunkMailPlugin.IS_SPAM_SCORE)
if (junkScore == Ci.nsIJunkMailPlugin.IS_SPAM_SCORE) {
junkMsgHdrs.appendElement(msgHdr);
}
}
if (junkMsgHdrs.length)
gDBView.msgFolder.deleteMessages(junkMsgHdrs, msgWindow, false, false, null, true);
if (junkMsgHdrs.length) {
gDBView.msgFolder.deleteMessages(
junkMsgHdrs,
msgWindow,
false,
false,
null,
true
);
}
return junkMsgHdrs.length;
}
@ -367,8 +451,9 @@ function deleteJunkInFolder() {
var treeView = gDBView.QueryInterface(Ci.nsITreeView);
var count = treeView.rowCount;
if (!count)
if (!count) {
return 0;
}
var treeSelection = treeView.selection;
@ -383,9 +468,11 @@ function deleteJunkInFolder() {
} catch (ex) {
continue; // blow off errors for dummy rows
}
let msgHdr = messenger.messageServiceFromURI(messageUri).messageURIToMsgHdr(messageUri);
let msgHdr = messenger
.messageServiceFromURI(messageUri)
.messageURIToMsgHdr(messageUri);
let junkScore = msgHdr.getStringProperty("junkscore");
var isJunk = (junkScore == Ci.nsIJunkMailPlugin.IS_SPAM_SCORE);
var isJunk = junkScore == Ci.nsIJunkMailPlugin.IS_SPAM_SCORE;
// if the message is junk, select it.
if (isJunk) {
// only do this once
@ -403,8 +490,9 @@ function deleteJunkInFolder() {
// if we didn't clear the selection
// there was no junk, so bail.
if (!clearedSelection)
if (!clearedSelection) {
return 0;
}
treeSelection.selectEventsSuppressed = false;
// delete the selected messages

Просмотреть файл

@ -3,7 +3,7 @@
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
var {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm");
var { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm");
var gLogView;
var gLogFile;

Просмотреть файл

@ -5,8 +5,8 @@
/* import-globals-from dateFormat.js */
var MILLISECONDS_PER_HOUR = 60 * 60 * 1000;
var MICROSECONDS_PER_DAY = 1000 * MILLISECONDS_PER_HOUR * 24;
var MILLISECONDS_PER_HOUR = 60 * 60 * 1000;
var MICROSECONDS_PER_DAY = 1000 * MILLISECONDS_PER_HOUR * 24;
document.addEventListener("dialogaccept", onAccept);
@ -20,10 +20,10 @@ function onLoad() {
var initialDate = new Date();
initialDate.setHours(0);
initialDate.setTime(initialDate.getTime() - MILLISECONDS_PER_HOUR);
// note that this is sufficient - though it is at the end of the previous day,
// we convert it to a date string, and then the time part is truncated
// note that this is sufficient - though it is at the end of the previous day,
// we convert it to a date string, and then the time part is truncated
upperDateBox.value = convertDateToString(initialDate);
upperDateBox.select(); // allows to start overwriting immediately
upperDateBox.select(); // allows to start overwriting immediately
}
function onAccept() {
@ -82,8 +82,12 @@ function markInDatabase(lower, upper) {
// the headers which are going to be marked
var headers = Cc["@mozilla.org/array;1"].createInstance(Ci.nsIMutableArray);
var searchSession = Cc["@mozilla.org/messenger/searchSession;1"].createInstance(Ci.nsIMsgSearchSession);
var searchTerms = Cc["@mozilla.org/array;1"].createInstance(Ci.nsIMutableArray);
var searchSession = Cc[
"@mozilla.org/messenger/searchSession;1"
].createInstance(Ci.nsIMsgSearchSession);
var searchTerms = Cc["@mozilla.org/array;1"].createInstance(
Ci.nsIMutableArray
);
searchSession.addScopeTerm(Ci.nsMsgSearchScope.offlineMail, messageFolder);
const nsMsgSearchAttrib = Ci.nsMsgSearchAttrib;
@ -116,11 +120,17 @@ function markInDatabase(lower, upper) {
var keepGoing;
var numMatches = {};
do {
keepGoing = messageDatabase.nextMatchingHdrs(filterEnumerator, 0, 0, headers, numMatches);
}
while (keepGoing);
keepGoing = messageDatabase.nextMatchingHdrs(
filterEnumerator,
0,
0,
headers,
numMatches
);
} while (keepGoing);
}
if (headers.length)
if (headers.length) {
messageFolder.markMessagesRead(headers, true);
}
}

Просмотреть файл

@ -10,7 +10,9 @@ if (!customElements.get("menulist")) {
// Wrap in a block to prevent leaking to window scope.
{
const {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm");
const { Services } = ChromeUtils.import(
"resource://gre/modules/Services.jsm"
);
/**
* MozMenulistCharsetpicker is a menulist widget that is automatically
@ -45,21 +47,26 @@ if (!customElements.get("menulist")) {
}
let charsetBundle = Services.strings.createBundle(
"chrome://messenger/locale/charsetTitles.properties");
this.charsetValues.map((item) => {
let strCharset = charsetBundle.GetStringFromName(
item.toLowerCase() + ".title");
return { label: strCharset, value: item };
}).sort((a, b) => {
if (a.value == "UTF-8" || a.label < b.label) {
return -1;
} else if (b.value == "UTF-8" || a.label > b.label) {
return 1;
}
return 0;
}).forEach((item) => {
this.appendItem(item.label, item.value);
});
"chrome://messenger/locale/charsetTitles.properties"
);
this.charsetValues
.map(item => {
let strCharset = charsetBundle.GetStringFromName(
item.toLowerCase() + ".title"
);
return { label: strCharset, value: item };
})
.sort((a, b) => {
if (a.value == "UTF-8" || a.label < b.label) {
return -1;
} else if (b.value == "UTF-8" || a.label > b.label) {
return 1;
}
return 0;
})
.forEach(item => {
this.appendItem(item.label, item.value);
});
this._setupSelectedValueFromPref();
}
@ -67,7 +74,9 @@ if (!customElements.get("menulist")) {
// Set appropriate selected menu item based on preference value.
if (this.hasAttribute("preference")) {
let preference = Services.prefs.getComplexValue(
this.getAttribute("preference"), Ci.nsIPrefLocalizedString);
this.getAttribute("preference"),
Ci.nsIPrefLocalizedString
);
this.value = preference.data;
}
}
@ -75,7 +84,11 @@ if (!customElements.get("menulist")) {
attributeChangedCallback(name, oldValue, newValue) {
super.attributeChangedCallback(name, oldValue, newValue);
// @see MozElementMixin.attributeChangedCallback()
if (!this.isConnectedAndReady || oldValue === newValue || !this.inheritedAttributesCache) {
if (
!this.isConnectedAndReady ||
oldValue === newValue ||
!this.inheritedAttributesCache
) {
return;
}
if (name == "preference") {
@ -91,13 +104,21 @@ if (!customElements.get("menulist")) {
class MozMenulistCharsetpickerSending extends MozMenulistCharsetpickerBase {
get charsetValues() {
return [
"UTF-8", "EUC-KR", "gbk", "gb18030", "ISO-2022-JP",
"ISO-8859-1", "ISO-8859-7", "windows-1252",
"UTF-8",
"EUC-KR",
"gbk",
"gb18030",
"ISO-2022-JP",
"ISO-8859-1",
"ISO-8859-7",
"windows-1252",
];
}
}
customElements.define("menulist-charsetpicker-sending",
MozMenulistCharsetpickerSending, { extends: "menulist" }
customElements.define(
"menulist-charsetpicker-sending",
MozMenulistCharsetpickerSending,
{ extends: "menulist" }
);
/**
@ -107,15 +128,28 @@ if (!customElements.get("menulist")) {
class MozMenulistCharsetpickerViewing extends MozMenulistCharsetpickerBase {
get charsetValues() {
return [
"UTF-8", "Big5", "EUC-KR", "gbk", "ISO-2022-JP",
"ISO-8859-1", "ISO-8859-2", "ISO-8859-7",
"windows-874", "windows-1250", "windows-1251",
"windows-1252", "windows-1255", "windows-1256",
"windows-1257", "windows-1258",
"UTF-8",
"Big5",
"EUC-KR",
"gbk",
"ISO-2022-JP",
"ISO-8859-1",
"ISO-8859-2",
"ISO-8859-7",
"windows-874",
"windows-1250",
"windows-1251",
"windows-1252",
"windows-1255",
"windows-1256",
"windows-1257",
"windows-1258",
];
}
}
customElements.define("menulist-charsetpicker-viewing",
MozMenulistCharsetpickerViewing, { extends: "menulist" }
customElements.define(
"menulist-charsetpicker-viewing",
MozMenulistCharsetpickerViewing,
{ extends: "menulist" }
);
}

Просмотреть файл

@ -6,7 +6,7 @@
/* import-globals-from ../../../mail/base/content/mailCore.js */
/* import-globals-from ../prefs/content/accountUtils.js */
var {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm");
var { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm");
var selectedServer = null;
@ -15,12 +15,13 @@ function OnInit() {
// Title contains the brand name of the application and the account
// type (mail/news) and the name of the account
try {
let msgFolder = null;
let msgFolder = null;
let title;
// Get the brand name
let brandName = document.getElementById("bundle_brand")
.getString("brandShortName");
let brandName = document
.getElementById("bundle_brand")
.getString("brandShortName");
let messengerBundle = document.getElementById("bundle_messenger");
selectedServer = GetSelectedServer();
@ -28,12 +29,13 @@ function OnInit() {
// Get the account type
let serverType = selectedServer.type;
let acctType;
if (serverType == "nntp")
if (serverType == "nntp") {
acctType = messengerBundle.getString("newsAcctType");
else if (serverType == "rss")
} else if (serverType == "rss") {
acctType = messengerBundle.getString("feedsAcctType");
else
} else {
acctType = messengerBundle.getString("mailAcctType");
}
// Get the account name
msgFolder = GetSelectedMsgFolder();
@ -41,8 +43,11 @@ function OnInit() {
let acctName = msgFolder.prettyName;
// Display and collapse items presented to the user based on account type
title = messengerBundle.getFormattedString("acctCentralTitleFormat",
[brandName, acctType, acctName]);
title = messengerBundle.getFormattedString("acctCentralTitleFormat", [
brandName,
acctType,
acctName,
]);
} else {
// If there is no selectedServer, we are in a brand new profile with
// no accounts - show the create account rows.
@ -81,27 +86,36 @@ function ArrangeAccountCentralItems(server, msgFolder) {
try {
canGetMessages = protocolInfo && protocolInfo.canGetMessages;
SetItemDisplay("readMessages", canGetMessages && !displayRssHeader);
} catch (e) { exceptions.push(e); }
} catch (e) {
exceptions.push(e);
}
// Compose Messages link
let showComposeMsgLink = false;
try {
showComposeMsgLink = protocolInfo && protocolInfo.showComposeMsgLink;
SetItemDisplay("composeMessage", showComposeMsgLink);
} catch (e) { exceptions.push(e); }
} catch (e) {
exceptions.push(e);
}
// Junk mail settings (false, until ready for prime time)
let canControlJunkEmail = false;
try {
canControlJunkEmail = false && protocolInfo &&
protocolInfo.canGetIncomingMessages &&
protocolInfo.canGetMessages;
canControlJunkEmail =
false &&
protocolInfo &&
protocolInfo.canGetIncomingMessages &&
protocolInfo.canGetMessages;
SetItemDisplay("junkSettingsMail", canControlJunkEmail);
} catch (e) { exceptions.push(e); }
} catch (e) {
exceptions.push(e);
}
// Display Email header, only if any of the items are displayed
let displayEmailHeader = !displayRssHeader &&
(canGetMessages || showComposeMsgLink || canControlJunkEmail);
let displayEmailHeader =
!displayRssHeader &&
(canGetMessages || showComposeMsgLink || canControlJunkEmail);
SetItemDisplay("emailHeader", displayEmailHeader);
/* Email header and items : End */
@ -111,19 +125,28 @@ function ArrangeAccountCentralItems(server, msgFolder) {
// Subscribe to Newsgroups
let canSubscribe = false;
try {
canSubscribe = msgFolder && msgFolder.canSubscribe &&
protocolInfo && !protocolInfo.canGetMessages;
canSubscribe =
msgFolder &&
msgFolder.canSubscribe &&
protocolInfo &&
!protocolInfo.canGetMessages;
SetItemDisplay("subscribeNewsgroups", canSubscribe);
} catch (e) { exceptions.push(e); }
} catch (e) {
exceptions.push(e);
}
// Junk news settings (false, until ready for prime time)
let canControlJunkNews = false;
try {
canControlJunkNews = false && protocolInfo &&
protocolInfo.canGetIncomingMessages &&
!protocolInfo.canGetMessages;
canControlJunkNews =
false &&
protocolInfo &&
protocolInfo.canGetIncomingMessages &&
!protocolInfo.canGetMessages;
SetItemDisplay("junkSettingsNews", canControlJunkNews);
} catch (e) { exceptions.push(e); }
} catch (e) {
exceptions.push(e);
}
// Display News header, only if any of the items are displayed
let displayNewsHeader = canSubscribe || canControlJunkNews;
@ -142,8 +165,10 @@ function ArrangeAccountCentralItems(server, msgFolder) {
/* RSS header and items : End */
// If either of above sections exists, show section separators
SetItemDisplay("messagesSection",
displayNewsHeader || displayEmailHeader || displayRssHeader);
SetItemDisplay(
"messagesSection",
displayNewsHeader || displayEmailHeader || displayRssHeader
);
/* Accounts : Begin */
@ -154,11 +179,14 @@ function ArrangeAccountCentralItems(server, msgFolder) {
// Show New Mail Account Wizard if not prohibited by pref
let canShowCreateAccount = false;
try {
canShowCreateAccount = !Services.prefs
.prefIsLocked("mail.disable_new_account_addition");
canShowCreateAccount = !Services.prefs.prefIsLocked(
"mail.disable_new_account_addition"
);
SetItemDisplay("createAccount", canShowCreateAccount);
SetItemDisplay("createAccounts", canShowCreateAccount);
} catch (e) { exceptions.push(e); }
} catch (e) {
exceptions.push(e);
}
// Display Accounts header, only if any of the items are displayed
SetItemDisplay("accountsHeader", canShowCreateAccount);
@ -172,33 +200,47 @@ function ArrangeAccountCentralItems(server, msgFolder) {
try {
canSearchMessages = server && server.canSearchMessages;
SetItemDisplay("searchMessages", canSearchMessages);
} catch (e) { exceptions.push(e); }
} catch (e) {
exceptions.push(e);
}
// Create Filters
let canHaveFilters = false;
try {
canHaveFilters = server && server.canHaveFilters;
SetItemDisplay("createFilters", canHaveFilters);
} catch (e) { exceptions.push(e); }
} catch (e) {
exceptions.push(e);
}
// Subscribe to IMAP Folders
let canSubscribeImapFolders = false;
try {
canSubscribeImapFolders = msgFolder && msgFolder.canSubscribe &&
protocolInfo && protocolInfo.canGetMessages;
canSubscribeImapFolders =
msgFolder &&
msgFolder.canSubscribe &&
protocolInfo &&
protocolInfo.canGetMessages;
SetItemDisplay("subscribeImapFolders", canSubscribeImapFolders);
} catch (e) { exceptions.push(e); }
} catch (e) {
exceptions.push(e);
}
// Offline Settings
let supportsOffline = false;
try {
supportsOffline = server && server.offlineSupportLevel != 0;
SetItemDisplay("offlineSettings", supportsOffline);
} catch (e) { exceptions.push(e); }
} catch (e) {
exceptions.push(e);
}
// Display Adv Features header, only if any of the items are displayed
let displayAdvFeatures = canSearchMessages || canHaveFilters ||
canSubscribeImapFolders || supportsOffline;
let displayAdvFeatures =
canSearchMessages ||
canHaveFilters ||
canSubscribeImapFolders ||
supportsOffline;
SetItemDisplay("advancedFeaturesHeader", displayAdvFeatures);
/* Advanced Featuers header and items : End */
@ -207,8 +249,9 @@ function ArrangeAccountCentralItems(server, msgFolder) {
SetItemDisplay("accountsSection", displayAdvFeatures);
while (exceptions.length) {
Cu.reportError("Error in setting AccountCentral Items: "
+ exceptions.pop() + "\n");
Cu.reportError(
"Error in setting AccountCentral Items: " + exceptions.pop() + "\n"
);
}
}
/* eslint-enable complexity */
@ -217,12 +260,14 @@ function ArrangeAccountCentralItems(server, msgFolder) {
function SetItemDisplay(elemId, displayThisItem) {
if (displayThisItem) {
let elem = document.getElementById(elemId);
if (elem)
if (elem) {
elem.setAttribute("collapsed", false);
}
let elemSpacer = document.getElementById(elemId + "Spacer");
if (elemSpacer)
if (elemSpacer) {
elemSpacer.setAttribute("collapsed", false);
}
}
}
@ -235,8 +280,10 @@ function GetSelectedServer() {
// From the current folder tree, return the selected folder,
// the root folder of default account or null
function GetSelectedMsgFolder() {
return window.parent.GetSelectedMsgFolders()[0] ||
window.parent.GetDefaultAccountRootFolder();
return (
window.parent.GetSelectedMsgFolders()[0] ||
window.parent.GetDefaultAccountRootFolder()
);
}
/**
@ -244,8 +291,9 @@ function GetSelectedMsgFolder() {
* If needed, open the twisty and select Inbox.
*/
function ReadMessages() {
if (!selectedServer)
if (!selectedServer) {
return;
}
try {
window.parent.OpenInboxForServer(selectedServer);
} catch (ex) {
@ -286,15 +334,14 @@ function CreateNewAccountTB(type) {
return;
}
window.parent.msgOpenAccountWizard(
function(state) {
window.parent.msgOpenAccountWizard(function(state) {
let win = getMostRecentMailWindow();
if (state && win && win.gFolderTreeView && this.gCurrentAccount) {
win.gFolderTreeView.selectFolder(
this.gCurrentAccount.incomingServer.rootMsgFolder);
this.gCurrentAccount.incomingServer.rootMsgFolder
);
}
},
type);
}, type);
}
// Bring up search interface for selected account
@ -309,12 +356,14 @@ function CreateMsgFilters() {
// Open Subscribe dialog
function Subscribe() {
if (!selectedServer)
if (!selectedServer) {
return;
if (selectedServer.type == "rss")
}
if (selectedServer.type == "rss") {
window.parent.openSubscriptionsDialog(selectedServer.rootFolder);
else
} else {
window.parent.MsgSubscribe();
}
}
// Open junk mail settings dialog

Просмотреть файл

@ -3,7 +3,7 @@
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
var {MailUtils} = ChromeUtils.import("resource:///modules/MailUtils.jsm");
var { MailUtils } = ChromeUtils.import("resource:///modules/MailUtils.jsm");
var gMessengerBundle;
@ -23,7 +23,9 @@ function MsgFolderPickerOnLoad(pickerID) {
// pre-flight the menu with is valid for this
// picker type
var msgfolder = MailUtils.getExistingFolder(uri);
if (!msgfolder) return;
if (!msgfolder) {
return;
}
var verifyFunction = null;
@ -53,8 +55,9 @@ function PickedMsgFolder(selection, pickerID) {
function SetFolderPickerElement(uri, picker) {
var msgfolder = MailUtils.getExistingFolder(uri);
if (!msgfolder)
if (!msgfolder) {
return;
}
var selectedValue = null;
var serverName;
@ -65,8 +68,8 @@ function SetFolderPickerElement(uri, picker) {
if (msgfolder.server) {
serverName = msgfolder.server.prettyName;
} else {
dump("Can't find server for " + uri + "\n");
serverName = "???";
dump("Can't find server for " + uri + "\n");
serverName = "???";
}
switch (picker.id) {
@ -77,10 +80,13 @@ function SetFolderPickerElement(uri, picker) {
selectedValue = msgfolder.name;
break;
default:
if (!gMessengerBundle)
if (!gMessengerBundle) {
gMessengerBundle = document.getElementById("bundle_messenger");
selectedValue = gMessengerBundle.getFormattedString("verboseFolderFormat",
[msgfolder.name, serverName]);
}
selectedValue = gMessengerBundle.getFormattedString(
"verboseFolderFormat",
[msgfolder.name, serverName]
);
break;
}
}

Просмотреть файл

@ -7,10 +7,10 @@
/* import-globals-from ../../../../toolkit/components/printing/content/printUtils.js */
var {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm");
var { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm");
/* globals for a particular window */
var printEngineContractID = "@mozilla.org/messenger/msgPrintEngine;1";
var printEngineContractID = "@mozilla.org/messenger/msgPrintEngine;1";
var printEngineWindow;
var printEngine;
var printSettings = null;
@ -82,8 +82,9 @@ var gStartupPPObserver = {
};
function ReplaceWithSelection() {
if (!printOpener.content)
if (!printOpener.content) {
return;
}
var selection = printOpener.content.getSelection();
@ -108,7 +109,9 @@ function InitPrintEngineWindow() {
/* Register the event listener to be able to replace the document
* content with the user selection when loading is finished.
*/
document.getElementById("content").addEventListener("load", ReplaceWithSelection, true);
document
.getElementById("content")
.addEventListener("load", ReplaceWithSelection, true);
/* Tell the nsIPrintEngine object what window is rendering the email */
printEngine.setWindow(window);
@ -156,8 +159,9 @@ function InitPrintEngineWindow() {
}
function ClearPrintEnginePane() {
if (window.frames.content.location.href != "about:blank")
if (window.frames.content.location.href != "about:blank") {
window.frames.content.location.href = "about:blank";
}
}
function StopUrls() {
@ -165,9 +169,19 @@ function StopUrls() {
}
function PrintEnginePrint() {
printEngineWindow = window.openDialog("chrome://messenger/content/msgPrintEngine.xul", "", "chrome,dialog=no,all,centerscreen", false);
printEngineWindow = window.openDialog(
"chrome://messenger/content/msgPrintEngine.xul",
"",
"chrome,dialog=no,all,centerscreen",
false
);
}
function PrintEnginePrintPreview() {
printEngineWindow = window.openDialog("chrome://messenger/content/msgPrintEngine.xul", "", "chrome,dialog=no,all,centerscreen", true);
printEngineWindow = window.openDialog(
"chrome://messenger/content/msgPrintEngine.xul",
"",
"chrome,dialog=no,all,centerscreen",
true
);
}

Просмотреть файл

@ -11,16 +11,19 @@ var gSelectOffline = {
load() {
let oldProps = ftvItem.prototype.getProperties;
ftvItem.prototype.getProperties = function(aColumn) {
if (!aColumn || aColumn.id != "syncCol")
if (!aColumn || aColumn.id != "syncCol") {
return oldProps.call(this, aColumn);
}
let properties = "syncCol";
if (this._folder.isServer)
if (this._folder.isServer) {
return " isServer-true";
}
if (this._folder.getFlag(Ci.nsMsgFolderFlags.Offline))
if (this._folder.getFlag(Ci.nsMsgFolderFlags.Offline)) {
properties += " synchronize-true";
}
return properties;
};
@ -29,27 +32,35 @@ var gSelectOffline = {
__proto__: IFolderTreeMode,
generateMap(ftv) {
let filterOffline = function(aFolder) { return aFolder.supportsOffline; };
let accounts = gFolderTreeView._sortedAccounts()
.filter(acct => filterOffline(acct.incomingServer.rootFolder));
let filterOffline = function(aFolder) {
return aFolder.supportsOffline;
};
let accounts = gFolderTreeView
._sortedAccounts()
.filter(acct => filterOffline(acct.incomingServer.rootFolder));
// Force each root folder to do its local subfolder discovery.
MailUtils.discoverFolders();
return accounts.map(acct => new ftvItem(acct.incomingServer.rootFolder,
filterOffline));
return accounts.map(
acct => new ftvItem(acct.incomingServer.rootFolder, filterOffline)
);
},
};
this._treeElement = document.getElementById("synchronizeTree");
gFolderTreeView.registerFolderTreeMode(this._treeElement.getAttribute("mode"),
modeOffline, "Offline Folders");
gFolderTreeView.registerFolderTreeMode(
this._treeElement.getAttribute("mode"),
modeOffline,
"Offline Folders"
);
gFolderTreeView.load(this._treeElement);
},
onKeyPress(aEvent) {
// For now, only do something on space key.
if (aEvent.charCode != aEvent.DOM_VK_SPACE)
if (aEvent.charCode != aEvent.DOM_VK_SPACE) {
return;
}
let selection = this._treeElement.view.selection;
let start = {};
@ -66,13 +77,18 @@ var gSelectOffline = {
onClick(aEvent) {
// We only care about button 0 (left click) events.
if (aEvent.button != 0)
if (aEvent.button != 0) {
return;
}
let treeCellInfo = this._treeElement.getCellAt(aEvent.clientX, aEvent.clientY);
let treeCellInfo = this._treeElement.getCellAt(
aEvent.clientX,
aEvent.clientY
);
if (treeCellInfo.row == -1 || treeCellInfo.col.id != "syncCol")
if (treeCellInfo.row == -1 || treeCellInfo.col.id != "syncCol") {
return;
}
this._toggle(treeCellInfo.row);
},
@ -80,12 +96,17 @@ var gSelectOffline = {
_toggle(aRow) {
let folder = gFolderTreeView._rowMap[aRow]._folder;
if (folder.isServer)
if (folder.isServer) {
return;
}
// Save our current state for rollback, if necessary.
if (!this._rollbackMap.has(folder))
this._rollbackMap.set(folder, folder.getFlag(Ci.nsMsgFolderFlags.Offline));
if (!this._rollbackMap.has(folder)) {
this._rollbackMap.set(
folder,
folder.getFlag(Ci.nsMsgFolderFlags.Offline)
);
}
folder.toggleFlag(Ci.nsMsgFolderFlags.Offline);
gFolderTreeView._tree.invalidateRow(aRow);
@ -98,8 +119,9 @@ var gSelectOffline = {
onCancel() {
gFolderTreeView.unload();
for (let [folder, value] of this._rollbackMap) {
if (value != folder.getFlag(Ci.nsMsgFolderFlags.Offline))
if (value != folder.getFlag(Ci.nsMsgFolderFlags.Offline)) {
folder.toggleFlag(Ci.nsMsgFolderFlags.Offline);
}
}
},
};

Просмотреть файл

@ -3,8 +3,8 @@
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
var {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm");
var {MailUtils} = ChromeUtils.import("resource:///modules/MailUtils.jsm");
var { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm");
var { MailUtils } = ChromeUtils.import("resource:///modules/MailUtils.jsm");
var gSynchronizeTree = null;
var gParentMsgWindow;
@ -21,14 +21,18 @@ function OnLoad() {
}
}
document.getElementById("syncMail").checked =
Services.prefs.getBoolPref("mailnews.offline_sync_mail");
document.getElementById("syncNews").checked =
Services.prefs.getBoolPref("mailnews.offline_sync_news");
document.getElementById("sendMessage").checked =
Services.prefs.getBoolPref("mailnews.offline_sync_send_unsent");
document.getElementById("workOffline").checked =
Services.prefs.getBoolPref("mailnews.offline_sync_work_offline");
document.getElementById("syncMail").checked = Services.prefs.getBoolPref(
"mailnews.offline_sync_mail"
);
document.getElementById("syncNews").checked = Services.prefs.getBoolPref(
"mailnews.offline_sync_news"
);
document.getElementById("sendMessage").checked = Services.prefs.getBoolPref(
"mailnews.offline_sync_send_unsent"
);
document.getElementById("workOffline").checked = Services.prefs.getBoolPref(
"mailnews.offline_sync_work_offline"
);
return true;
}
@ -45,16 +49,27 @@ function syncOkButton() {
Services.prefs.setBoolPref("mailnews.offline_sync_work_offline", workOffline);
if (syncMail || syncNews || sendMessage || workOffline) {
var offlineManager = Cc["@mozilla.org/messenger/offline-manager;1"]
.getService(Ci.nsIMsgOfflineManager);
if (offlineManager)
offlineManager.synchronizeForOffline(syncNews, syncMail, sendMessage, workOffline, gParentMsgWindow);
var offlineManager = Cc[
"@mozilla.org/messenger/offline-manager;1"
].getService(Ci.nsIMsgOfflineManager);
if (offlineManager) {
offlineManager.synchronizeForOffline(
syncNews,
syncMail,
sendMessage,
workOffline,
gParentMsgWindow
);
}
}
}
function OnSelect() {
top.window.openDialog("chrome://messenger/content/msgSelectOfflineFolders.xul", "",
"centerscreen,chrome,modal,titlebar,resizable=yes");
top.window.openDialog(
"chrome://messenger/content/msgSelectOfflineFolders.xul",
"",
"centerscreen,chrome,modal,titlebar,resizable=yes"
);
return true;
}
@ -67,17 +82,19 @@ function selectOkButton() {
function selectCancelButton() {
for (var resourceValue in gInitialFolderStates) {
let folder = MailUtils.getExistingFolder(resourceValue);
if (gInitialFolderStates[resourceValue])
if (gInitialFolderStates[resourceValue]) {
folder.setFlag(Ci.nsMsgFolderFlags.Offline);
else
} else {
folder.clearFlag(Ci.nsMsgFolderFlags.Offline);
}
}
return true;
}
function selectOnLoad() {
gMsgWindow = Cc["@mozilla.org/messenger/msgwindow;1"]
.createInstance(Ci.nsIMsgWindow);
gMsgWindow = Cc["@mozilla.org/messenger/msgwindow;1"].createInstance(
Ci.nsIMsgWindow
);
gMsgWindow.domWindow = window;
gMsgWindow.rootDocShell.appType = Ci.nsIDocShell.APP_TYPE_MAIL;
@ -101,36 +118,41 @@ function SortSynchronizePane(column, sortKey) {
function FindInWindow(currentWindow, id) {
var item = currentWindow.document.getElementById(id);
if (item)
if (item) {
return item;
}
for (var i = 0; i < currentWindow.frames.length; i++) {
var frameItem = FindInWindow(currentWindow.frames[i], id);
if (frameItem)
if (frameItem) {
return frameItem;
}
}
return null;
}
function onSynchronizeClick(event) {
// we only care about button 0 (left click) events
if (event.button != 0)
if (event.button != 0) {
return;
}
let treeCellInfo = gSynchronizeTree.getCellAt(event.clientX, event.clientY);
if (treeCellInfo.row == -1)
if (treeCellInfo.row == -1) {
return;
}
if (treeCellInfo.childElt == "twisty") {
var folderResource = GetFolderResource(gSynchronizeTree, treeCellInfo.row);
var folder = folderResource.QueryInterface(Ci.nsIMsgFolder);
if (!(gSynchronizeTree.view.isContainerOpen(treeCellInfo.row))) {
if (!gSynchronizeTree.view.isContainerOpen(treeCellInfo.row)) {
var serverType = folder.server.type;
// imap is the only server type that does folder discovery
if (serverType != "imap") return;
if (serverType != "imap") {
return;
}
if (folder.isServer) {
var server = folder.server;
@ -143,32 +165,41 @@ function onSynchronizeClick(event) {
}
}
} else if (treeCellInfo.col.id == "syncCol") {
UpdateNode(GetFolderResource(gSynchronizeTree, treeCellInfo.row), treeCellInfo.row);
UpdateNode(
GetFolderResource(gSynchronizeTree, treeCellInfo.row),
treeCellInfo.row
);
}
}
function onSynchronizeTreeKeyPress(event) {
// for now, only do something on space key
if (event.charCode != KeyEvent.DOM_VK_SPACE)
if (event.charCode != KeyEvent.DOM_VK_SPACE) {
return;
}
var treeSelection = gSynchronizeTree.view.selection;
for (let i = 0; i < treeSelection.getRangeCount(); i++) {
var start = {}, end = {};
var start = {},
end = {};
treeSelection.getRangeAt(i, start, end);
for (let k = start.value; k <= end.value; k++)
for (let k = start.value; k <= end.value; k++) {
UpdateNode(GetFolderResource(gSynchronizeTree, k), k);
}
}
}
function UpdateNode(resource, row) {
var folder = resource.QueryInterface(Ci.nsIMsgFolder);
if (folder.isServer)
if (folder.isServer) {
return;
}
if (!(resource.Value in gInitialFolderStates)) {
gInitialFolderStates[resource.Value] = folder.getFlag(Ci.nsMsgFolderFlags.Offline);
gInitialFolderStates[resource.Value] = folder.getFlag(
Ci.nsMsgFolderFlags.Offline
);
}
folder.toggleFlag(Ci.nsMsgFolderFlags.Offline);

Просмотреть файл

@ -24,11 +24,14 @@ function onLoad() {
// pre select the folderPicker, based on what they selected in the folder pane
dialog.folder = windowArgs.folder;
try {
document.getElementById("MsgNewFolderPopup").selectFolder(windowArgs.folder);
document
.getElementById("MsgNewFolderPopup")
.selectFolder(windowArgs.folder);
} catch (ex) {
// selected a child folder
document.getElementById("msgNewFolderPicker")
.setAttribute("label", windowArgs.folder.prettyName);
document
.getElementById("msgNewFolderPicker")
.setAttribute("label", windowArgs.folder.prettyName);
}
// can folders contain both folders and messages?
@ -48,8 +51,9 @@ function onLoad() {
function onFolderSelect(event) {
dialog.folder = event.target._folder;
document.getElementById("msgNewFolderPicker")
.setAttribute("label", dialog.folder.prettyName);
document
.getElementById("msgNewFolderPicker")
.setAttribute("label", dialog.folder.prettyName);
}
function onOK() {
@ -58,10 +62,11 @@ function onOK() {
// do name validity check?
// make sure name ends in "/" if folder to create can only contain folders
if ((dialog.folderType == FOLDERS) && !name.endsWith("/"))
if (dialog.folderType == FOLDERS && !name.endsWith("/")) {
dialog.okCallback(name + "/", dialog.folder);
else
} else {
dialog.okCallback(name, dialog.folder);
}
}
function onFoldersOnly() {
@ -73,6 +78,6 @@ function onMessagesOnly() {
}
function doEnabling() {
document.documentElement.getButton("accept").disabled = !dialog.nameField.value;
document.documentElement.getButton("accept").disabled = !dialog.nameField
.value;
}

Просмотреть файл

@ -2,9 +2,13 @@
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
var {fixIterator} = ChromeUtils.import("resource:///modules/iteratorUtils.jsm");
var {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm");
var {PluralForm} = ChromeUtils.import("resource://gre/modules/PluralForm.jsm");
var { fixIterator } = ChromeUtils.import(
"resource:///modules/iteratorUtils.jsm"
);
var { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm");
var { PluralForm } = ChromeUtils.import(
"resource://gre/modules/PluralForm.jsm"
);
// Copied from nsILookAndFeel.h, see comments on eMetric_AlertNotificationOrigin
var NS_ALERT_HORIZONTAL = 1;
@ -34,19 +38,22 @@ function prefillAlertInfo() {
// For now just grab the first folder which should be a root folder
// for the account that has new mail. If we can't find a folder, just
// return to avoid the exception and empty dialog in upper left-hand corner.
if (!foldersWithNewMail || foldersWithNewMail.length < 1)
if (!foldersWithNewMail || foldersWithNewMail.length < 1) {
return;
let rootFolder = foldersWithNewMail.queryElementAt(0, Ci.nsIWeakReference)
.QueryReferent(Ci.nsIMsgFolder);
}
let rootFolder = foldersWithNewMail
.queryElementAt(0, Ci.nsIWeakReference)
.QueryReferent(Ci.nsIMsgFolder);
// Generate an account label string based on the root folder.
var label = document.getElementById("alertTitle");
var totalNumNewMessages = rootFolder.getNumNewMessages(true);
let message = document.getElementById("bundle_messenger")
.getString("newMailAlert_message");
let message = document
.getElementById("bundle_messenger")
.getString("newMailAlert_message");
label.value = PluralForm.get(totalNumNewMessages, message)
.replace("#1", rootFolder.prettyName)
.replace("#2", totalNumNewMessages);
.replace("#1", rootFolder.prettyName)
.replace("#2", totalNumNewMessages);
// This is really the root folder and we have to walk through the list to
// find the real folder that has new mail in it...:(
@ -60,13 +67,21 @@ function prefillAlertInfo() {
folder.getFlag(Ci.nsMsgFolderFlags.Inbox) ||
// any non-special or non-virtual folder. In other words, we don't
// notify for Drafts|Trash|SentMail|Templates|Junk|Archive|Queue or virtual.
!(folder.flags & (Ci.nsMsgFolderFlags.SpecialUse | Ci.nsMsgFolderFlags.Virtual));
!(
folder.flags &
(Ci.nsMsgFolderFlags.SpecialUse | Ci.nsMsgFolderFlags.Virtual)
);
if (notify) {
var asyncFetch = {};
folderSummaryInfoEl.parseFolder(folder, new urlListener(folder), asyncFetch);
if (asyncFetch.value)
folderSummaryInfoEl.parseFolder(
folder,
new urlListener(folder),
asyncFetch
);
if (asyncFetch.value) {
gPendingPreviewFetchRequests++;
}
}
}
}
@ -77,8 +92,7 @@ function urlListener(aFolder) {
}
urlListener.prototype = {
OnStartRunningUrl(aUrl) {
},
OnStartRunningUrl(aUrl) {},
OnStopRunningUrl(aUrl, aExitCode) {
let folderSummaryInfoEl = document.getElementById("folderSummaryInfo");
@ -87,8 +101,9 @@ urlListener.prototype = {
// when we are done running all of our urls for fetching the preview text,
// start the alert.
if (!gPendingPreviewFetchRequests)
if (!gPendingPreviewFetchRequests) {
showAlert();
}
},
};
@ -102,9 +117,10 @@ function onAlertLoad() {
// if we aren't waiting to fetch preview text, then go ahead and
// start showing the alert.
if (!gPendingPreviewFetchRequests)
setTimeout(showAlert, 0); // let the JS thread unwind, to give layout
// a chance to recompute the styles and widths for our alert text.
if (!gPendingPreviewFetchRequests) {
setTimeout(showAlert, 0);
} // let the JS thread unwind, to give layout
// a chance to recompute the styles and widths for our alert text.
}
// If the user initiated the alert, show it right away, otherwise start opening the alert with
@ -120,8 +136,10 @@ function showAlert() {
var alertContainer = document.getElementById("alertContainer");
// Don't fade in if the user opened the alert or the pref is true.
if (gUserInitiated ||
!Services.prefs.getBoolPref("toolkit.cosmeticAnimations.enabled")) {
if (
gUserInitiated ||
!Services.prefs.getBoolPref("toolkit.cosmeticAnimations.enabled")
) {
alertContainer.setAttribute("noanimation", true);
setTimeout(closeAlert, gOpenTime);
return;
@ -145,14 +163,19 @@ function resizeAlert(aMoveOffScreen) {
sizeToContent();
// leftover hack to get the window properly hidden when we first open it
if (aMoveOffScreen)
if (aMoveOffScreen) {
window.outerHeight = 1;
}
// Determine position
var x = gOrigin & NS_ALERT_LEFT ? screen.availLeft :
screen.availLeft + screen.availWidth - window.outerWidth;
var y = gOrigin & NS_ALERT_TOP ? screen.availTop :
screen.availTop + screen.availHeight - window.outerHeight;
var x =
gOrigin & NS_ALERT_LEFT
? screen.availLeft
: screen.availLeft + screen.availWidth - window.outerWidth;
var y =
gOrigin & NS_ALERT_TOP
? screen.availTop
: screen.availTop + screen.availHeight - window.outerHeight;
// Offset the alert by 10 pixels from the edge of the screen
y += gOrigin & NS_ALERT_TOP ? 10 : -10;
@ -173,7 +196,8 @@ function fadeOutAlert() {
}
function closeAlert() {
if (gAlertListener)
if (gAlertListener) {
gAlertListener.observe(null, "alertfinished", "");
}
window.close();
}

Просмотреть файл

@ -1,45 +1,44 @@
// Error url must be formatted like this:
// about:newserror?r=response&m=messageid&k=messagekey&f=folderuri
// "r" is required; "m" and "f" are optional, but "k" always comes with "m".
// Error url must be formatted like this:
// about:newserror?r=response&m=messageid&k=messagekey&f=folderuri
// "r" is required; "m" and "f" are optional, but "k" always comes with "m".
var folderUri;
var folderUri;
function initPage() {
let uri = document.documentURI;
let query = uri.slice(uri.indexOf("?") + 1);
let params = {};
for (let piece of query.split("&")) {
let [key, value] = piece.split("=");
params[key] = decodeURIComponent(value);
}
function initPage() {
let uri = document.documentURI;
let query = uri.slice(uri.indexOf("?") + 1);
let params = {};
for (let piece of query.split("&")) {
let [key, value] = piece.split("=");
params[key] = decodeURIComponent(value);
}
document.getElementById("ngResp").textContent = params.r;
document.getElementById("ngResp").textContent = params.r;
if ("m" in params) {
document.getElementById("msgId").textContent = params.m;
document.getElementById("msgKey").textContent = params.k;
} else {
document.getElementById("messageIdDesc").hidden = true;
}
if ("m" in params) {
document.getElementById("msgId").textContent = params.m;
document.getElementById("msgKey").textContent = params.k;
} else {
document.getElementById("messageIdDesc").hidden = true;
}
if ("f" in params) {
folderUri = params.f;
} else {
document.getElementById("errorTryAgain").hidden = true;
}
}
if ("f" in params) {
folderUri = params.f;
} else {
document.getElementById("errorTryAgain").hidden = true;
}
}
function removeExpired() {
document.location.href = folderUri + "?list-ids";
}
function removeExpired() {
document.location.href = folderUri + "?list-ids";
}
let errorTryAgain = document.getElementById("errorTryAgain");
errorTryAgain.addEventListener("click", function() {
removeExpired();
});
let errorTryAgain = document.getElementById("errorTryAgain");
errorTryAgain.addEventListener("click", function() {
removeExpired();
});
// This must be called in this way,
// see mozilla-central/docshell/resources/content/netError.js after which
// this is modelled.
initPage();
// This must be called in this way,
// see mozilla-central/docshell/resources/content/netError.js after which
// this is modelled.
initPage();

Просмотреть файл

@ -35,8 +35,9 @@ function onOK() {
function doEnabling() {
if (dialog.nameField.value) {
if (dialog.OKButton.disabled)
if (dialog.OKButton.disabled) {
dialog.OKButton.disabled = false;
}
} else if (!dialog.OKButton.disabled) {
dialog.OKButton.disabled = true;
}

Просмотреть файл

@ -4,27 +4,40 @@
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
/* globals gLockedPref */// From either folderProps.js or am-offline.js.
/* globals gLockedPref */ // From either folderProps.js or am-offline.js.
function initCommonRetentionSettings(retentionSettings) {
document.getElementById("retention.keepMsg").value = retentionSettings.retainByPreference;
document.getElementById("retention.keepMsg").value =
retentionSettings.retainByPreference;
document.getElementById("retention.keepOldMsgMin").value =
(retentionSettings.daysToKeepHdrs > 0) ? retentionSettings.daysToKeepHdrs : 30;
retentionSettings.daysToKeepHdrs > 0
? retentionSettings.daysToKeepHdrs
: 30;
document.getElementById("retention.keepNewMsgMin").value =
(retentionSettings.numHeadersToKeep > 0) ? retentionSettings.numHeadersToKeep : 2000;
retentionSettings.numHeadersToKeep > 0
? retentionSettings.numHeadersToKeep
: 2000;
document.getElementById("retention.applyToFlagged").checked =
!retentionSettings.applyToFlaggedMessages;
document.getElementById(
"retention.applyToFlagged"
).checked = !retentionSettings.applyToFlaggedMessages;
}
function saveCommonRetentionSettings(aRetentionSettings) {
aRetentionSettings.retainByPreference = document.getElementById("retention.keepMsg").value;
aRetentionSettings.retainByPreference = document.getElementById(
"retention.keepMsg"
).value;
aRetentionSettings.daysToKeepHdrs = document.getElementById("retention.keepOldMsgMin").value;
aRetentionSettings.numHeadersToKeep = document.getElementById("retention.keepNewMsgMin").value;
aRetentionSettings.daysToKeepHdrs = document.getElementById(
"retention.keepOldMsgMin"
).value;
aRetentionSettings.numHeadersToKeep = document.getElementById(
"retention.keepNewMsgMin"
).value;
aRetentionSettings.applyToFlaggedMessages =
!document.getElementById("retention.applyToFlagged").checked;
aRetentionSettings.applyToFlaggedMessages = !document.getElementById(
"retention.applyToFlagged"
).checked;
return aRetentionSettings;
}

Просмотреть файл

@ -8,8 +8,9 @@ var curTaskIndex = 0;
var numTasks = 0;
var stringBundle;
var msgShutdownService = Cc["@mozilla.org/messenger/msgshutdownservice;1"]
.getService(Ci.nsIMsgShutdownService);
var msgShutdownService = Cc[
"@mozilla.org/messenger/msgshutdownservice;1"
].getService(Ci.nsIMsgShutdownService);
document.addEventListener("dialogcancel", onCancel);
@ -32,7 +33,10 @@ function updateProgressLabel(inTaskName) {
function updateTaskProgressLabel(inCurTaskNum) {
var taskProgressLabel = document.getElementById("shutdownTask_label");
taskProgressLabel.value = stringBundle.getFormattedString("taskProgress", [inCurTaskNum, numTasks]);
taskProgressLabel.value = stringBundle.getFormattedString("taskProgress", [
inCurTaskNum,
numTasks,
]);
}
function updateProgressMeter(inPercent) {
@ -48,10 +52,11 @@ function nsMsgShutdownTaskListener() {
msgShutdownService.setShutdownListener(this);
}
nsMsgShutdownTaskListener.prototype =
{
QueryInterface: ChromeUtils.generateQI(["nsIWebProgressListener",
"nsISupportsWeakReference"]),
nsMsgShutdownTaskListener.prototype = {
QueryInterface: ChromeUtils.generateQI([
"nsIWebProgressListener",
"nsISupportsWeakReference",
]),
onStateChange(aWebProgress, aRequest, aStateFlags, aStatus) {
if (aStateFlags & Ci.nsIWebProgressListener.STATE_STOP) {
@ -59,8 +64,15 @@ nsMsgShutdownTaskListener.prototype =
}
},
onProgressChange(aWebProgress, aRequest, aCurSelfProgress, aMaxSelfProgress, aCurTotalProgress, aMaxTotalProgress) {
updateProgressMeter(((aCurTotalProgress / aMaxTotalProgress) * 100));
onProgressChange(
aWebProgress,
aRequest,
aCurSelfProgress,
aMaxSelfProgress,
aCurTotalProgress,
aMaxTotalProgress
) {
updateProgressMeter((aCurTotalProgress / aMaxTotalProgress) * 100);
updateTaskProgressLabel(aCurTotalProgress + 1);
},
@ -69,8 +81,9 @@ nsMsgShutdownTaskListener.prototype =
},
onStatusChange(aWebProgress, aRequest, aStatus, aMessage) {
if (aMessage)
if (aMessage) {
updateProgressLabel(aMessage);
}
},
onSecurityChange(aWebProgress, aRequest, state) {
@ -83,4 +96,3 @@ nsMsgShutdownTaskListener.prototype =
};
var MsgShutdownTaskListener = new nsMsgShutdownTaskListener();

Просмотреть файл

@ -4,7 +4,7 @@
/* import-globals-from ../../../mail/base/content/mailWindow.js */
var {MailUtils} = ChromeUtils.import("resource:///modules/MailUtils.jsm");
var { MailUtils } = ChromeUtils.import("resource:///modules/MailUtils.jsm");
var gSubscribeTree = null;
var gSubscribeBody = null;
@ -30,21 +30,34 @@ function Stop() {
}
function SetServerTypeSpecificTextValues() {
if (!gServerURI)
if (!gServerURI) {
return;
}
let serverType = MailUtils.getExistingFolder(gServerURI).server.type;
// set the server specific ui elements
let subscribeLabelString = gSubscribeBundle.getString("subscribeLabel-" + serverType);
let currentListTab = "currentListTab-" + serverType;
let currentListTabLabel = gSubscribeBundle.getString(currentListTab + ".label");
let currentListTabAccesskey = gSubscribeBundle.getString(currentListTab + ".accesskey");
let subscribeLabelString = gSubscribeBundle.getString(
"subscribeLabel-" + serverType
);
let currentListTab = "currentListTab-" + serverType;
let currentListTabLabel = gSubscribeBundle.getString(
currentListTab + ".label"
);
let currentListTabAccesskey = gSubscribeBundle.getString(
currentListTab + ".accesskey"
);
document.getElementById("currentListTab").setAttribute("label", currentListTabLabel);
document.getElementById("currentListTab").setAttribute("accesskey", currentListTabAccesskey);
document.getElementById("newGroupsTab").collapsed = (serverType != "nntp"); // show newGroupsTab only for nntp servers
document.getElementById("subscribeLabel").setAttribute("value", subscribeLabelString);
document
.getElementById("currentListTab")
.setAttribute("label", currentListTabLabel);
document
.getElementById("currentListTab")
.setAttribute("accesskey", currentListTabAccesskey);
document.getElementById("newGroupsTab").collapsed = serverType != "nntp"; // show newGroupsTab only for nntp servers
document
.getElementById("subscribeLabel")
.setAttribute("value", subscribeLabelString);
}
function onServerClick(aFolder) {
@ -67,8 +80,9 @@ var MySubscribeListener = {
};
function SetUpTree(forceToServer, getOnlyNew) {
if (!gServerURI)
if (!gServerURI) {
return;
}
var server = MailUtils.getExistingFolder(gServerURI).server;
try {
@ -90,31 +104,38 @@ function SetUpTree(forceToServer, getOnlyNew) {
}
var currentListTab = document.getElementById("currentListTab");
if (currentListTab.selected)
if (currentListTab.selected) {
document.getElementById("newGroupsTab").disabled = true;
else
} else {
currentListTab.disabled = true;
}
document.getElementById("refreshButton").disabled = true;
gStatusFeedback._startMeteors();
gStatusFeedback.setStatusString("");
gStatusFeedback.showStatusString(gSubscribeBundle.getString("pleaseWaitString"));
gStatusFeedback.showStatusString(
gSubscribeBundle.getString("pleaseWaitString")
);
document.getElementById("stopButton").disabled = false;
gSubscribableServer.startPopulating(msgWindow, forceToServer, getOnlyNew);
} catch (e) {
if (e.result == 0x80550014) { // NS_MSG_ERROR_OFFLINE
gStatusFeedback.setStatusString(gSubscribeBundle.getString("offlineState"));
if (e.result == 0x80550014) {
// NS_MSG_ERROR_OFFLINE
gStatusFeedback.setStatusString(
gSubscribeBundle.getString("offlineState")
);
} else {
Cu.reportError("Failed to populate subscribe tree: " + e);
gStatusFeedback.setStatusString(gSubscribeBundle.getString("errorPopulating"));
gStatusFeedback.setStatusString(
gSubscribeBundle.getString("errorPopulating")
);
}
Stop();
}
}
function SubscribeOnUnload() {
try {
CleanUpSearchView();
@ -146,10 +167,11 @@ function SubscribeOnLoad() {
gSubscribeDeck = document.getElementById("subscribedeck");
// eslint-disable-next-line no-global-assign
msgWindow = Cc["@mozilla.org/messenger/msgwindow;1"]
.createInstance(Ci.nsIMsgWindow);
msgWindow = Cc["@mozilla.org/messenger/msgwindow;1"].createInstance(
Ci.nsIMsgWindow
);
msgWindow.domWindow = window;
gStatusFeedback = new nsMsgStatusFeedback;
gStatusFeedback = new nsMsgStatusFeedback();
msgWindow.statusFeedback = gStatusFeedback;
msgWindow.rootDocShell.allowAuth = true;
msgWindow.rootDocShell.appType = Ci.nsIDocShell.APP_TYPE_MAIL;
@ -164,12 +186,15 @@ function SubscribeOnLoad() {
var serverMenu = document.getElementById("serverMenu");
gServerURI = null;
let folder = ("folder" in window.arguments[0]) ? window.arguments[0].folder : null;
let folder =
"folder" in window.arguments[0] ? window.arguments[0].folder : null;
if (folder && folder.server instanceof Ci.nsISubscribableServer) {
serverMenu.menupopup.selectFolder(folder.server.rootMsgFolder);
try {
CleanUpSearchView();
gSubscribableServer = folder.server.QueryInterface(Ci.nsISubscribableServer);
gSubscribableServer = folder.server.QueryInterface(
Ci.nsISubscribableServer
);
// Enable (or disable) the search related UI.
EnableSearchUI();
gServerURI = folder.server.serverURI;
@ -222,16 +247,18 @@ function subscribeCancel() {
function SetState(name, state) {
var changed = gSubscribableServer.setState(name, state);
if (changed)
if (changed) {
StateChanged(name, state);
}
}
function StateChanged(name, state) {
if (gServerURI in gChangeTable) {
if (name in gChangeTable[gServerURI]) {
var oldValue = gChangeTable[gServerURI][name];
if (oldValue != state)
if (oldValue != state) {
delete gChangeTable[gServerURI][name];
}
} else {
gChangeTable[gServerURI][name] = state;
}
@ -243,16 +270,19 @@ function StateChanged(name, state) {
function InSearchMode() {
// search is the second card in the deck
return (gSubscribeDeck.getAttribute("selectedIndex") == "1");
return gSubscribeDeck.getAttribute("selectedIndex") == "1";
}
function SearchOnClick(event) {
// we only care about button 0 (left click) events
if (event.button != 0 || event.originalTarget.localName != "treechildren") return;
if (event.button != 0 || event.originalTarget.localName != "treechildren") {
return;
}
let treeCellInfo = gSearchTree.getCellAt(event.clientX, event.clientY);
if (treeCellInfo.row == -1 || treeCellInfo.row > gSearchView.rowCount - 1)
if (treeCellInfo.row == -1 || treeCellInfo.row > gSearchView.rowCount - 1) {
return;
}
if (treeCellInfo.col.id == "subscribedColumn2") {
if (event.detail != 2) {
@ -298,7 +328,8 @@ function SetSubscribeState(state) {
var sel = view.selection;
for (var i = 0; i < sel.getRangeCount(); ++i) {
var start = {}, end = {};
var start = {},
end = {};
sel.getRangeAt(i, start, end);
for (var k = start.value; k <= end.value; ++k) {
if (inSearchMode) {
@ -320,18 +351,26 @@ function SetSubscribeState(state) {
}
function ReverseStateFromNode(row) {
let name = gSubscribeTree.view.getCellValue(row, gSubscribeTree.columns.nameColumn);
let name = gSubscribeTree.view.getCellValue(
row,
gSubscribeTree.columns.nameColumn
);
SetState(name, !gSubscribableServer.isSubscribed(name), row);
}
function SubscribeOnClick(event) {
// we only care about button 0 (left click) events
if (event.button != 0 || event.originalTarget.localName != "treechildren")
return;
if (event.button != 0 || event.originalTarget.localName != "treechildren") {
return;
}
let treeCellInfo = gSubscribeTree.getCellAt(event.clientX, event.clientY);
if (treeCellInfo.row == -1 || treeCellInfo.row > (gSubscribeTree.view.rowCount - 1))
if (
treeCellInfo.row == -1 ||
treeCellInfo.row > gSubscribeTree.view.rowCount - 1
) {
return;
}
if (event.detail == 2) {
// only toggle subscribed state when double clicking something
@ -341,8 +380,9 @@ function SubscribeOnClick(event) {
}
} else if (event.detail == 1) {
// if the user single clicks on the subscribe check box, we handle it here
if (treeCellInfo.col.id == "subscribedColumn")
if (treeCellInfo.col.id == "subscribedColumn") {
ReverseStateFromNode(treeCellInfo.row);
}
}
}
@ -401,10 +441,10 @@ function Search() {
gSubscribableServer.setSearchValue(searchValue);
if (!gSearchView && gSubscribableServer) {
gSearchView = gSubscribableServer.QueryInterface(Ci.nsITreeView);
gSearchView = gSubscribableServer.QueryInterface(Ci.nsITreeView);
gSearchView.selection = null;
gSearchTree.view = gSearchView;
}
gSearchTree.view = gSearchView;
}
} else {
SwitchToNormalView();
}
@ -419,15 +459,18 @@ function CleanUpSearchView() {
function onSearchTreeKeyPress(event) {
// for now, only do something on space key
if (event.charCode != KeyEvent.DOM_VK_SPACE)
if (event.charCode != KeyEvent.DOM_VK_SPACE) {
return;
}
var treeSelection = gSearchView.selection;
for (let i = 0; i < treeSelection.getRangeCount(); i++) {
var start = {}, end = {};
var start = {},
end = {};
treeSelection.getRangeAt(i, start, end);
for (let k = start.value; k <= end.value; k++)
for (let k = start.value; k <= end.value; k++) {
ReverseStateFromRow(k);
}
// force a repaint
InvalidateSearchTree();
@ -436,14 +479,17 @@ function onSearchTreeKeyPress(event) {
function onSubscribeTreeKeyPress(event) {
// for now, only do something on space key
if (event.charCode != KeyEvent.DOM_VK_SPACE)
if (event.charCode != KeyEvent.DOM_VK_SPACE) {
return;
}
var treeSelection = gSubscribeTree.view.selection;
for (let i = 0; i < treeSelection.getRangeCount(); i++) {
var start = {}, end = {};
var start = {},
end = {};
treeSelection.getRangeAt(i, start, end);
for (let k = start.value; k <= end.value; k++)
for (let k = start.value; k <= end.value; k++) {
ReverseStateFromNode(k);
}
}
}

Просмотреть файл

@ -4,7 +4,7 @@
/* import-globals-from ../../../mail/base/content/folderPane.js */
var {MailUtils} = ChromeUtils.import("resource:///modules/MailUtils.jsm");
var { MailUtils } = ChromeUtils.import("resource:///modules/MailUtils.jsm");
var gSelectVirtual = {
_treeElement: null,
@ -21,12 +21,14 @@ var gSelectVirtual = {
// Now tweak the folder tree for our purposes here.
let oldProps = ftvItem.prototype.getProperties;
ftvItem.prototype.getProperties = function(aColumn) {
if (!aColumn || aColumn.id != "selectedCol")
if (!aColumn || aColumn.id != "selectedCol") {
return oldProps.call(this, aColumn);
}
let properties = "selectedColumn";
if (gSelectVirtual._selectedList.has(this._folder))
if (gSelectVirtual._selectedList.has(this._folder)) {
properties += " selected-true";
}
return properties;
};
@ -41,21 +43,26 @@ var gSelectVirtual = {
let filterVirtual = function(aFolder) {
return !aFolder.getFlag(Ci.nsMsgFolderFlags.Virtual);
};
return accounts.map(acct => new ftvItem(acct.incomingServer.rootFolder,
filterVirtual));
return accounts.map(
acct => new ftvItem(acct.incomingServer.rootFolder, filterVirtual)
);
},
};
this._treeElement = document.getElementById("folderPickerTree");
gFolderTreeView.registerFolderTreeMode(this._treeElement.getAttribute("mode"),
modeVirtual, "Virtual Folders");
gFolderTreeView.registerFolderTreeMode(
this._treeElement.getAttribute("mode"),
modeVirtual,
"Virtual Folders"
);
gFolderTreeView.load(this._treeElement);
},
onKeyPress(aEvent) {
// For now, only do something on space key.
if (aEvent.charCode != aEvent.DOM_VK_SPACE)
if (aEvent.charCode != aEvent.DOM_VK_SPACE) {
return;
}
let selection = this._treeElement.view.selection;
let start = {};
@ -72,22 +79,28 @@ var gSelectVirtual = {
onClick(aEvent) {
// We only care about button 0 (left click) events.
if (aEvent.button != 0)
if (aEvent.button != 0) {
return;
}
let treeCellInfo = this._treeElement.getCellAt(aEvent.clientX, aEvent.clientY);
if (treeCellInfo.row == -1 || treeCellInfo.col.id != "selectedCol")
let treeCellInfo = this._treeElement.getCellAt(
aEvent.clientX,
aEvent.clientY
);
if (treeCellInfo.row == -1 || treeCellInfo.col.id != "selectedCol") {
return;
}
this._toggle(treeCellInfo.row);
},
_toggle(aRow) {
let folder = gFolderTreeView._rowMap[aRow]._folder;
if (this._selectedList.has(folder))
if (this._selectedList.has(folder)) {
this._selectedList.delete(folder);
else
} else {
this._selectedList.add(folder);
}
gFolderTreeView._tree.invalidateRow(aRow);
},
@ -95,10 +108,13 @@ var gSelectVirtual = {
onAccept() {
gFolderTreeView.unload();
// XXX We should just pass the folder objects around...
let uris = [...this._selectedList.values()].map(folder => folder.URI).join("|");
let uris = [...this._selectedList.values()]
.map(folder => folder.URI)
.join("|");
if (window.arguments[0].okCallback)
if (window.arguments[0].okCallback) {
window.arguments[0].okCallback(uris);
}
},
onCancel() {

Просмотреть файл

@ -14,14 +14,20 @@ var gMessengerBundle = null;
var nsMsgSearchScope = Ci.nsMsgSearchScope;
var {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm");
var {PluralForm} = ChromeUtils.import("resource://gre/modules/PluralForm.jsm");
var {MailServices} = ChromeUtils.import("resource:///modules/MailServices.jsm");
var {
VirtualFolderHelper,
} = ChromeUtils.import("resource:///modules/virtualFolderWrapper.js");
var {fixIterator} = ChromeUtils.import("resource:///modules/iteratorUtils.jsm");
var {MailUtils} = ChromeUtils.import("resource:///modules/MailUtils.jsm");
var { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm");
var { PluralForm } = ChromeUtils.import(
"resource://gre/modules/PluralForm.jsm"
);
var { MailServices } = ChromeUtils.import(
"resource:///modules/MailServices.jsm"
);
var { VirtualFolderHelper } = ChromeUtils.import(
"resource:///modules/virtualFolderWrapper.js"
);
var { fixIterator } = ChromeUtils.import(
"resource:///modules/iteratorUtils.jsm"
);
var { MailUtils } = ChromeUtils.import("resource:///modules/MailUtils.jsm");
document.addEventListener("dialogaccept", onOK);
@ -38,63 +44,82 @@ function onLoad() {
setSearchScope(nsMsgSearchScope.offlineMail);
if (windowArgs.editExistingFolder) {
acceptButton.label =
document.documentElement.getAttribute("editFolderAcceptButtonLabel");
acceptButton.accesskey =
document.documentElement.getAttribute("editFolderAcceptButtonAccessKey");
acceptButton.label = document.documentElement.getAttribute(
"editFolderAcceptButtonLabel"
);
acceptButton.accesskey = document.documentElement.getAttribute(
"editFolderAcceptButtonAccessKey"
);
InitDialogWithVirtualFolder(windowArgs.folder);
} else { // we are creating a new virtual folder
acceptButton.label =
document.documentElement.getAttribute("newFolderAcceptButtonLabel");
acceptButton.accesskey =
document.documentElement.getAttribute("newFolderAcceptButtonAccessKey");
} else {
// we are creating a new virtual folder
acceptButton.label = document.documentElement.getAttribute(
"newFolderAcceptButtonLabel"
);
acceptButton.accesskey = document.documentElement.getAttribute(
"newFolderAcceptButtonAccessKey"
);
// it is possible that we were given arguments to pre-fill the dialog with...
gSearchTermSession = Cc["@mozilla.org/messenger/searchSession;1"]
.createInstance(Ci.nsIMsgSearchSession);
gSearchTermSession = Cc[
"@mozilla.org/messenger/searchSession;1"
].createInstance(Ci.nsIMsgSearchSession);
if (windowArgs.searchTerms) { // then add them to our search session
for (let searchTerm of fixIterator(windowArgs.searchTerms,
Ci.nsIMsgSearchTerm))
if (windowArgs.searchTerms) {
// then add them to our search session
for (let searchTerm of fixIterator(
windowArgs.searchTerms,
Ci.nsIMsgSearchTerm
)) {
gSearchTermSession.appendTerm(searchTerm);
}
}
if (windowArgs.folder) {
// pre select the folderPicker, based on what they selected in the folder pane
gPickedFolder = windowArgs.folder;
try {
document.getElementById("msgNewFolderPopup").selectFolder(windowArgs.folder);
document
.getElementById("msgNewFolderPopup")
.selectFolder(windowArgs.folder);
} catch (ex) {
document.getElementById("msgNewFolderPicker")
.setAttribute("label", windowArgs.folder.prettyName);
document
.getElementById("msgNewFolderPicker")
.setAttribute("label", windowArgs.folder.prettyName);
}
// if the passed in URI is not a server then pre-select it as the folder to search
if (!windowArgs.folder.isServer)
if (!windowArgs.folder.isServer) {
gSearchFolderURIs = windowArgs.folder.URI;
}
}
let folderNameField = document.getElementById("name");
folderNameField.hidden = false;
folderNameField.focus();
if (windowArgs.newFolderName)
if (windowArgs.newFolderName) {
folderNameField.value = windowArgs.newFolderName;
if (windowArgs.searchFolderURIs)
}
if (windowArgs.searchFolderURIs) {
gSearchFolderURIs = windowArgs.searchFolderURIs;
}
setupSearchRows(gSearchTermSession.searchTerms);
doEnabling(); // we only need to disable/enable the OK button for new virtual folders
}
if (typeof windowArgs.searchOnline != "undefined")
if (typeof windowArgs.searchOnline != "undefined") {
document.getElementById("searchOnline").checked = windowArgs.searchOnline;
}
updateOnlineSearchState();
updateFoldersCount();
}
function setupSearchRows(aSearchTerms) {
if (aSearchTerms && aSearchTerms.length > 0)
initializeSearchRows(Ci.nsMsgSearchScope.offlineMail, aSearchTerms); // load the search terms for the folder
else
if (aSearchTerms && aSearchTerms.length > 0) {
initializeSearchRows(Ci.nsMsgSearchScope.offlineMail, aSearchTerms);
} // load the search terms for the folder
else {
onMore(null);
}
}
function updateOnlineSearchState() {
@ -116,8 +141,9 @@ function updateOnlineSearchState() {
}
function InitDialogWithVirtualFolder(aVirtualFolder) {
let virtualFolderWrapper =
VirtualFolderHelper.wrapVirtualFolder(window.arguments[0].folder);
let virtualFolderWrapper = VirtualFolderHelper.wrapVirtualFolder(
window.arguments[0].folder
);
// when editing an existing folder, hide the folder picker that stores the parent location of the folder
document.getElementById("msgNewFolderPicker").collapsed = true;
@ -127,25 +153,29 @@ function InitDialogWithVirtualFolder(aVirtualFolder) {
gSearchFolderURIs = virtualFolderWrapper.searchFolderURIs;
updateFoldersCount();
document.getElementById("searchOnline").checked = virtualFolderWrapper.onlineSearch;
document.getElementById("searchOnline").checked =
virtualFolderWrapper.onlineSearch;
gSearchTermSession = virtualFolderWrapper.searchTermsSession;
setupSearchRows(gSearchTermSession.searchTerms);
// set the name of the folder
let folderBundle = document.getElementById("bundle_folder");
let name = folderBundle.getFormattedString("verboseFolderFormat",
[aVirtualFolder.prettyName, aVirtualFolder.server.prettyName]);
let name = folderBundle.getFormattedString("verboseFolderFormat", [
aVirtualFolder.prettyName,
aVirtualFolder.server.prettyName,
]);
folderNameField.setAttribute("value", name);
// update the window title based on the name of the saved search
document.title = gMessengerBundle.getFormattedString("editVirtualFolderPropertiesTitle",
[aVirtualFolder.prettyName]);
document.title = gMessengerBundle.getFormattedString(
"editVirtualFolderPropertiesTitle",
[aVirtualFolder.prettyName]
);
}
function onFolderPick(aEvent) {
gPickedFolder = aEvent.target._folder;
document.getElementById("msgNewFolderPopup")
.selectFolder(gPickedFolder);
document.getElementById("msgNewFolderPopup").selectFolder(gPickedFolder);
}
function onOK(event) {
@ -153,8 +183,11 @@ function onOK(event) {
var searchOnline = document.getElementById("searchOnline").checked;
if (!gSearchFolderURIs) {
Services.prompt.alert(window, null,
gMessengerBundle.getString("alertNoSearchFoldersSelected"));
Services.prompt.alert(
window,
null,
gMessengerBundle.getString("alertNoSearchFoldersSelected")
);
event.preventDefault();
return;
}
@ -163,8 +196,9 @@ function onOK(event) {
// update the search terms
saveSearchTerms(gSearchTermSession.searchTerms, gSearchTermSession);
// save the settings
let virtualFolderWrapper =
VirtualFolderHelper.wrapVirtualFolder(window.arguments[0].folder);
let virtualFolderWrapper = VirtualFolderHelper.wrapVirtualFolder(
window.arguments[0].folder
);
virtualFolderWrapper.searchTerms = gSearchTermSession.searchTerms;
virtualFolderWrapper.searchFolders = gSearchFolderURIs;
virtualFolderWrapper.onlineSearch = searchOnline;
@ -172,33 +206,45 @@ function onOK(event) {
MailServices.accounts.saveVirtualFolders();
if (window.arguments[0].onOKCallback)
if (window.arguments[0].onOKCallback) {
window.arguments[0].onOKCallback(virtualFolderWrapper.virtualFolder.URI);
}
return;
}
var uri = gPickedFolder.URI;
if (name && uri) { // create a new virtual folder
if (name && uri) {
// create a new virtual folder
// check to see if we already have a folder with the same name and alert the user if so...
var parentFolder = MailUtils.getOrCreateFolder(uri);
// sanity check the name based on the logic used by nsMsgBaseUtils.cpp. It can't start with a '.', it can't end with a '.', '~' or ' '.
// it can't contain a ';' or '#'.
if (/^\.|[\.\~ ]$|[\;\#]/.test(name)) {
Services.prompt.alert(window, null,
gMessengerBundle.getString("folderCreationFailed"));
Services.prompt.alert(
window,
null,
gMessengerBundle.getString("folderCreationFailed")
);
event.preventDefault();
return;
} else if (parentFolder.containsChildNamed(name)) {
Services.prompt.alert(window, null,
gMessengerBundle.getString("folderExists"));
Services.prompt.alert(
window,
null,
gMessengerBundle.getString("folderExists")
);
event.preventDefault();
return;
}
saveSearchTerms(gSearchTermSession.searchTerms, gSearchTermSession);
VirtualFolderHelper.createNewVirtualFolder(name, parentFolder, gSearchFolderURIs,
gSearchTermSession.searchTerms,
searchOnline);
VirtualFolderHelper.createNewVirtualFolder(
name,
parentFolder,
gSearchFolderURIs,
gSearchTermSession.searchTerms,
searchOnline
);
}
}
@ -211,12 +257,15 @@ function chooseFoldersToSearch() {
// if we have some search folders already, then root the folder picker dialog off the account
// for those folders. Otherwise fall back to the preselectedfolderURI which is the parent folder
// for this new virtual folder.
window.openDialog("chrome://messenger/content/virtualFolderListEdit.xul", "",
"chrome,titlebar,modal,centerscreen,resizable",
{
searchFolderURIs: gSearchFolderURIs,
okCallback: onFolderListDialogCallback,
});
window.openDialog(
"chrome://messenger/content/virtualFolderListEdit.xul",
"",
"chrome,titlebar,modal,centerscreen,resizable",
{
searchFolderURIs: gSearchFolderURIs,
okCallback: onFolderListDialogCallback,
}
);
}
// callback routine from chooseFoldersToSearch
@ -230,15 +279,18 @@ function updateFoldersCount() {
let srchFolderUriArray = gSearchFolderURIs.split("|");
let folderCount = gSearchFolderURIs ? srchFolderUriArray.length : 0;
let foldersList = document.getElementById("chosenFoldersCount");
foldersList.textContent =
PluralForm.get(folderCount, gMessengerBundle.getString("virtualFolderSourcesChosen"))
.replace("#1", folderCount);
foldersList.textContent = PluralForm.get(
folderCount,
gMessengerBundle.getString("virtualFolderSourcesChosen")
).replace("#1", folderCount);
if (folderCount > 0) {
let folderNames = [];
for (let folderURI of srchFolderUriArray) {
let folder = MailUtils.getOrCreateFolder(folderURI);
let name = this.gMessengerBundle.getFormattedString("verboseFolderFormat",
[folder.prettyName, folder.server.prettyName]);
let name = this.gMessengerBundle.getFormattedString(
"verboseFolderFormat",
[folder.prettyName, folder.server.prettyName]
);
folderNames.push(name);
}
foldersList.setAttribute("tooltiptext", folderNames.join("\n"));

Разница между файлами не показана из-за своего большого размера Загрузить разницу

Просмотреть файл

@ -49,8 +49,10 @@ var okCallback = null;
(server vs. newsserver)
*/
var {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm");
var {MailServices} = ChromeUtils.import("resource:///modules/MailServices.jsm");
var { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm");
var { MailServices } = ChromeUtils.import(
"resource:///modules/MailServices.jsm"
);
var contentWindow;
@ -121,12 +123,16 @@ function onAccountWizardLoad() {
// Set default value for global inbox checkbox
var checkGlobalInbox = document.getElementById("deferStorage");
checkGlobalInbox.checked = Services.prefs.getBoolPref("mail.accountwizard.deferstorage", false);
checkGlobalInbox.checked = Services.prefs.getBoolPref(
"mail.accountwizard.deferstorage",
false
);
}
function onCancel() {
if ("ActivationOnCancel" in this && this.ActivationOnCancel())
if ("ActivationOnCancel" in this && this.ActivationOnCancel()) {
return false;
}
var firstInvalidAccount = getFirstInvalidAccount();
var closeWizard = true;
@ -156,15 +162,22 @@ function onCancel() {
if (MailServices.accounts.accounts.length < 1) {
let confirmMsg = gPrefsBundle.getString("cancelWizard");
let confirmTitle = gPrefsBundle.getString("accountWizard");
let result = Services.prompt.confirmEx(window, confirmTitle, confirmMsg,
(Services.prompt.BUTTON_TITLE_IS_STRING * Services.prompt.BUTTON_POS_0) +
(Services.prompt.BUTTON_TITLE_IS_STRING * Services.prompt.BUTTON_POS_1),
let result = Services.prompt.confirmEx(
window,
confirmTitle,
confirmMsg,
Services.prompt.BUTTON_TITLE_IS_STRING * Services.prompt.BUTTON_POS_0 +
Services.prompt.BUTTON_TITLE_IS_STRING * Services.prompt.BUTTON_POS_1,
gPrefsBundle.getString("WizardExit"),
gPrefsBundle.getString("WizardContinue"),
null, null, {value: 0});
null,
null,
{ value: 0 }
);
if (result == 1)
if (result == 1) {
closeWizard = false;
}
}
if (top.okCallback && closeWizard) {
@ -181,8 +194,9 @@ function FinishAccount() {
var accountData = gCurrentAccountData;
if (!accountData)
if (!accountData) {
accountData = {};
}
// we may need local folders before account is "Finished"
// if it's a pop3 account which defers to Local Folders.
@ -193,16 +207,22 @@ function FinishAccount() {
FixupAccountDataForIsp(accountData);
// we might be simply finishing another account
if (!gCurrentAccount)
if (!gCurrentAccount) {
gCurrentAccount = createAccount(accountData);
}
// transfer all attributes from the accountdata
finishAccount(gCurrentAccount, accountData);
setupCopiesAndFoldersServer(gCurrentAccount, getCurrentServerIsDeferred(pageData), accountData);
setupCopiesAndFoldersServer(
gCurrentAccount,
getCurrentServerIsDeferred(pageData),
accountData
);
if (gCurrentAccount.incomingServer.canBeDefaultServer)
if (gCurrentAccount.incomingServer.canBeDefaultServer) {
EnableCheckMailAtStartUpIfNeeded(gCurrentAccount);
}
if (!document.getElementById("downloadMsgs").hidden) {
// skip the default biff, we will load messages manually if needed
@ -298,16 +318,21 @@ function AccountDataToPageData(accountData, pageData) {
// take data from each page of pageData and dump it into accountData
// use: to put results of wizard into a account-oriented object
function PageDataToAccountData(pageData, accountData) {
if (!accountData.identity)
if (!accountData.identity) {
accountData.identity = {};
if (!accountData.incomingServer)
}
if (!accountData.incomingServer) {
accountData.incomingServer = {};
if (!accountData.smtp)
}
if (!accountData.smtp) {
accountData.smtp = {};
if (!accountData.pop3)
}
if (!accountData.pop3) {
accountData.pop3 = {};
if (!accountData.imap)
}
if (!accountData.imap) {
accountData.imap = {};
}
var identity = accountData.identity;
var server = accountData.incomingServer;
@ -315,17 +340,21 @@ function PageDataToAccountData(pageData, accountData) {
var pop3 = accountData.pop3;
var imap = accountData.imap;
if (pageData.identity.email)
if (pageData.identity.email) {
identity.email = pageData.identity.email.value;
if (pageData.identity.fullName)
}
if (pageData.identity.fullName) {
identity.fullName = pageData.identity.fullName.value;
}
server.type = getCurrentServerType(pageData);
server.hostName = getCurrentHostname(pageData);
if (getCurrentServerIsDeferred(pageData)) {
try {
let localFoldersServer = MailServices.accounts.localFoldersServer;
let localFoldersAccount = MailServices.accounts.FindAccountForServer(localFoldersServer);
let localFoldersAccount = MailServices.accounts.FindAccountForServer(
localFoldersServer
);
pop3.deferredToAccount = localFoldersAccount.key;
pop3.deferGetNewMail = true;
server["ServerType-pop3"] = pop3;
@ -338,23 +367,31 @@ function PageDataToAccountData(pageData, accountData) {
dump("not setting username/password/etc\n");
} else {
if (pageData.login) {
if (pageData.login.username)
if (pageData.login.username) {
server.username = pageData.login.username.value;
if (pageData.login.password)
}
if (pageData.login.password) {
server.password = pageData.login.password.value;
if (pageData.login.smtpusername)
}
if (pageData.login.smtpusername) {
smtp.username = pageData.login.smtpusername.value;
}
}
dump("pageData.server = " + pageData.server + "\n");
if (pageData.server) {
dump("pageData.server.smtphostname.value = " + pageData.server.smtphostname + "\n");
if (pageData.server.smtphostname &&
pageData.server.smtphostname.value)
dump(
"pageData.server.smtphostname.value = " +
pageData.server.smtphostname +
"\n"
);
if (pageData.server.smtphostname && pageData.server.smtphostname.value) {
smtp.hostname = pageData.server.smtphostname.value;
}
}
if (pageData.identity && pageData.identity.smtpServerKey)
if (pageData.identity && pageData.identity.smtpServerKey) {
identity.smtpServerKey = pageData.identity.smtpServerKey.value;
}
if (pageData.server.port && pageData.server.port.value) {
if (server.type == "imap") {
@ -366,16 +403,19 @@ function PageDataToAccountData(pageData, accountData) {
}
}
if (pageData.server.leaveMessagesOnServer &&
pageData.server.leaveMessagesOnServer.value) {
if (
pageData.server.leaveMessagesOnServer &&
pageData.server.leaveMessagesOnServer.value
) {
pop3.leaveMessagesOnServer = pageData.server.leaveMessagesOnServer.value;
server["ServerType-pop3"] = pop3;
}
}
if (pageData.accname) {
if (pageData.accname.prettyName)
if (pageData.accname.prettyName) {
server.prettyName = pageData.accname.prettyName.value;
}
}
}
@ -386,11 +426,22 @@ function createAccount(accountData) {
var server = accountData.incomingServer;
// for news, username is always null
var username = (server.type == "nntp") ? null : server.username;
dump("MailServices.accounts.createIncomingServer(" +
username + ", " + server.hostName + ", " + server.type + ")\n");
var username = server.type == "nntp" ? null : server.username;
dump(
"MailServices.accounts.createIncomingServer(" +
username +
", " +
server.hostName +
", " +
server.type +
")\n"
);
// Create a (actual) server.
server = MailServices.accounts.createIncomingServer(username, server.hostName, server.type);
server = MailServices.accounts.createIncomingServer(
username,
server.hostName,
server.type
);
dump("MailServices.accounts.createAccount()\n");
// Create an account.
@ -405,8 +456,9 @@ function createAccount(accountData) {
// New nntp identities should use plain text by default;
// we want that GNKSA (The Good Net-Keeping Seal of Approval).
if (server.type == "nntp")
if (server.type == "nntp") {
identity.composeHtml = false;
}
account.addIdentity(identity);
}
@ -433,8 +485,8 @@ function finishAccount(account, accountData) {
// If so, we use the type to get the IID, QueryInterface
// as appropriate, then copy the data over.
const typeProperty = "ServerType-" + srcServer.type;
let serverAttrs = (typeProperty in srcServer) ?
srcServer[typeProperty] : null;
let serverAttrs =
typeProperty in srcServer ? srcServer[typeProperty] : null;
dump(`srcServer.${typeProperty} = ${serverAttrs}\n`);
if (serverAttrs) {
// handle server-specific stuff
@ -460,65 +512,65 @@ function finishAccount(account, accountData) {
}
// copy identity info
var destIdentity = account.identities.length ?
account.identities.queryElementAt(0, nsIMsgIdentity) :
null;
var destIdentity = account.identities.length
? account.identities.queryElementAt(0, nsIMsgIdentity)
: null;
if (destIdentity) { // does this account have an identity?
if (accountData.identity && accountData.identity.email) {
// fixup the email address if we have a default domain
let emailArray = accountData.identity.email.split("@");
if (emailArray.length < 2 && accountData.domain) {
accountData.identity.email += "@" + accountData.domain;
}
copyObjectToInterface(destIdentity, accountData.identity, true);
destIdentity.valid = true;
if (destIdentity) {
// does this account have an identity?
if (accountData.identity && accountData.identity.email) {
// fixup the email address if we have a default domain
let emailArray = accountData.identity.email.split("@");
if (emailArray.length < 2 && accountData.domain) {
accountData.identity.email += "@" + accountData.domain;
}
/**
* If signature file need to be set, get the path to the signature file.
* Signature files, if exist, are placed under default location. Get
* default files location for messenger using directory service. Signature
* file name should be extracted from the account data to build the complete
* path for signature file. Once the path is built, set the identity's signature pref.
*/
if (destIdentity.attachSignature) {
var sigFileName = accountData.signatureFileName;
let sigFile = MailServices.mailSession.getDataFilesDir("messenger");
sigFile.append(sigFileName);
destIdentity.signature = sigFile;
copyObjectToInterface(destIdentity, accountData.identity, true);
destIdentity.valid = true;
}
/**
* If signature file need to be set, get the path to the signature file.
* Signature files, if exist, are placed under default location. Get
* default files location for messenger using directory service. Signature
* file name should be extracted from the account data to build the complete
* path for signature file. Once the path is built, set the identity's signature pref.
*/
if (destIdentity.attachSignature) {
var sigFileName = accountData.signatureFileName;
let sigFile = MailServices.mailSession.getDataFilesDir("messenger");
sigFile.append(sigFileName);
destIdentity.signature = sigFile;
}
if (accountData.smtp.hostname && !destIdentity.smtpServerKey) {
// hostname + no key => create a new SMTP server.
let smtpServer = MailServices.smtp.createServer();
var isDefaultSmtpServer;
if (!MailServices.smtp.defaultServer.hostname) {
MailServices.smtp.defaultServer = smtpServer;
isDefaultSmtpServer = true;
}
if (accountData.smtp.hostname && !destIdentity.smtpServerKey) {
// hostname + no key => create a new SMTP server.
copyObjectToInterface(smtpServer, accountData.smtp, false);
let smtpServer = MailServices.smtp.createServer();
var isDefaultSmtpServer;
if (!MailServices.smtp.defaultServer.hostname) {
MailServices.smtp.defaultServer = smtpServer;
isDefaultSmtpServer = true;
}
// If it's the default server we created, make the identity use
// "Use Default" by default.
destIdentity.smtpServerKey = isDefaultSmtpServer ? "" : smtpServer.key;
}
} // if the account has an identity...
copyObjectToInterface(smtpServer, accountData.smtp, false);
// If it's the default server we created, make the identity use
// "Use Default" by default.
destIdentity.smtpServerKey =
(isDefaultSmtpServer) ? "" : smtpServer.key;
}
} // if the account has an identity...
if (this.FinishAccountHook != undefined) {
this.FinishAccountHook(accountData.domain);
}
if (this.FinishAccountHook != undefined) {
this.FinishAccountHook(accountData.domain);
}
}
// Helper method used by copyObjectToInterface which attempts to set dest[attribute] as a generic
// attribute on the xpconnect object, src.
// This routine skips any attribute that begins with ServerType-
function setGenericAttribute(dest, src, attribute) {
if (!(attribute.toLowerCase().startsWith("servertype-")) && src[attribute]) {
if (!attribute.toLowerCase().startsWith("servertype-") && src[attribute]) {
switch (typeof src[attribute]) {
case "string":
dest.setUnicharAttribute(attribute, src[attribute]);
@ -530,7 +582,13 @@ function setGenericAttribute(dest, src, attribute) {
dest.setIntAttribute(attribute, src[attribute]);
break;
default:
dump("Error: No Generic attribute " + attribute + " found for: " + dest + "\n");
dump(
"Error: No Generic attribute " +
attribute +
" found for: " +
dest +
"\n"
);
break;
}
}
@ -542,15 +600,21 @@ function setGenericAttribute(dest, src, attribute) {
// and try setting it generically. This assumes that src supports setIntAttribute, setUnicharAttribute
// and setBoolAttribute.
function copyObjectToInterface(dest, src, useGenericFallback) {
if (!dest) return;
if (!src) return;
if (!dest) {
return;
}
if (!src) {
return;
}
var attribute;
for (attribute in src) {
if (dest.__lookupSetter__(attribute)) {
if (dest[attribute] != src[attribute])
if (dest[attribute] != src[attribute]) {
dest[attribute] = src[attribute];
} else if (useGenericFallback) { // fall back to setting the attribute generically
}
} else if (useGenericFallback) {
// fall back to setting the attribute generically
setGenericAttribute(dest, src, attribute);
}
} // for each attribute in src we want to copy
@ -563,7 +627,7 @@ function verifyLocalFoldersAccount() {
try {
localMailServer = MailServices.accounts.localFoldersServer;
} catch (ex) {
// dump("exception in findserver: " + ex + "\n");
// dump("exception in findserver: " + ex + "\n");
localMailServer = null;
}
@ -575,7 +639,9 @@ function verifyLocalFoldersAccount() {
try {
localMailServer = MailServices.accounts.localFoldersServer;
} catch (ex) {
dump("error! we should have found the local mail server after we created it.\n");
dump(
"error! we should have found the local mail server after we created it.\n"
);
localMailServer = null;
}
}
@ -590,12 +656,14 @@ function setupCopiesAndFoldersServer(account, accountIsDeferred, accountData) {
// This function sets up the default send preferences. The send preferences
// go on identities, so there is no need to continue without any identities.
if (server.type == "rss" || account.identities.length == 0)
if (server.type == "rss" || account.identities.length == 0) {
return false;
}
let identity = account.identities.queryElementAt(0, Ci.nsIMsgIdentity);
// For this server, do we default the folder prefs to this server, or to the "Local Folders" server
// If it's deferred, we use the local folders account.
var defaultCopiesAndFoldersPrefsToServer = !accountIsDeferred && server.defaultCopiesAndFoldersPrefsToServer;
var defaultCopiesAndFoldersPrefsToServer =
!accountIsDeferred && server.defaultCopiesAndFoldersPrefsToServer;
var copiesAndFoldersServer = null;
if (defaultCopiesAndFoldersPrefsToServer) {
@ -608,7 +676,11 @@ function setupCopiesAndFoldersServer(account, accountIsDeferred, accountData) {
copiesAndFoldersServer = MailServices.accounts.localFoldersServer;
}
setDefaultCopiesAndFoldersPrefs(identity, copiesAndFoldersServer, accountData);
setDefaultCopiesAndFoldersPrefs(
identity,
copiesAndFoldersServer,
accountData
);
} catch (ex) {
// return false (meaning we did not setupCopiesAndFoldersServer)
// on any error
@ -655,35 +727,54 @@ function setDefaultCopiesAndFoldersPrefs(identity, server, accountData) {
otherwise we use internal names known to everyone like Sent, Templates and Drafts */
// Note the capital F, D and S!
var draftFolder = (accountData.identity && accountData.identity.DraftFolder ?
accountData.identity.DraftFolder : "Drafts");
var stationeryFolder = (accountData.identity && accountData.identity.StationeryFolder ?
accountData.identity.StationeryFolder : "Templates");
var fccFolder = (accountData.identity && accountData.identity.FccFolder ?
accountData.identity.FccFolder : "Sent");
var draftFolder =
accountData.identity && accountData.identity.DraftFolder
? accountData.identity.DraftFolder
: "Drafts";
var stationeryFolder =
accountData.identity && accountData.identity.StationeryFolder
? accountData.identity.StationeryFolder
: "Templates";
var fccFolder =
accountData.identity && accountData.identity.FccFolder
? accountData.identity.FccFolder
: "Sent";
identity.draftFolder = msgFolder.server.serverURI + folderDelim + draftFolder;
identity.stationeryFolder = msgFolder.server.serverURI + folderDelim + stationeryFolder;
identity.stationeryFolder =
msgFolder.server.serverURI + folderDelim + stationeryFolder;
identity.fccFolder = msgFolder.server.serverURI + folderDelim + fccFolder;
// Note the capital F, D and S!
identity.fccFolderPickerMode = (accountData.identity &&
accountData.identity.FccFolder ? 1 : gDefaultSpecialFolderPickerMode);
identity.draftsFolderPickerMode = (accountData.identity &&
accountData.identity.DraftFolder ? 1 : gDefaultSpecialFolderPickerMode);
identity.tmplFolderPickerMode = (accountData.identity &&
accountData.identity.StationeryFolder ? 1 : gDefaultSpecialFolderPickerMode);
identity.fccFolderPickerMode =
accountData.identity && accountData.identity.FccFolder
? 1
: gDefaultSpecialFolderPickerMode;
identity.draftsFolderPickerMode =
accountData.identity && accountData.identity.DraftFolder
? 1
: gDefaultSpecialFolderPickerMode;
identity.tmplFolderPickerMode =
accountData.identity && accountData.identity.StationeryFolder
? 1
: gDefaultSpecialFolderPickerMode;
}
function AccountExists(userName, hostName, serverType) {
return MailServices.accounts.findRealServer(userName, hostName, serverType, 0);
return MailServices.accounts.findRealServer(
userName,
hostName,
serverType,
0
);
}
function getFirstInvalidAccount() {
let invalidAccounts = getInvalidAccounts(MailServices.accounts.accounts);
if (invalidAccounts.length > 0)
if (invalidAccounts.length > 0) {
return invalidAccounts[0];
}
return null;
}
@ -692,13 +783,19 @@ function checkForInvalidAccounts() {
if (firstInvalidAccount) {
var pageData = GetPageData();
dump("We have an invalid account, " + firstInvalidAccount + ", let's use that!\n");
dump(
"We have an invalid account, " +
firstInvalidAccount +
", let's use that!\n"
);
gCurrentAccount = firstInvalidAccount;
var accountData = {};
accountData.incomingServer = firstInvalidAccount.incomingServer;
accountData.identity = firstInvalidAccount.identities.queryElementAt(0,
nsIMsgIdentity);
accountData.identity = firstInvalidAccount.identities.queryElementAt(
0,
nsIMsgIdentity
);
accountData.smtp = MailServices.smtp.defaultServer;
AccountDataToPageData(accountData, pageData);
@ -712,14 +809,20 @@ function checkForInvalidAccounts() {
// sets the page data, automatically creating the arrays as necessary
function setPageData(pageData, tag, slot, value) {
if (!pageData[tag]) pageData[tag] = [];
if (!pageData[tag]) {
pageData[tag] = [];
}
if (value == undefined) {
// clear out this slot
if (pageData[tag][slot]) delete pageData[tag][slot];
if (pageData[tag][slot]) {
delete pageData[tag][slot];
}
} else {
// pre-fill this slot
if (!pageData[tag][slot]) pageData[tag][slot] = [];
if (!pageData[tag][slot]) {
pageData[tag][slot] = [];
}
pageData[tag][slot].id = slot;
pageData[tag][slot].value = value;
}
@ -727,8 +830,9 @@ function setPageData(pageData, tag, slot, value) {
// value of checkbox on the first page
function serverIsNntp(pageData) {
if (pageData.accounttype.newsaccount)
if (pageData.accounttype.newsaccount) {
return pageData.accounttype.newsaccount.value;
}
return false;
}
@ -753,31 +857,39 @@ function getCurrentUserName(pageData) {
}
function getCurrentServerType(pageData) {
var servertype = "pop3"; // hopefully don't resort to default!
if (serverIsNntp(pageData))
var servertype = "pop3"; // hopefully don't resort to default!
if (serverIsNntp(pageData)) {
servertype = "nntp";
else if (pageData.server && pageData.server.servertype)
} else if (pageData.server && pageData.server.servertype) {
servertype = pageData.server.servertype.value;
}
return servertype;
}
function getCurrentServerIsDeferred(pageData) {
var serverDeferred = false;
if (getCurrentServerType(pageData) == "pop3" && pageData.server && pageData.server.deferStorage)
if (
getCurrentServerType(pageData) == "pop3" &&
pageData.server &&
pageData.server.deferStorage
) {
serverDeferred = pageData.server.deferStorage.value;
}
return serverDeferred;
}
function getCurrentHostname(pageData) {
if (serverIsNntp(pageData))
if (serverIsNntp(pageData)) {
return pageData.newsserver.hostname.value;
}
return pageData.server.hostname.value;
}
function GetPageData() {
if (!gPageData)
if (!gPageData) {
gPageData = {};
}
return gPageData;
}
@ -789,28 +901,32 @@ function FixupAccountDataForIsp(accountData) {
// no fixup for news
// setting the username does bad things
// see bugs #42105 and #154213
if (accountData.incomingServer.type == "nntp")
if (accountData.incomingServer.type == "nntp") {
return;
}
var email = accountData.identity.email;
// The identity might not have an email address, which is what the rest of
// this function is looking for.
if (!email)
if (!email) {
return;
}
// fix up the username
if (!accountData.incomingServer.username)
if (!accountData.incomingServer.username) {
accountData.incomingServer.username = getUsernameFromEmail(email);
}
if (!accountData.smtp.username) {
// fix for bug #107953
// if incoming hostname is same as smtp hostname
// use the server username (instead of the email username)
if (accountData.smtp.hostname == accountData.incomingServer.hostName)
if (accountData.smtp.hostname == accountData.incomingServer.hostName) {
accountData.smtp.username = accountData.incomingServer.username;
else
} else {
accountData.smtp.username = getUsernameFromEmail(email);
}
}
}
@ -821,9 +937,9 @@ function onFlush() {
}
/** If there are no default accounts..
* this is will be the new default, so enable
* check for mail at startup
*/
* this is will be the new default, so enable
* check for mail at startup
*/
function EnableCheckMailAtStartUpIfNeeded(newAccount) {
// Check if default account existed.
// If no such account, make this one the default account

Просмотреть файл

@ -3,9 +3,13 @@
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
var {cleanUpHostName, isLegalHostNameOrIP} = ChromeUtils.import("resource:///modules/hostnameUtils.jsm");
var {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm");
var {MailServices} = ChromeUtils.import("resource:///modules/MailServices.jsm");
var { cleanUpHostName, isLegalHostNameOrIP } = ChromeUtils.import(
"resource:///modules/hostnameUtils.jsm"
);
var { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm");
var { MailServices } = ChromeUtils.import(
"resource:///modules/MailServices.jsm"
);
var gSmtpServer;
var gSmtpUsername;
@ -55,58 +59,67 @@ function onAccept(event) {
}
function initSmtpSettings(server) {
gSmtpUsername = document.getElementById("smtp.username");
gSmtpDescription = document.getElementById("smtp.description");
gSmtpUsernameLabel = document.getElementById("smtp.username.label");
gSmtpHostname = document.getElementById("smtp.hostname");
gSmtpPort = document.getElementById("smtp.port");
gSmtpAuthMethod = document.getElementById("smtp.authMethod");
gSmtpSocketType = document.getElementById("smtp.socketType");
gDefaultPort = document.getElementById("smtp.defaultPort");
gPort = document.getElementById("smtp.port");
gSmtpUsername = document.getElementById("smtp.username");
gSmtpDescription = document.getElementById("smtp.description");
gSmtpUsernameLabel = document.getElementById("smtp.username.label");
gSmtpHostname = document.getElementById("smtp.hostname");
gSmtpPort = document.getElementById("smtp.port");
gSmtpAuthMethod = document.getElementById("smtp.authMethod");
gSmtpSocketType = document.getElementById("smtp.socketType");
gDefaultPort = document.getElementById("smtp.defaultPort");
gPort = document.getElementById("smtp.port");
if (server) {
gSmtpHostname.value = server.hostname;
gSmtpDescription.value = server.description;
gSmtpPort.value = server.port;
gSmtpUsername.value = server.username;
gSmtpAuthMethod.value = server.authMethod;
gSmtpSocketType.value = (server.socketType < 4) ? server.socketType : 1;
} else {
// New server, load default values.
gSmtpAuthMethod.value = Services.prefs.getIntPref("mail.smtpserver.default.authMethod");
gSmtpSocketType.value = Services.prefs.getIntPref("mail.smtpserver.default.try_ssl");
}
if (server) {
gSmtpHostname.value = server.hostname;
gSmtpDescription.value = server.description;
gSmtpPort.value = server.port;
gSmtpUsername.value = server.username;
gSmtpAuthMethod.value = server.authMethod;
gSmtpSocketType.value = server.socketType < 4 ? server.socketType : 1;
} else {
// New server, load default values.
gSmtpAuthMethod.value = Services.prefs.getIntPref(
"mail.smtpserver.default.authMethod"
);
gSmtpSocketType.value = Services.prefs.getIntPref(
"mail.smtpserver.default.try_ssl"
);
}
// Although sslChanged will set a label for cleartext password,
// we need to use the long label so that we can size the dialog.
setLabelFromStringBundle("authMethod-no", "authNo");
setLabelFromStringBundle("authMethod-password-encrypted",
"authPasswordEncrypted");
setLabelFromStringBundle("authMethod-password-cleartext",
"authPasswordCleartextInsecurely");
setLabelFromStringBundle("authMethod-kerberos", "authKerberos");
setLabelFromStringBundle("authMethod-ntlm", "authNTLM");
setLabelFromStringBundle("authMethod-oauth2", "authOAuth2");
setLabelFromStringBundle("authMethod-anysecure", "authAnySecure");
setLabelFromStringBundle("authMethod-any", "authAny");
// Although sslChanged will set a label for cleartext password,
// we need to use the long label so that we can size the dialog.
setLabelFromStringBundle("authMethod-no", "authNo");
setLabelFromStringBundle(
"authMethod-password-encrypted",
"authPasswordEncrypted"
);
setLabelFromStringBundle(
"authMethod-password-cleartext",
"authPasswordCleartextInsecurely"
);
setLabelFromStringBundle("authMethod-kerberos", "authKerberos");
setLabelFromStringBundle("authMethod-ntlm", "authNTLM");
setLabelFromStringBundle("authMethod-oauth2", "authOAuth2");
setLabelFromStringBundle("authMethod-anysecure", "authAnySecure");
setLabelFromStringBundle("authMethod-any", "authAny");
sizeToContent();
sizeToContent();
sslChanged(false);
authMethodChanged(false);
sslChanged(false);
authMethodChanged(false);
if (MailServices.smtp.defaultServer)
onLockPreference();
if (MailServices.smtp.defaultServer) {
onLockPreference();
}
// Hide deprecated/hidden auth options, unless selected
hideUnlessSelected(document.getElementById("authMethod-anysecure"));
hideUnlessSelected(document.getElementById("authMethod-any"));
// Hide deprecated/hidden auth options, unless selected
hideUnlessSelected(document.getElementById("authMethod-anysecure"));
hideUnlessSelected(document.getElementById("authMethod-any"));
// "STARTTLS, if available" is vulnerable to MITM attacks so we shouldn't
// allow users to choose it anymore. Hide the option unless the user already
// has it set.
hideUnlessSelected(document.getElementById("connectionSecurityType-1"));
// "STARTTLS, if available" is vulnerable to MITM attacks so we shouldn't
// allow users to choose it anymore. Hide the option unless the user already
// has it set.
hideUnlessSelected(document.getElementById("connectionSecurityType-1"));
}
function hideUnlessSelected(element) {
@ -114,22 +127,24 @@ function hideUnlessSelected(element) {
}
function setLabelFromStringBundle(elementID, stringName) {
document.getElementById(elementID).label =
document.getElementById("bundle_messenger").getString(stringName);
document.getElementById(elementID).label = document
.getElementById("bundle_messenger")
.getString(stringName);
}
// Disables xul elements that have associated preferences locked.
function onLockPreference() {
try {
let allPrefElements = {
hostname: gSmtpHostname,
description: gSmtpDescription,
port: gSmtpPort,
authMethod: gSmtpAuthMethod,
try_ssl: gSmtpSocketType,
hostname: gSmtpHostname,
description: gSmtpDescription,
port: gSmtpPort,
authMethod: gSmtpAuthMethod,
try_ssl: gSmtpSocketType,
};
disableIfLocked(allPrefElements);
} catch (e) { // non-fatal
} catch (e) {
// non-fatal
Cu.reportError("Error while getting locked prefs: " + e);
}
}
@ -142,25 +157,27 @@ function onLockPreference() {
* TODO: try to merge this with disableIfLocked function in am-offline.js (bug 755885)
*/
function disableIfLocked(prefstrArray) {
let finalPrefString = "mail.smtpserver." +
MailServices.smtp.defaultServer.key + ".";
let finalPrefString =
"mail.smtpserver." + MailServices.smtp.defaultServer.key + ".";
let smtpPrefBranch = Services.prefs.getBranch(finalPrefString);
for (let prefstring in prefstrArray)
if (smtpPrefBranch.prefIsLocked(prefstring))
for (let prefstring in prefstrArray) {
if (smtpPrefBranch.prefIsLocked(prefstring)) {
prefstrArray[prefstring].disabled = true;
}
}
}
function saveSmtpSettings(server) {
// dump("Saving to " + server + "\n");
if (server) {
server.hostname = cleanUpHostName(gSmtpHostname.value);
server.description = gSmtpDescription.value;
server.port = gSmtpPort.value;
server.authMethod = gSmtpAuthMethod.value;
server.username = gSmtpUsername.value;
server.socketType = gSmtpSocketType.value;
}
// dump("Saving to " + server + "\n");
if (server) {
server.hostname = cleanUpHostName(gSmtpHostname.value);
server.description = gSmtpDescription.value;
server.port = gSmtpPort.value;
server.authMethod = gSmtpAuthMethod.value;
server.username = gSmtpUsername.value;
server.socketType = gSmtpSocketType.value;
}
}
function authMethodChanged(userAction) {
@ -196,14 +213,21 @@ function sslChanged(userAction) {
// or the user is causing the default port to change,
// and the port is set to the default for the other protocol,
// then set the port to the default for the new protocol.
if ((gPort.value == 0) ||
(userAction && (gDefaultPort.value != prevDefaultPort) &&
(gPort.value == otherDefaultPort)))
if (
gPort.value == 0 ||
(userAction &&
gDefaultPort.value != prevDefaultPort &&
gPort.value == otherDefaultPort)
) {
gPort.value = gDefaultPort.value;
}
// switch "insecure password" label
setLabelFromStringBundle("authMethod-password-cleartext",
socketType == Ci.nsMsgSocketType.SSL ||
socketType == Ci.nsMsgSocketType.alwaysSTARTTLS ?
"authPasswordCleartextViaSSL" : "authPasswordCleartextInsecurely");
setLabelFromStringBundle(
"authMethod-password-cleartext",
socketType == Ci.nsMsgSocketType.SSL ||
socketType == Ci.nsMsgSocketType.alwaysSTARTTLS
? "authPasswordCleartextViaSSL"
: "authPasswordCleartextInsecurely"
);
}

Просмотреть файл

@ -4,17 +4,21 @@
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
/* import-globals-from AccountManager.js */
/* globals SelectFolder */// From messageWindow.js or msgMail3PaneWindow.js.
/* globals MsgGetMessage */// From mailWindowOverlay.js.
/* globals SelectFolder */ // From messageWindow.js or msgMail3PaneWindow.js.
/* globals MsgGetMessage */ // From mailWindowOverlay.js.
var {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm");
var {AppConstants} = ChromeUtils.import("resource://gre/modules/AppConstants.jsm");
var {MailServices} = ChromeUtils.import("resource:///modules/MailServices.jsm");
var { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm");
var { AppConstants } = ChromeUtils.import(
"resource://gre/modules/AppConstants.jsm"
);
var { MailServices } = ChromeUtils.import(
"resource:///modules/MailServices.jsm"
);
var gAnyValidIdentity = false; // If there are no valid identities for any account
// returns the first account with an invalid server or identity
var gNewAccountToLoad = null; // used to load new messages if we come from the mail3pane
var gNewAccountToLoad = null; // used to load new messages if we come from the mail3pane
function getInvalidAccounts(accounts) {
let numAccounts = accounts.length;
@ -24,7 +28,7 @@ function getInvalidAccounts(accounts) {
let account = accounts.queryElementAt(i, Ci.nsIMsgAccount);
try {
if (!account.incomingServer.valid) {
invalidAccounts[invalidAccounts.length] = account;
invalidAccounts[invalidAccounts.length] = account;
// skip to the next account
continue;
}
@ -52,18 +56,27 @@ function showMailIntegrationDialog() {
const nsIShellService = Ci.nsIShellService;
try {
var shellService = Cc["@mozilla.org/suite/shell-service;1"]
.getService(nsIShellService);
var appTypesCheck = shellService.shouldBeDefaultClientFor &
(nsIShellService.MAIL | nsIShellService.NEWS);
var shellService = Cc["@mozilla.org/suite/shell-service;1"].getService(
nsIShellService
);
var appTypesCheck =
shellService.shouldBeDefaultClientFor &
(nsIShellService.MAIL | nsIShellService.NEWS);
// show the default client dialog only if we have at least one account,
// if we should check for the default client, and we want to check if we are
// the default for mail/news and are not the default client for mail/news
if (appTypesCheck && shellService.shouldCheckDefaultClient &&
!shellService.isDefaultClient(true, appTypesCheck))
window.openDialog("chrome://communicator/content/defaultClientDialog.xul",
"DefaultClient", "modal,centerscreen,chrome,resizable=no");
if (
appTypesCheck &&
shellService.shouldCheckDefaultClient &&
!shellService.isDefaultClient(true, appTypesCheck)
) {
window.openDialog(
"chrome://communicator/content/defaultClientDialog.xul",
"DefaultClient",
"modal,centerscreen,chrome,resizable=no"
);
}
} catch (ex) {}
}
@ -89,7 +102,9 @@ function verifyAccounts(wizardCallback, needsIdentity, wizardOpen) {
// migrate quoting preferences from global to per account. This function returns
// true if it had to migrate, which we will use to mean this is a just migrated
// or new profile
var newProfile = migrateGlobalQuotingPrefs(MailServices.accounts.allIdentities);
var newProfile = migrateGlobalQuotingPrefs(
MailServices.accounts.allIdentities
);
var accounts = MailServices.accounts.accounts;
@ -106,12 +121,20 @@ function verifyAccounts(wizardCallback, needsIdentity, wizardOpen) {
if (newProfile) {
// check if MCD is configured. If not, say this is not a new profile
// so that we don't accidentally remigrate non MCD profiles.
var adminUrl = Services.prefs.getCharPref("autoadmin.global_config_url", "");
if (!adminUrl)
var adminUrl = Services.prefs.getCharPref(
"autoadmin.global_config_url",
""
);
if (!adminUrl) {
newProfile = false;
}
}
if ((newProfile && !accountCount) || accountCount == invalidAccounts.length)
if (
(newProfile && !accountCount) ||
accountCount == invalidAccounts.length
) {
openWizard = true;
}
// openWizard is true if messenger migration returns some kind of
// error (including those cases where there is nothing to migrate).
@ -124,11 +147,12 @@ function verifyAccounts(wizardCallback, needsIdentity, wizardOpen) {
// wizard if the user does not have any identities defined and tries to
// compose mail.
if (openWizard || prefillAccount || ((!gAnyValidIdentity) && needsIdentity)) {
if (wizardOpen != undefined)
if (openWizard || prefillAccount || (!gAnyValidIdentity && needsIdentity)) {
if (wizardOpen != undefined) {
wizardOpen(wizardCallback);
else
} else {
MsgAccountWizard(wizardCallback);
}
ret = false;
} else {
var localFoldersExists;
@ -139,8 +163,9 @@ function verifyAccounts(wizardCallback, needsIdentity, wizardOpen) {
}
// we didn't create the MsgAccountWizard - we need to verify that local folders exists.
if (!localFoldersExists)
if (!localFoldersExists) {
MailServices.accounts.createLocalMailAccount();
}
}
// This will do nothing on platforms without a shell service
@ -159,7 +184,9 @@ function verifyAccounts(wizardCallback, needsIdentity, wizardOpen) {
// handler, then the parent window doesn't appear until after the wizard
// has closed, and this is confusing to the user
function MsgAccountWizard(wizardCallback) {
setTimeout(function() { msgOpenAccountWizard(wizardCallback); }, 0);
setTimeout(function() {
msgOpenAccountWizard(wizardCallback);
}, 0);
}
/**
@ -172,18 +199,24 @@ function MsgAccountWizard(wizardCallback) {
function msgOpenAccountWizard(wizardCallback, type) {
gNewAccountToLoad = null;
window.openDialog("chrome://messenger/content/AccountWizard.xul", "AccountWizard",
"chrome,modal,titlebar,centerscreen",
{okCallback: wizardCallback, acctType: type});
window.openDialog(
"chrome://messenger/content/AccountWizard.xul",
"AccountWizard",
"chrome,modal,titlebar,centerscreen",
{ okCallback: wizardCallback, acctType: type }
);
loadInboxForNewAccount();
// If we started with no servers at all and "smtp servers" list selected,
// refresh display somehow. Bug 58506.
// TODO Better fix: select newly created account (in all cases)
if (typeof(getCurrentAccount) == "function" && // in AccountManager, not menu
!getCurrentAccount())
if (
typeof getCurrentAccount == "function" && // in AccountManager, not menu
!getCurrentAccount()
) {
selectServer(null, null);
}
}
function initAccountWizardTB(args) {
@ -197,10 +230,13 @@ function initAccountWizardTB(args) {
let accountwizard = document.getElementById("AccountWizard");
let acctyperadio = document.getElementById("acctyperadio");
let feedRadio = acctyperadio.querySelector("radio[value='Feeds']");
if (feedRadio)
if (feedRadio) {
feedRadio.remove();
}
if (selType) {
acctyperadio.selectedItem = acctyperadio.querySelector("radio[value='" + selType + "']");
acctyperadio.selectedItem = acctyperadio.querySelector(
"radio[value='" + selType + "']"
);
accountwizard.advance("identitypage");
} else {
acctyperadio.selectedItem = acctyperadio.getItemAtIndex(0);
@ -212,14 +248,19 @@ function AddMailAccount() {
}
function AddIMAccount() {
window.openDialog("chrome://messenger/content/chat/imAccountWizard.xul",
"", "chrome,modal,titlebar,centerscreen");
window.openDialog(
"chrome://messenger/content/chat/imAccountWizard.xul",
"",
"chrome,modal,titlebar,centerscreen"
);
}
function AddFeedAccount() {
window.openDialog("chrome://messenger-newsblog/content/feedAccountWizard.xul",
"", "chrome,modal,titlebar,centerscreen");
window.openDialog(
"chrome://messenger-newsblog/content/feedAccountWizard.xul",
"",
"chrome,modal,titlebar,centerscreen"
);
}
/**
@ -233,7 +274,9 @@ function AddFeedAccount() {
* @param aServer The server of the account to select. Optional.
*/
function MsgAccountManager(selectPage, aServer) {
var existingAccountManager = Services.wm.getMostRecentWindow("mailnews:accountmanager");
var existingAccountManager = Services.wm.getMostRecentWindow(
"mailnews:accountmanager"
);
if (existingAccountManager) {
existingAccountManager.focus();
@ -241,20 +284,27 @@ function MsgAccountManager(selectPage, aServer) {
if (!aServer) {
if (typeof window.GetSelectedMsgFolders === "function") {
let folders = window.GetSelectedMsgFolders();
if (folders.length > 0)
if (folders.length > 0) {
aServer = folders[0].server;
}
}
if (!aServer && (typeof window.GetDefaultAccountRootFolder === "function")) {
if (
!aServer &&
typeof window.GetDefaultAccountRootFolder === "function"
) {
let folder = window.GetDefaultAccountRootFolder();
if (folder instanceof Ci.nsIMsgFolder)
if (folder instanceof Ci.nsIMsgFolder) {
aServer = folder.server;
}
}
}
window.openDialog("chrome://messenger/content/AccountManager.xul",
"AccountManager",
"chrome,centerscreen,modal,titlebar,resizable",
{ server: aServer, selectPage });
window.openDialog(
"chrome://messenger/content/AccountManager.xul",
"AccountManager",
"chrome,centerscreen,modal,titlebar,resizable",
{ server: aServer, selectPage }
);
}
}
@ -280,7 +330,10 @@ function migrateGlobalQuotingPrefs(allIdentities) {
// migrate and delete, if default just delete.
var reply_on_top = 0;
var auto_quote = true;
var quotingPrefs = Services.prefs.getIntPref("mailnews.quotingPrefs.version", 0);
var quotingPrefs = Services.prefs.getIntPref(
"mailnews.quotingPrefs.version",
0
);
var migrated = false;
// If the quotingPrefs version is 0 then we need to migrate our preferences
@ -311,42 +364,52 @@ function migrateGlobalQuotingPrefs(allIdentities) {
// handler, then the parent window doesn't appear until after the wizard
// has closed, and this is confusing to the user
function NewMailAccount(msgWindow, okCallback, extraData) {
if (!msgWindow)
if (!msgWindow) {
throw new Error("NewMailAccount must be given a msgWindow.");
}
// Populate the extra data.
if (!extraData)
if (!extraData) {
extraData = {};
}
extraData.msgWindow = msgWindow;
let mail3Pane = Services.wm.getMostRecentWindow("mail:3pane");
if (!extraData.NewMailAccount)
if (!extraData.NewMailAccount) {
extraData.NewMailAccount = NewMailAccount;
}
if (!extraData.msgNewMailAccount)
if (!extraData.msgNewMailAccount) {
extraData.msgNewMailAccount = msgNewMailAccount;
}
if (!extraData.NewComposeMessage)
if (!extraData.NewComposeMessage) {
extraData.NewComposeMessage = mail3Pane.ComposeMessage;
}
if (!extraData.openAddonsMgr)
if (!extraData.openAddonsMgr) {
extraData.openAddonsMgr = mail3Pane.openAddonsMgr;
}
if (!extraData.okCallback)
if (!extraData.okCallback) {
extraData.okCallback = null;
}
if (!extraData.success)
if (!extraData.success) {
extraData.success = false;
}
setTimeout(extraData.msgNewMailAccount, 0, msgWindow, okCallback, extraData);
}
function NewMailAccountProvisioner(aMsgWindow, args) {
if (!args)
if (!args) {
args = {};
if (!aMsgWindow)
}
if (!aMsgWindow) {
aMsgWindow = MailServices.mailSession.topmostMsgWindow;
}
args.msgWindow = aMsgWindow;
@ -368,7 +431,8 @@ function NewMailAccountProvisioner(aMsgWindow, args) {
// If there's already an accountProvisionerTab open, just focus it instead
// of opening a new dialog.
let apTab = tabmail.getTabInfoForCurrentOrFirstModeInstance(
tabmail.tabModes.accountProvisionerTab);
tabmail.tabModes.accountProvisionerTab
);
if (apTab) {
tabmail.switchToTab(apTab);
@ -377,20 +441,25 @@ function NewMailAccountProvisioner(aMsgWindow, args) {
// XXX make sure these are all defined in all contexts... to be on the safe
// side, just get a mail:3pane and borrow the functions from it?
if (!args.NewMailAccount)
if (!args.NewMailAccount) {
args.NewMailAccount = NewMailAccount;
}
if (!args.msgNewMailAccount)
if (!args.msgNewMailAccount) {
args.msgNewMailAccount = msgNewMailAccount;
}
if (!args.NewComposeMessage)
if (!args.NewComposeMessage) {
args.NewComposeMessage = mail3Pane.ComposeMessage;
}
if (!args.openAddonsMgr)
if (!args.openAddonsMgr) {
args.openAddonsMgr = mail3Pane.openAddonsMgr;
}
if (!args.okCallback)
if (!args.okCallback) {
args.okCallback = null;
}
let windowParams = "chrome,titlebar,centerscreen,width=640,height=480";
@ -409,7 +478,8 @@ function NewMailAccountProvisioner(aMsgWindow, args) {
"chrome://messenger/content/newmailaccount/accountProvisioner.xhtml",
"AccountCreation",
windowParams,
args);
args
);
}
/**
@ -423,17 +493,21 @@ function NewMailAccountProvisioner(aMsgWindow, args) {
* @see msgOpenAccountWizard above for the previous implementation.
*/
function msgNewMailAccount(msgWindow, okCallback, extraData) {
if (!msgWindow)
if (!msgWindow) {
throw new Error("msgNewMailAccount must be given a msgWindow.");
}
let existingWindow = Services.wm.getMostRecentWindow("mail:autoconfig");
if (existingWindow) {
existingWindow.focus();
} else if (AppConstants.MOZ_APP_NAME == "thunderbird") {
// disabling modal for the time being, see 688273 REMOVEME
window.openDialog("chrome://messenger/content/accountcreation/emailWizard.xul",
"AccountSetup", "chrome,titlebar,centerscreen,resizable",
{ msgWindow, okCallback, extraData });
window.openDialog(
"chrome://messenger/content/accountcreation/emailWizard.xul",
"AccountSetup",
"chrome,titlebar,centerscreen,resizable",
{ msgWindow, okCallback, extraData }
);
}
/*

Просмотреть файл

@ -6,7 +6,7 @@
/* import-globals-from am-prefs.js */
/* import-globals-from amUtils.js */
var {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm");
var { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm");
function onLoad() {
parent.onPanelLoaded("am-addressing.xul");
@ -22,12 +22,15 @@ function onInitCompositionAndAddressing() {
}
function onEditDirectories() {
window.openDialog("chrome://messenger/content/addressbook/pref-editdirectories.xul",
"editDirectories", "chrome,modal=yes,resizable=no", null);
window.openDialog(
"chrome://messenger/content/addressbook/pref-editdirectories.xul",
"editDirectories",
"chrome,modal=yes,resizable=no",
null
);
}
function onPreInit(account, accountValues) {
}
function onPreInit(account, accountValues) {}
function LDAPenabling() {
onCheckItem("identity.directoryServer", ["directories"]);
@ -50,12 +53,22 @@ function quoteEnabling() {
* Open the Preferences dialog on the tab with Addressing options.
*/
function showGlobalAddressingPrefs() {
openPrefsFromAccountManager("paneCompose", "compositionAddressingCategory", null, "addressing_pane");
openPrefsFromAccountManager(
"paneCompose",
"compositionAddressingCategory",
null,
"addressing_pane"
);
}
/**
* Open the Preferences dialog on the tab with Composing options.
*/
function showGlobalComposingPrefs() {
openPrefsFromAccountManager("paneCompose", null, null, "composing_messages_pane");
openPrefsFromAccountManager(
"paneCompose",
null,
null,
"composing_messages_pane"
);
}

Просмотреть файл

@ -30,10 +30,12 @@ function onLoadArchiveOptions() {
* Save the archive settings to the current identity.
*/
function onAcceptArchiveOptions() {
gIdentity.archiveGranularity =
document.getElementById("archiveGranularity").selectedIndex;
gIdentity.archiveKeepFolderStructure =
document.getElementById("archiveKeepFolderStructure").checked;
gIdentity.archiveGranularity = document.getElementById(
"archiveGranularity"
).selectedIndex;
gIdentity.archiveKeepFolderStructure = document.getElementById(
"archiveKeepFolderStructure"
).checked;
}
/**
@ -42,9 +44,11 @@ function onAcceptArchiveOptions() {
function updateArchiveExample() {
let granularity = document.getElementById("archiveGranularity").selectedIndex;
let kfs = document.getElementById("archiveKeepFolderStructure").checked;
let hierarchy = [ document.getElementsByClassName("root"),
document.getElementsByClassName("year"),
document.getElementsByClassName("month") ];
let hierarchy = [
document.getElementsByClassName("root"),
document.getElementsByClassName("year"),
document.getElementsByClassName("month"),
];
// First, show/hide the appropriate levels in the hierarchy and turn the
// necessary items into containers.

Просмотреть файл

@ -6,19 +6,35 @@
/* import-globals-from am-prefs.js */
/* import-globals-from amUtils.js */
var {MailUtils} = ChromeUtils.import("resource:///modules/MailUtils.jsm");
var { MailUtils } = ChromeUtils.import("resource:///modules/MailUtils.jsm");
var gFccRadioElemChoice, gDraftsRadioElemChoice, gArchivesRadioElemChoice, gTmplRadioElemChoice;
var gFccRadioElemChoiceLocked, gDraftsRadioElemChoiceLocked, gArchivesRadioElemChoiceLocked, gTmplRadioElemChoiceLocked;
var gFccRadioElemChoice,
gDraftsRadioElemChoice,
gArchivesRadioElemChoice,
gTmplRadioElemChoice;
var gFccRadioElemChoiceLocked,
gDraftsRadioElemChoiceLocked,
gArchivesRadioElemChoiceLocked,
gTmplRadioElemChoiceLocked;
var gDefaultPickerMode = "1";
var gFccFolderWithDelim, gDraftsFolderWithDelim, gArchivesFolderWithDelim, gTemplatesFolderWithDelim;
var gFccFolderWithDelim,
gDraftsFolderWithDelim,
gArchivesFolderWithDelim,
gTemplatesFolderWithDelim;
var gAccount;
var gCurrentServerId;
function onPreInit(account, accountValues) {
gAccount = account;
var type = parent.getAccountValue(account, accountValues, "server", "type", null, false);
var type = parent.getAccountValue(
account,
accountValues,
"server",
"type",
null,
false
);
hideShowControls(type);
}
@ -28,35 +44,47 @@ function onPreInit(account, accountValues) {
*/
function onInit(aPageId, aServerId) {
gCurrentServerId = aServerId;
onInitCopiesAndFolders();
onInitCopiesAndFolders();
}
function onInitCopiesAndFolders() {
SetGlobalRadioElemChoices();
SetFolderDisplay(gFccRadioElemChoice, gFccRadioElemChoiceLocked,
"fcc",
"msgFccAccountPicker",
"identity.fccFolder",
"msgFccFolderPicker");
SetFolderDisplay(
gFccRadioElemChoice,
gFccRadioElemChoiceLocked,
"fcc",
"msgFccAccountPicker",
"identity.fccFolder",
"msgFccFolderPicker"
);
SetFolderDisplay(gArchivesRadioElemChoice, gArchivesRadioElemChoiceLocked,
"archive",
"msgArchivesAccountPicker",
"identity.archiveFolder",
"msgArchivesFolderPicker");
SetFolderDisplay(
gArchivesRadioElemChoice,
gArchivesRadioElemChoiceLocked,
"archive",
"msgArchivesAccountPicker",
"identity.archiveFolder",
"msgArchivesFolderPicker"
);
SetFolderDisplay(gDraftsRadioElemChoice, gDraftsRadioElemChoiceLocked,
"draft",
"msgDraftsAccountPicker",
"identity.draftFolder",
"msgDraftsFolderPicker");
SetFolderDisplay(
gDraftsRadioElemChoice,
gDraftsRadioElemChoiceLocked,
"draft",
"msgDraftsAccountPicker",
"identity.draftFolder",
"msgDraftsFolderPicker"
);
SetFolderDisplay(gTmplRadioElemChoice, gTmplRadioElemChoiceLocked,
"tmpl",
"msgStationeryAccountPicker",
"identity.stationeryFolder",
"msgStationeryFolderPicker");
SetFolderDisplay(
gTmplRadioElemChoice,
gTmplRadioElemChoiceLocked,
"tmpl",
"msgStationeryAccountPicker",
"identity.stationeryFolder",
"msgStationeryFolderPicker"
);
setupCcTextbox(true);
setupBccTextbox(true);
@ -68,25 +96,39 @@ function onInitCopiesAndFolders() {
// Initialize the picker mode choices (account/folder picker) into global vars
function SetGlobalRadioElemChoices() {
var pickerModeElement = document.getElementById("identity.fccFolderPickerMode");
var pickerModeElement = document.getElementById(
"identity.fccFolderPickerMode"
);
gFccRadioElemChoice = pickerModeElement.getAttribute("value");
gFccRadioElemChoiceLocked = pickerModeElement.getAttribute("disabled");
if (!gFccRadioElemChoice) gFccRadioElemChoice = gDefaultPickerMode;
if (!gFccRadioElemChoice) {
gFccRadioElemChoice = gDefaultPickerMode;
}
pickerModeElement = document.getElementById("identity.archivesFolderPickerMode");
pickerModeElement = document.getElementById(
"identity.archivesFolderPickerMode"
);
gArchivesRadioElemChoice = pickerModeElement.getAttribute("value");
gArchivesRadioElemChoiceLocked = pickerModeElement.getAttribute("disabled");
if (!gArchivesRadioElemChoice) gArchivesRadioElemChoice = gDefaultPickerMode;
if (!gArchivesRadioElemChoice) {
gArchivesRadioElemChoice = gDefaultPickerMode;
}
pickerModeElement = document.getElementById("identity.draftsFolderPickerMode");
pickerModeElement = document.getElementById(
"identity.draftsFolderPickerMode"
);
gDraftsRadioElemChoice = pickerModeElement.getAttribute("value");
gDraftsRadioElemChoiceLocked = pickerModeElement.getAttribute("disabled");
if (!gDraftsRadioElemChoice) gDraftsRadioElemChoice = gDefaultPickerMode;
if (!gDraftsRadioElemChoice) {
gDraftsRadioElemChoice = gDefaultPickerMode;
}
pickerModeElement = document.getElementById("identity.tmplFolderPickerMode");
gTmplRadioElemChoice = pickerModeElement.getAttribute("value");
gTmplRadioElemChoiceLocked = pickerModeElement.getAttribute("disabled");
if (!gTmplRadioElemChoice) gTmplRadioElemChoice = gDefaultPickerMode;
if (!gTmplRadioElemChoice) {
gTmplRadioElemChoice = gDefaultPickerMode;
}
}
/*
@ -95,13 +137,17 @@ function SetGlobalRadioElemChoices() {
* set to 1 i.e., Other picker displaying the folder value read from the
* preferences file.
*/
function SetFolderDisplay(pickerMode, disableMode,
radioElemPrefix,
accountPickerId,
folderPickedField,
folderPickerId) {
if (!pickerMode)
function SetFolderDisplay(
pickerMode,
disableMode,
radioElemPrefix,
accountPickerId,
folderPickedField,
folderPickerId
) {
if (!pickerMode) {
pickerMode = gDefaultPickerMode;
}
var selectAccountRadioId = radioElemPrefix + "_selectAccount";
var selectAccountRadioElem = document.getElementById(selectAccountRadioId);
@ -121,17 +167,17 @@ function SetFolderDisplay(pickerMode, disableMode,
InitFolderDisplay(msgFolder, folderPicker);
switch (pickerMode) {
case "0" :
case "0":
rg.selectedItem = selectAccountRadioElem;
SetPickerEnabling(accountPickerId, folderPickerId);
break;
case "1" :
case "1":
rg.selectedItem = selectFolderRadioElem;
SetPickerEnabling(folderPickerId, accountPickerId);
break;
default :
default:
dump("Error in setting initial folder display on pickers\n");
break;
}
@ -168,23 +214,23 @@ function noteSelectionChange(aGroup, aType, aEvent) {
var picker;
switch (radioGroup) {
case "doFcc" :
case "doFcc":
gFccRadioElemChoice = modeValue;
picker = document.getElementById("msgFcc" + aType + "Picker");
break;
case "messageArchives" :
case "messageArchives":
gArchivesRadioElemChoice = modeValue;
picker = document.getElementById("msgArchives" + aType + "Picker");
updateArchiveHierarchyButton(folder);
break;
case "messageDrafts" :
case "messageDrafts":
gDraftsRadioElemChoice = modeValue;
picker = document.getElementById("msgDrafts" + aType + "Picker");
break;
case "messageTemplates" :
case "messageTemplates":
gTmplRadioElemChoice = modeValue;
picker = document.getElementById("msgStationery" + aType + "Picker");
break;
@ -213,52 +259,64 @@ function onSave() {
}
function onSaveCopiesAndFolders() {
SaveFolderSettings(gFccRadioElemChoice,
"doFcc",
gFccFolderWithDelim,
"msgFccAccountPicker",
"msgFccFolderPicker",
"identity.fccFolder",
"identity.fccFolderPickerMode");
SaveFolderSettings(
gFccRadioElemChoice,
"doFcc",
gFccFolderWithDelim,
"msgFccAccountPicker",
"msgFccFolderPicker",
"identity.fccFolder",
"identity.fccFolderPickerMode"
);
SaveFolderSettings(gArchivesRadioElemChoice,
"messageArchives",
gArchivesFolderWithDelim,
"msgArchivesAccountPicker",
"msgArchivesFolderPicker",
"identity.archiveFolder",
"identity.archivesFolderPickerMode");
SaveFolderSettings(
gArchivesRadioElemChoice,
"messageArchives",
gArchivesFolderWithDelim,
"msgArchivesAccountPicker",
"msgArchivesFolderPicker",
"identity.archiveFolder",
"identity.archivesFolderPickerMode"
);
SaveFolderSettings(gDraftsRadioElemChoice,
"messageDrafts",
gDraftsFolderWithDelim,
"msgDraftsAccountPicker",
"msgDraftsFolderPicker",
"identity.draftFolder",
"identity.draftsFolderPickerMode");
SaveFolderSettings(
gDraftsRadioElemChoice,
"messageDrafts",
gDraftsFolderWithDelim,
"msgDraftsAccountPicker",
"msgDraftsFolderPicker",
"identity.draftFolder",
"identity.draftsFolderPickerMode"
);
SaveFolderSettings(gTmplRadioElemChoice,
"messageTemplates",
gTemplatesFolderWithDelim,
"msgStationeryAccountPicker",
"msgStationeryFolderPicker",
"identity.stationeryFolder",
"identity.tmplFolderPickerMode");
SaveFolderSettings(
gTmplRadioElemChoice,
"messageTemplates",
gTemplatesFolderWithDelim,
"msgStationeryAccountPicker",
"msgStationeryFolderPicker",
"identity.stationeryFolder",
"identity.tmplFolderPickerMode"
);
}
// Save folder settings and radio element choices
function SaveFolderSettings(radioElemChoice,
radioGroupId,
folderSuffix,
accountPickerId,
folderPickerId,
folderElementId,
folderPickerModeId) {
function SaveFolderSettings(
radioElemChoice,
radioGroupId,
folderSuffix,
accountPickerId,
folderPickerId,
folderElementId,
folderPickerModeId
) {
var formElement = document.getElementById(folderElementId);
var uri;
if (radioElemChoice == "0" ||
!document.getElementById(folderPickerId).value) {
if (
radioElemChoice == "0" ||
!document.getElementById(folderPickerId).value
) {
// Default or revert to default if no folder chosen.
radioElemChoice = "0";
uri = document.getElementById(accountPickerId).folder.URI;
@ -294,19 +352,21 @@ function setupFccItems() {
}
switch (gFccRadioElemChoice) {
case "0" :
if (!gFccRadioElemChoiceLocked)
SetPickerEnabling("msgFccAccountPicker", "msgFccFolderPicker");
case "0":
if (!gFccRadioElemChoiceLocked) {
SetPickerEnabling("msgFccAccountPicker", "msgFccFolderPicker");
}
SetRadioButtons("fcc_selectAccount", "fcc_selectFolder");
break;
case "1" :
if (!gFccRadioElemChoiceLocked)
SetPickerEnabling("msgFccFolderPicker", "msgFccAccountPicker");
case "1":
if (!gFccRadioElemChoiceLocked) {
SetPickerEnabling("msgFccFolderPicker", "msgFccAccountPicker");
}
SetRadioButtons("fcc_selectFolder", "fcc_selectAccount");
break;
default :
default:
dump("Error in setting Fcc elements.\n");
break;
}
@ -321,12 +381,15 @@ function setupCcTextbox(init) {
if (ccChecked) {
if (ccTextbox.value == "") {
ccTextbox.value = document.getElementById("identity.email").value;
if (!init)
ccTextbox.select();
ccTextbox.value = document.getElementById("identity.email").value;
if (!init) {
ccTextbox.select();
}
}
} else if ((ccTextbox.value == document.getElementById("identity.email").value) ||
(init && ccTextbox.getAttribute("value") == "")) {
} else if (
ccTextbox.value == document.getElementById("identity.email").value ||
(init && ccTextbox.getAttribute("value") == "")
) {
ccTextbox.value = "";
}
}
@ -340,12 +403,15 @@ function setupBccTextbox(init) {
if (bccChecked) {
if (bccTextbox.value == "") {
bccTextbox.value = document.getElementById("identity.email").value;
if (!init)
bccTextbox.value = document.getElementById("identity.email").value;
if (!init) {
bccTextbox.select();
}
}
} else if ((bccTextbox.value == document.getElementById("identity.email").value) ||
(init && bccTextbox.getAttribute("value") == "")) {
} else if (
bccTextbox.value == document.getElementById("identity.email").value ||
(init && bccTextbox.getAttribute("value") == "")
) {
bccTextbox.value = "";
}
}
@ -373,8 +439,9 @@ function setPickersState(enablePickerId, disablePickerId, event) {
case "archive_selectAccount":
case "archive_selectFolder":
gArchivesRadioElemChoice = radioElemValue;
updateArchiveHierarchyButton(document.getElementById(enablePickerId)
.folder);
updateArchiveHierarchyButton(
document.getElementById(enablePickerId).folder
);
break;
case "draft_selectAccount":
case "draft_selectFolder":
@ -404,10 +471,9 @@ function SetRadioButtons(selectPickerId, unselectPickerId) {
* @param archiveFolder the currently-selected folder to store archives in
*/
function updateArchiveHierarchyButton(archiveFolder) {
let isGmailImap = (archiveFolder.server.type == "imap" &&
archiveFolder.server.QueryInterface(
Ci.nsIImapIncomingServer)
.isGMailServer);
let isGmailImap =
archiveFolder.server.type == "imap" &&
archiveFolder.server.QueryInterface(Ci.nsIImapIncomingServer).isGMailServer;
document.getElementById("archiveHierarchyButton").disabled = isGmailImap;
}
@ -429,19 +495,29 @@ function setupArchiveItems() {
switch (gArchivesRadioElemChoice) {
case "0":
if (!gArchivesRadioElemChoiceLocked)
SetPickerEnabling("msgArchivesAccountPicker", "msgArchivesFolderPicker");
if (!gArchivesRadioElemChoiceLocked) {
SetPickerEnabling(
"msgArchivesAccountPicker",
"msgArchivesFolderPicker"
);
}
SetRadioButtons("archive_selectAccount", "archive_selectFolder");
updateArchiveHierarchyButton(document.getElementById(
"msgArchivesAccountPicker").folder);
updateArchiveHierarchyButton(
document.getElementById("msgArchivesAccountPicker").folder
);
break;
case "1":
if (!gArchivesRadioElemChoiceLocked)
SetPickerEnabling("msgArchivesFolderPicker", "msgArchivesAccountPicker");
if (!gArchivesRadioElemChoiceLocked) {
SetPickerEnabling(
"msgArchivesFolderPicker",
"msgArchivesAccountPicker"
);
}
SetRadioButtons("archive_selectFolder", "archive_selectAccount");
updateArchiveHierarchyButton(document.getElementById(
"msgArchivesFolderPicker").folder);
updateArchiveHierarchyButton(
document.getElementById("msgArchivesFolderPicker").folder
);
break;
default:
@ -455,8 +531,11 @@ function setupArchiveItems() {
function ChangeArchiveHierarchy() {
let identity = parent.gIdentity || parent.getCurrentAccount().defaultIdentity;
top.window.openDialog("chrome://messenger/content/am-archiveoptions.xul",
"", "centerscreen,chrome,modal,titlebar,resizable=yes",
identity);
top.window.openDialog(
"chrome://messenger/content/am-archiveoptions.xul",
"",
"centerscreen,chrome,modal,titlebar,resizable=yes",
identity
);
return true;
}

Просмотреть файл

@ -5,7 +5,7 @@
// This file is SeaMonkey-only.
/* globals openHelp */// suite/components/helpviewer/content/contextHelp.js
/* globals openHelp */ // suite/components/helpviewer/content/contextHelp.js
/**
* Key value pairs to derive the tag based on the page loaded.
@ -23,7 +23,8 @@ var pageTagPairs = {
"chrome://messenger/content/am-offline.xul": "mail-offline-accounts",
"chrome://messenger/content/am-smtp.xul": "mail_smtp",
"chrome://messenger/content/am-smime.xul": "mail_security_settings",
"chrome://messenger/content/am-serverwithnoidentities.xul": "mail_local_folders_settings",
"chrome://messenger/content/am-serverwithnoidentities.xul":
"mail_local_folders_settings",
"chrome://messenger/content/am-mdn.xul": "mail-account-receipts",
};
@ -34,7 +35,7 @@ function doHelpButton() {
var helpTag = pageTagPairs[pageSourceURI];
// If the help tag is generic or offline, check if there is a need to set tags per server type
if ((helpTag == "mail") || (helpTag == "mail-offline-accounts")) {
if (helpTag == "mail" || helpTag == "mail-offline-accounts") {
// Get server type, as we may need to set help tags per server type for some pages
var serverType = GetServerType();
@ -55,15 +56,16 @@ function doHelpButton() {
helpTag = "mail_offline_" + serverType;
break;
default :
default:
break;
}
}
if (helpTag)
if (helpTag) {
openHelp(helpTag);
else
} else {
openHelp("mail");
}
}
/**
@ -72,7 +74,8 @@ function doHelpButton() {
function GetServerType() {
var serverType = null;
var currentAccount = parent.getCurrentAccount();
if (currentAccount)
if (currentAccount) {
serverType = currentAccount.incomingServer.type;
}
return serverType;
}

Просмотреть файл

@ -3,34 +3,37 @@
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
var {Gloda} = ChromeUtils.import("resource:///modules/gloda/gloda.js");
var {fixIterator} = ChromeUtils.import("resource:///modules/iteratorUtils.jsm");
var {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm");
var { Gloda } = ChromeUtils.import("resource:///modules/gloda/gloda.js");
var { fixIterator } = ChromeUtils.import(
"resource:///modules/iteratorUtils.jsm"
);
var { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm");
var gIdentityListBox; // the root <listbox> node
var gIdentityListBox; // the root <listbox> node
var gAddButton;
var gEditButton;
var gSetDefaultButton;
var gDeleteButton;
var gAccount = null; // the account we are showing the identities for
var gAccount = null; // the account we are showing the identities for
document.addEventListener("dialogaccept", onOk);
document.addEventListener("dialogcancel", onOk);
function onLoad() {
gIdentityListBox = document.getElementById("identitiesList");
gAddButton = document.getElementById("cmd_add");
gEditButton = document.getElementById("cmd_edit");
gIdentityListBox = document.getElementById("identitiesList");
gAddButton = document.getElementById("cmd_add");
gEditButton = document.getElementById("cmd_edit");
gSetDefaultButton = document.getElementById("cmd_default");
gDeleteButton = document.getElementById("cmd_delete");
gDeleteButton = document.getElementById("cmd_delete");
// extract the account
gAccount = window.arguments[0].account;
var accountName = window.arguments[0].accountName;
document.title = document.getElementById("bundle_prefs")
.getFormattedString("identity-list-title", [accountName]);
document.title = document
.getElementById("bundle_prefs")
.getFormattedString("identity-list-title", [accountName]);
refreshIdentityList(0);
}
@ -42,8 +45,9 @@ function onLoad() {
*/
function refreshIdentityList(aSelectIndex) {
// Remove all children.
while (gIdentityListBox.hasChildNodes())
while (gIdentityListBox.hasChildNodes()) {
gIdentityListBox.lastChild.remove();
}
// Build the list from the identities array.
let identities = gAccount.identities;
@ -60,10 +64,11 @@ function refreshIdentityList(aSelectIndex) {
}
// Ensure one identity is always selected.
if (!aSelectIndex || aSelectIndex < 0)
if (!aSelectIndex || aSelectIndex < 0) {
aSelectIndex = 0;
else if (aSelectIndex >= gIdentityListBox.itemCount)
} else if (aSelectIndex >= gIdentityListBox.itemCount) {
aSelectIndex = gIdentityListBox.itemCount - 1;
}
// This also fires the onselect event, which in turn calls updateButtons().
gIdentityListBox.selectedIndex = aSelectIndex;
@ -77,32 +82,40 @@ function refreshIdentityList(aSelectIndex) {
function openIdentityEditor(identity) {
let args = { identity, account: gAccount, result: false };
let indexToSelect = identity ? gIdentityListBox.selectedIndex :
gIdentityListBox.itemCount;
let indexToSelect = identity
? gIdentityListBox.selectedIndex
: gIdentityListBox.itemCount;
window.openDialog("am-identity-edit.xul", "",
"chrome,modal,resizable,centerscreen", args);
window.openDialog(
"am-identity-edit.xul",
"",
"chrome,modal,resizable,centerscreen",
args
);
if (args.result)
if (args.result) {
refreshIdentityList(indexToSelect);
}
}
function getSelectedIdentity() {
if (gIdentityListBox.selectedItems.length != 1)
if (gIdentityListBox.selectedItems.length != 1) {
return null;
}
var identityKey = gIdentityListBox.selectedItems[0].getAttribute("key");
let identities = gAccount.identities;
for (let identity of fixIterator(identities, Ci.nsIMsgIdentity)) {
if (identity.valid && identity.key == identityKey)
if (identity.valid && identity.key == identityKey) {
return identity;
}
}
return null; // no identity found
}
function onEdit(event) {
var id = (event.target.localName == "listbox") ? null : getSelectedIdentity();
var id = event.target.localName == "listbox" ? null : getSelectedIdentity();
openIdentityEditor(id);
}
@ -111,7 +124,10 @@ function onEdit(event) {
*/
function updateButtons() {
// In this listbox there should always be one item selected.
if (gIdentityListBox.selectedItems.length != 1 || gIdentityListBox.itemCount == 0) {
if (
gIdentityListBox.selectedItems.length != 1 ||
gIdentityListBox.itemCount == 0
) {
// But in case this is not met (e.g. there is no identity for some reason,
// or the list is being rebuilt), disable all buttons.
gEditButton.setAttribute("disabled", "true");
@ -121,19 +137,27 @@ function updateButtons() {
}
gEditButton.setAttribute("disabled", "false");
gDeleteButton.setAttribute("disabled", (gIdentityListBox.itemCount <= 1) ? "true" : "false");
gSetDefaultButton.setAttribute("disabled", (gIdentityListBox.selectedIndex == 0) ? "true" : "false");
gDeleteButton.setAttribute(
"disabled",
gIdentityListBox.itemCount <= 1 ? "true" : "false"
);
gSetDefaultButton.setAttribute(
"disabled",
gIdentityListBox.selectedIndex == 0 ? "true" : "false"
);
// The Add command is always enabled.
}
function onSetDefault(event) {
let identity = getSelectedIdentity();
if (!identity)
if (!identity) {
return;
}
// If the first identity is selected, there is nothing to do.
if (gIdentityListBox.selectedIndex == 0)
if (gIdentityListBox.selectedIndex == 0) {
return;
}
gAccount.defaultIdentity = identity;
// Rebuilt the identity list and select the moved identity again.
@ -143,24 +167,40 @@ function onSetDefault(event) {
}
function onDelete(event) {
if (gIdentityListBox.itemCount <= 1) // don't support deleting the last identity
if (gIdentityListBox.itemCount <= 1) {
// don't support deleting the last identity
return;
}
// get delete confirmation
let selectedIdentity = getSelectedIdentity();
let prefsBundle = document.getElementById("bundle_prefs");
let confirmTitle = prefsBundle.getFormattedString("identity-delete-confirm-title",
[window.arguments[0].accountName]);
let confirmText = prefsBundle.getFormattedString("identity-delete-confirm",
[selectedIdentity.identityName]);
let confirmTitle = prefsBundle.getFormattedString(
"identity-delete-confirm-title",
[window.arguments[0].accountName]
);
let confirmText = prefsBundle.getFormattedString("identity-delete-confirm", [
selectedIdentity.identityName,
]);
let confirmButton = prefsBundle.getString("identity-delete-confirm-button");
if (Services.prompt.confirmEx(window, confirmTitle, confirmText,
(Services.prompt.BUTTON_POS_0 * Services.prompt.BUTTON_TITLE_IS_STRING) +
(Services.prompt.BUTTON_POS_1 * Services.prompt.BUTTON_TITLE_CANCEL),
confirmButton, null, null, null, {}))
if (
Services.prompt.confirmEx(
window,
confirmTitle,
confirmText,
Services.prompt.BUTTON_POS_0 * Services.prompt.BUTTON_TITLE_IS_STRING +
Services.prompt.BUTTON_POS_1 * Services.prompt.BUTTON_TITLE_CANCEL,
confirmButton,
null,
null,
null,
{}
)
) {
return;
}
let selectedItemIndex = gIdentityListBox.selectedIndex;

Просмотреть файл

@ -6,11 +6,13 @@
/* import-globals-from am-addressing.js */
/* import-globals-from am-copies.js */
var {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm");
var {MailServices} = ChromeUtils.import("resource:///modules/MailServices.jsm");
var { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm");
var { MailServices } = ChromeUtils.import(
"resource:///modules/MailServices.jsm"
);
var gIdentity = null; // the identity we are editing (may be null for a new identity)
var gAccount = null; // the account the identity is (or will be) associated with
var gIdentity = null; // the identity we are editing (may be null for a new identity)
var gAccount = null; // the account the identity is (or will be) associated with
document.addEventListener("dialogaccept", onOk);
@ -23,7 +25,7 @@ function onLoadIdentityProperties() {
// Make the dialog the same height and 90% of the width of the main Account
// manager page when the Account manager is not maximized.
let accountDialog = Services.wm.getMostRecentWindow("mailnews:accountmanager")
.document;
.document;
if (accountDialog.documentElement.getAttribute("sizemode") != "maximized") {
document.getElementById("identityDialog").style.width =
accountDialog.getElementById("accountManager").clientWidth * 0.9 + "px";
@ -33,8 +35,9 @@ function onLoadIdentityProperties() {
if (gIdentity) {
let listName = gIdentity.identityName;
document.title = prefBundle
.getFormattedString("identityDialogTitleEdit", [listName]);
document.title = prefBundle.getFormattedString("identityDialogTitleEdit", [
listName,
]);
} else {
document.title = prefBundle.getString("identityDialogTitleAdd");
}
@ -60,22 +63,31 @@ function initIdentityValues(identity) {
document.getElementById("identity.fullName").value = identity.fullName;
document.getElementById("identity.email").value = identity.email;
document.getElementById("identity.replyTo").value = identity.replyTo;
document.getElementById("identity.organization").value = identity.organization;
document.getElementById("identity.attachSignature").checked = identity.attachSignature;
document.getElementById("identity.htmlSigText").value = identity.htmlSigText;
document.getElementById("identity.htmlSigFormat").checked = identity.htmlSigFormat;
document.getElementById("identity.organization").value =
identity.organization;
document.getElementById("identity.attachSignature").checked =
identity.attachSignature;
document.getElementById("identity.htmlSigText").value =
identity.htmlSigText;
document.getElementById("identity.htmlSigFormat").checked =
identity.htmlSigFormat;
if (identity.signature)
document.getElementById("identity.signature").value = identity.signature.path;
if (identity.signature) {
document.getElementById("identity.signature").value =
identity.signature.path;
}
document.getElementById("identity.attachVCard").checked = identity.attachVCard;
document.getElementById("identity.escapedVCard").value = identity.escapedVCard;
document.getElementById("identity.attachVCard").checked =
identity.attachVCard;
document.getElementById("identity.escapedVCard").value =
identity.escapedVCard;
initSmtpServer(identity.smtpServerKey);
// This field does not exist for the default identity shown in the am-main.xul pane.
let idLabel = document.getElementById("identity.label");
if (idLabel)
if (idLabel) {
idLabel.value = identity.label;
}
} else {
// We're adding an identity, use the best default we have.
initSmtpServer(gAccount.defaultIdentity.smtpServerKey);
@ -88,24 +100,52 @@ function initCopiesAndFolder(identity) {
// if we are editing an existing identity, use it...otherwise copy our values from the default identity
var copiesAndFoldersIdentity = identity ? identity : gAccount.defaultIdentity;
document.getElementById("identity.fccFolder").value = copiesAndFoldersIdentity.fccFolder;
document.getElementById("identity.draftFolder").value = copiesAndFoldersIdentity.draftFolder;
document.getElementById("identity.archiveFolder").value = copiesAndFoldersIdentity.archiveFolder;
document.getElementById("identity.stationeryFolder").value = copiesAndFoldersIdentity.stationeryFolder;
document.getElementById("identity.fccFolder").value =
copiesAndFoldersIdentity.fccFolder;
document.getElementById("identity.draftFolder").value =
copiesAndFoldersIdentity.draftFolder;
document.getElementById("identity.archiveFolder").value =
copiesAndFoldersIdentity.archiveFolder;
document.getElementById("identity.stationeryFolder").value =
copiesAndFoldersIdentity.stationeryFolder;
document.getElementById("identity.fccFolderPickerMode").value = copiesAndFoldersIdentity.fccFolderPickerMode ? copiesAndFoldersIdentity.fccFolderPickerMode : 0;
document.getElementById("identity.draftsFolderPickerMode").value = copiesAndFoldersIdentity.draftsFolderPickerMode ? copiesAndFoldersIdentity.draftsFolderPickerMode : 0;
document.getElementById("identity.archivesFolderPickerMode").value = copiesAndFoldersIdentity.archivesFolderPickerMode ? copiesAndFoldersIdentity.archivesFolderPickerMode : 0;
document.getElementById("identity.tmplFolderPickerMode").value = copiesAndFoldersIdentity.tmplFolderPickerMode ? copiesAndFoldersIdentity.tmplFolderPickerMode : 0;
document.getElementById(
"identity.fccFolderPickerMode"
).value = copiesAndFoldersIdentity.fccFolderPickerMode
? copiesAndFoldersIdentity.fccFolderPickerMode
: 0;
document.getElementById(
"identity.draftsFolderPickerMode"
).value = copiesAndFoldersIdentity.draftsFolderPickerMode
? copiesAndFoldersIdentity.draftsFolderPickerMode
: 0;
document.getElementById(
"identity.archivesFolderPickerMode"
).value = copiesAndFoldersIdentity.archivesFolderPickerMode
? copiesAndFoldersIdentity.archivesFolderPickerMode
: 0;
document.getElementById(
"identity.tmplFolderPickerMode"
).value = copiesAndFoldersIdentity.tmplFolderPickerMode
? copiesAndFoldersIdentity.tmplFolderPickerMode
: 0;
document.getElementById("identity.doCc").checked = copiesAndFoldersIdentity.doCc;
document.getElementById("identity.doCcList").value = copiesAndFoldersIdentity.doCcList;
document.getElementById("identity.doBcc").checked = copiesAndFoldersIdentity.doBcc;
document.getElementById("identity.doBccList").value = copiesAndFoldersIdentity.doBccList;
document.getElementById("identity.doFcc").checked = copiesAndFoldersIdentity.doFcc;
document.getElementById("identity.fccReplyFollowsParent").checked = copiesAndFoldersIdentity.fccReplyFollowsParent;
document.getElementById("identity.showSaveMsgDlg").checked = copiesAndFoldersIdentity.showSaveMsgDlg;
document.getElementById("identity.archiveEnabled").checked = copiesAndFoldersIdentity.archiveEnabled;
document.getElementById("identity.doCc").checked =
copiesAndFoldersIdentity.doCc;
document.getElementById("identity.doCcList").value =
copiesAndFoldersIdentity.doCcList;
document.getElementById("identity.doBcc").checked =
copiesAndFoldersIdentity.doBcc;
document.getElementById("identity.doBccList").value =
copiesAndFoldersIdentity.doBccList;
document.getElementById("identity.doFcc").checked =
copiesAndFoldersIdentity.doFcc;
document.getElementById("identity.fccReplyFollowsParent").checked =
copiesAndFoldersIdentity.fccReplyFollowsParent;
document.getElementById("identity.showSaveMsgDlg").checked =
copiesAndFoldersIdentity.showSaveMsgDlg;
document.getElementById("identity.archiveEnabled").checked =
copiesAndFoldersIdentity.archiveEnabled;
onInitCopiesAndFolders(); // am-copies.js method
}
@ -114,18 +154,30 @@ function initCompositionAndAddressing(identity) {
// if we are editing an existing identity, use it...otherwise copy our values from the default identity
var addressingIdentity = identity ? identity : gAccount.defaultIdentity;
document.getElementById("identity.directoryServer").value = addressingIdentity.directoryServer;
document.getElementById("identity.overrideGlobal_Pref").value = addressingIdentity.overrideGlobalPref;
let autoCompleteElement = document.getElementById("identity.autocompleteToMyDomain");
if (autoCompleteElement) // Thunderbird does not have this element.
document.getElementById("identity.directoryServer").value =
addressingIdentity.directoryServer;
document.getElementById("identity.overrideGlobal_Pref").value =
addressingIdentity.overrideGlobalPref;
let autoCompleteElement = document.getElementById(
"identity.autocompleteToMyDomain"
);
if (autoCompleteElement) {
// Thunderbird does not have this element.
autoCompleteElement.checked = addressingIdentity.autocompleteToMyDomain;
}
document.getElementById("identity.composeHtml").checked = addressingIdentity.composeHtml;
document.getElementById("identity.autoQuote").checked = addressingIdentity.autoQuote;
document.getElementById("identity.replyOnTop").value = addressingIdentity.replyOnTop;
document.getElementById("identity.sig_bottom").value = addressingIdentity.sigBottom;
document.getElementById("identity.sig_on_reply").checked = addressingIdentity.sigOnReply;
document.getElementById("identity.sig_on_fwd").checked = addressingIdentity.sigOnForward;
document.getElementById("identity.composeHtml").checked =
addressingIdentity.composeHtml;
document.getElementById("identity.autoQuote").checked =
addressingIdentity.autoQuote;
document.getElementById("identity.replyOnTop").value =
addressingIdentity.replyOnTop;
document.getElementById("identity.sig_bottom").value =
addressingIdentity.sigBottom;
document.getElementById("identity.sig_on_reply").checked =
addressingIdentity.sigOnReply;
document.getElementById("identity.sig_on_fwd").checked =
addressingIdentity.sigOnForward;
onInitCompositionAndAddressing(); // am-addressing.js method
}
@ -174,8 +226,11 @@ function validEmailAddress() {
var prefBundle = document.getElementById("bundle_prefs");
Services.prompt.alert(window, prefBundle.getString("identity-edit-req-title"),
prefBundle.getString("identity-edit-req"));
Services.prompt.alert(
window,
prefBundle.getString("identity-edit-req-title"),
prefBundle.getString("identity-edit-req")
);
return false;
}
@ -185,30 +240,46 @@ function validEmailAddress() {
function saveIdentitySettings(identity) {
if (identity) {
let idLabel = document.getElementById("identity.label");
if (idLabel)
if (idLabel) {
identity.label = idLabel.value;
}
identity.fullName = document.getElementById("identity.fullName").value;
identity.email = document.getElementById("identity.email").value;
identity.replyTo = document.getElementById("identity.replyTo").value;
identity.organization = document.getElementById("identity.organization").value;
identity.attachSignature = document.getElementById("identity.attachSignature").checked;
identity.htmlSigText = document.getElementById("identity.htmlSigText").value;
identity.htmlSigFormat = document.getElementById("identity.htmlSigFormat").checked;
identity.organization = document.getElementById(
"identity.organization"
).value;
identity.attachSignature = document.getElementById(
"identity.attachSignature"
).checked;
identity.htmlSigText = document.getElementById(
"identity.htmlSigText"
).value;
identity.htmlSigFormat = document.getElementById(
"identity.htmlSigFormat"
).checked;
identity.attachVCard = document.getElementById("identity.attachVCard").checked;
identity.escapedVCard = document.getElementById("identity.escapedVCard").value;
identity.smtpServerKey = document.getElementById("identity.smtpServerKey").value;
identity.attachVCard = document.getElementById(
"identity.attachVCard"
).checked;
identity.escapedVCard = document.getElementById(
"identity.escapedVCard"
).value;
identity.smtpServerKey = document.getElementById(
"identity.smtpServerKey"
).value;
let attachSignaturePath = document.getElementById("identity.signature").value;
let attachSignaturePath = document.getElementById("identity.signature")
.value;
identity.signature = null; // this is important so we don't accidentally inherit the default
if (attachSignaturePath) {
// convert signature path back into a nsIFile
var sfile = Cc["@mozilla.org/file/local;1"]
.createInstance(Ci.nsIFile);
var sfile = Cc["@mozilla.org/file/local;1"].createInstance(Ci.nsIFile);
sfile.initWithPath(attachSignaturePath);
if (sfile.exists())
if (sfile.exists()) {
identity.signature = sfile;
}
}
}
}
@ -216,43 +287,74 @@ function saveIdentitySettings(identity) {
function saveCopiesAndFolderSettings(identity) {
onSaveCopiesAndFolders(); // am-copies.js routine
identity.fccFolder = document.getElementById("identity.fccFolder").value;
identity.fccFolder = document.getElementById("identity.fccFolder").value;
identity.draftFolder = document.getElementById("identity.draftFolder").value;
identity.archiveFolder = document.getElementById("identity.archiveFolder").value;
identity.stationeryFolder = document.getElementById("identity.stationeryFolder").value;
identity.fccFolderPickerMode = document.getElementById("identity.fccFolderPickerMode").value;
identity.draftsFolderPickerMode = document.getElementById("identity.draftsFolderPickerMode").value;
identity.archivesFolderPickerMode = document.getElementById("identity.archivesFolderPickerMode").value;
identity.tmplFolderPickerMode = document.getElementById("identity.tmplFolderPickerMode").value;
identity.archiveFolder = document.getElementById(
"identity.archiveFolder"
).value;
identity.stationeryFolder = document.getElementById(
"identity.stationeryFolder"
).value;
identity.fccFolderPickerMode = document.getElementById(
"identity.fccFolderPickerMode"
).value;
identity.draftsFolderPickerMode = document.getElementById(
"identity.draftsFolderPickerMode"
).value;
identity.archivesFolderPickerMode = document.getElementById(
"identity.archivesFolderPickerMode"
).value;
identity.tmplFolderPickerMode = document.getElementById(
"identity.tmplFolderPickerMode"
).value;
identity.doCc = document.getElementById("identity.doCc").checked;
identity.doCcList = document.getElementById("identity.doCcList").value;
identity.doBcc = document.getElementById("identity.doBcc").checked;
identity.doBccList = document.getElementById("identity.doBccList").value;
identity.doFcc = document.getElementById("identity.doFcc").checked;
identity.fccReplyFollowsParent = document.getElementById("identity.fccReplyFollowsParent").checked;
identity.showSaveMsgDlg = document.getElementById("identity.showSaveMsgDlg").checked;
identity.archiveEnabled = document.getElementById("identity.archiveEnabled").checked;
identity.fccReplyFollowsParent = document.getElementById(
"identity.fccReplyFollowsParent"
).checked;
identity.showSaveMsgDlg = document.getElementById(
"identity.showSaveMsgDlg"
).checked;
identity.archiveEnabled = document.getElementById(
"identity.archiveEnabled"
).checked;
}
function saveAddressingAndCompositionSettings(identity) {
identity.directoryServer = document.getElementById("identity.directoryServer").value;
identity.overrideGlobalPref = document.getElementById("identity.overrideGlobal_Pref").value == "true";
let autoCompleteElement = document.getElementById("identity.autocompleteToMyDomain");
if (autoCompleteElement) // Thunderbird does not have this element.
identity.directoryServer = document.getElementById(
"identity.directoryServer"
).value;
identity.overrideGlobalPref =
document.getElementById("identity.overrideGlobal_Pref").value == "true";
let autoCompleteElement = document.getElementById(
"identity.autocompleteToMyDomain"
);
if (autoCompleteElement) {
// Thunderbird does not have this element.
identity.autocompleteToMyDomain = autoCompleteElement.checked;
identity.composeHtml = document.getElementById("identity.composeHtml").checked;
}
identity.composeHtml = document.getElementById(
"identity.composeHtml"
).checked;
identity.autoQuote = document.getElementById("identity.autoQuote").checked;
identity.replyOnTop = document.getElementById("identity.replyOnTop").value;
identity.sigBottom = document.getElementById("identity.sig_bottom").value == "true";
identity.sigOnReply = document.getElementById("identity.sig_on_reply").checked;
identity.sigOnForward = document.getElementById("identity.sig_on_fwd").checked;
identity.sigBottom =
document.getElementById("identity.sig_bottom").value == "true";
identity.sigOnReply = document.getElementById(
"identity.sig_on_reply"
).checked;
identity.sigOnForward = document.getElementById(
"identity.sig_on_fwd"
).checked;
}
function selectFile() {
const nsIFilePicker = Ci.nsIFilePicker;
var fp = Cc["@mozilla.org/filepicker;1"]
.createInstance(nsIFilePicker);
var fp = Cc["@mozilla.org/filepicker;1"].createInstance(nsIFilePicker);
var prefBundle = document.getElementById("bundle_prefs");
var title = prefBundle.getString("choosefile");
@ -263,8 +365,9 @@ function selectFile() {
// We can set that to be the initial folder so that users
// can maintain their signatures better.
var sigFolder = GetSigFolder();
if (sigFolder)
fp.displayDirectory = sigFolder;
if (sigFolder) {
fp.displayDirectory = sigFolder;
}
fp.open(rv => {
if (rv != nsIFilePicker.returnOK || !fp.file) {
@ -285,11 +388,12 @@ function GetSigFolder() {
signatureFile = signatureFile.QueryInterface(Ci.nsIFile);
sigFolder = signatureFile.parent;
if (!sigFolder.exists())
sigFolder = null;
if (!sigFolder.exists()) {
sigFolder = null;
}
}
} catch (ex) {
dump("failed to get signature folder..\n");
dump("failed to get signature folder..\n");
}
return sigFolder;
}
@ -316,15 +420,17 @@ function setupSignatureItems() {
htmlSigFormat.removeAttribute("disabled");
}
if (checked && !getAccountValueIsLocked(signature))
if (checked && !getAccountValueIsLocked(signature)) {
signature.removeAttribute("disabled");
else
} else {
signature.setAttribute("disabled", "true");
}
if (checked && !getAccountValueIsLocked(browse))
if (checked && !getAccountValueIsLocked(browse)) {
browse.removeAttribute("disabled");
else
} else {
browse.setAttribute("disabled", "true");
}
}
function editVCardCallback(escapedVCardStr) {
@ -336,15 +442,17 @@ function editVCard() {
var escapedVCard = document.getElementById("identity.escapedVCard");
// read vCard hidden value from UI
window.openDialog("chrome://messenger/content/addressbook/abNewCardDialog.xul",
"",
"chrome,modal,resizable=no,centerscreen",
{
escapedVCardStr: escapedVCard.value,
okCallback: editVCardCallback,
titleProperty: "editVCardTitle",
hideABPicker: true,
});
window.openDialog(
"chrome://messenger/content/addressbook/abNewCardDialog.xul",
"",
"chrome,modal,resizable=no,centerscreen",
{
escapedVCardStr: escapedVCard.value,
okCallback: editVCardCallback,
titleProperty: "editVCardTitle",
hideABPicker: true,
}
);
}
function getAccountForFolderPickerState() {
@ -361,23 +469,29 @@ function loadSMTPServerList() {
let currentValue = smtpServerList.value;
var smtpPopup = smtpServerList.menupopup;
while (smtpPopup.lastChild.nodeName != "menuseparator")
while (smtpPopup.lastChild.nodeName != "menuseparator") {
smtpPopup.lastChild.remove();
}
while (servers.hasMoreElements()) {
var server = servers.getNext();
if (server instanceof Ci.nsISmtpServer) {
var serverName = "";
if (server.description)
if (server.description) {
serverName = server.description + " - ";
else if (server.username)
} else if (server.username) {
serverName = server.username + " - ";
}
serverName += server.hostname;
if (defaultServer.key == server.key)
serverName += " " + document.getElementById("bundle_messenger")
.getString("defaultServerTag");
if (defaultServer.key == server.key) {
serverName +=
" " +
document
.getElementById("bundle_messenger")
.getString("defaultServerTag");
}
smtpServerList.appendItem(serverName, server.key);
}
@ -391,10 +505,13 @@ function loadSMTPServerList() {
*/
function editCurrentSMTP() {
let smtpKey = document.getElementById("identity.smtpServerKey").value;
let server = (smtpKey === "") ? MailServices.smtp.defaultServer :
MailServices.smtp.getServerByKey(smtpKey);
let server =
smtpKey === ""
? MailServices.smtp.defaultServer
: MailServices.smtp.getServerByKey(smtpKey);
let args = editSMTPServer(server);
if (args.result)
if (args.result) {
loadSMTPServerList();
}
}

Просмотреть файл

@ -6,27 +6,37 @@
/* import-globals-from am-prefs.js */
/* import-globals-from amUtils.js */
var {MailServices} = ChromeUtils.import("resource:///modules/MailServices.jsm");
var {fixIterator} = ChromeUtils.import("resource:///modules/iteratorUtils.jsm");
var {MailUtils} = ChromeUtils.import("resource:///modules/MailUtils.jsm");
var { MailServices } = ChromeUtils.import(
"resource:///modules/MailServices.jsm"
);
var { fixIterator } = ChromeUtils.import(
"resource:///modules/iteratorUtils.jsm"
);
var { MailUtils } = ChromeUtils.import("resource:///modules/MailUtils.jsm");
var gDeferredToAccount = "";
function onInit(aPageId, aServerId) {
// manually adjust several pref UI elements
document.getElementById("server.spamLevel.visible").setAttribute("checked",
document.getElementById("server.spamLevel").value > 0);
document
.getElementById("server.spamLevel.visible")
.setAttribute(
"checked",
document.getElementById("server.spamLevel").value > 0
);
let deferredToURI = null;
if (gDeferredToAccount)
deferredToURI = MailServices.accounts
.getAccount(gDeferredToAccount)
.incomingServer.serverURI;
if (gDeferredToAccount) {
deferredToURI = MailServices.accounts.getAccount(gDeferredToAccount)
.incomingServer.serverURI;
}
let spamActionTargetAccountElement =
document.getElementById("server.spamActionTargetAccount");
let spamActionTargetFolderElement =
document.getElementById("server.spamActionTargetFolder");
let spamActionTargetAccountElement = document.getElementById(
"server.spamActionTargetAccount"
);
let spamActionTargetFolderElement = document.getElementById(
"server.spamActionTargetFolder"
);
let spamActionTargetAccount = spamActionTargetAccountElement.value;
let spamActionTargetFolder = spamActionTargetFolderElement.value;
@ -35,13 +45,18 @@ function onInit(aPageId, aServerId) {
let moveOnSpamValue = moveOnSpamCheckbox.checked;
// Check if there are any invalid junk targets and fix them.
[ spamActionTargetAccount, spamActionTargetFolder, moveOnSpamValue ] =
sanitizeJunkTargets(spamActionTargetAccount,
spamActionTargetFolder,
deferredToURI || aServerId,
document.getElementById("server.moveTargetMode").value,
MailUtils.getOrCreateFolder(aServerId).server.spamSettings,
moveOnSpamValue);
[
spamActionTargetAccount,
spamActionTargetFolder,
moveOnSpamValue,
] = sanitizeJunkTargets(
spamActionTargetAccount,
spamActionTargetFolder,
deferredToURI || aServerId,
document.getElementById("server.moveTargetMode").value,
MailUtils.getOrCreateFolder(aServerId).server.spamSettings,
moveOnSpamValue
);
spamActionTargetAccountElement.value = spamActionTargetAccount;
spamActionTargetFolderElement.value = spamActionTargetFolder;
@ -54,8 +69,11 @@ function onInit(aPageId, aServerId) {
document.getElementById("actionFolderPopup").selectFolder(folder);
var currentArray = [];
if (document.getElementById("server.useWhiteList").checked)
currentArray = document.getElementById("server.whiteListAbURI").value.split(" ");
if (document.getElementById("server.useWhiteList").checked) {
currentArray = document
.getElementById("server.whiteListAbURI")
.value.split(" ");
}
// set up the whitelist UI
var wList = document.getElementById("whiteListAbURI");
@ -66,11 +84,11 @@ function onInit(aPageId, aServerId) {
// Populate the listbox with address books
let abItems = [];
for (let ab of fixIterator(MailServices.ab.directories,
Ci.nsIAbDirectory)) {
for (let ab of fixIterator(MailServices.ab.directories, Ci.nsIAbDirectory)) {
// We skip mailing lists and remote address books.
if (ab.isMailList || ab.isRemote)
if (ab.isMailList || ab.isRemote) {
continue;
}
abItems.push({ label: ab.dirName, URI: ab.URI });
}
@ -98,10 +116,12 @@ function onInit(aPageId, aServerId) {
// set up trusted IP headers
var serverFilterList = document.getElementById("useServerFilterList");
serverFilterList.value =
document.getElementById("server.serverFilterName").value;
if (!serverFilterList.selectedItem)
serverFilterList.value = document.getElementById(
"server.serverFilterName"
).value;
if (!serverFilterList.selectedItem) {
serverFilterList.selectedIndex = 0;
}
// enable or disable the useServerFilter checkbox
onCheckItem("useServerFilterList", ["server.useServerFilter"]);
@ -110,10 +130,25 @@ function onInit(aPageId, aServerId) {
}
function onPreInit(account, accountValues) {
if (top.getAccountValue(account, accountValues, "server", "type", null, false) == "pop3")
gDeferredToAccount = top.getAccountValue(account, accountValues,
"pop3", "deferredToAccount",
null, false);
if (
top.getAccountValue(
account,
accountValues,
"server",
"type",
null,
false
) == "pop3"
) {
gDeferredToAccount = top.getAccountValue(
account,
accountValues,
"pop3",
"deferredToAccount",
null,
false
);
}
buildServerFilterMenuList();
}
@ -134,8 +169,9 @@ function updateSpamLevel(aValue) {
* our hidden wsm element.
*/
function onServerFilterListChange() {
document.getElementById("server.serverFilterName").value =
document.getElementById("useServerFilterList").value;
document.getElementById(
"server.serverFilterName"
).value = document.getElementById("useServerFilterList").value;
}
/**
@ -166,8 +202,9 @@ function updateJunkTargetsAndRetention() {
onCheckItem("server.moveTargetMode", ["server.moveOnSpam"]);
updateJunkTargets();
onCheckItem("server.purgeSpam", ["server.moveOnSpam"]);
document.getElementById("purgeLabel").disabled =
document.getElementById("server.purgeSpam").disabled;
document.getElementById("purgeLabel").disabled = document.getElementById(
"server.purgeSpam"
).disabled;
updateJunkRetention();
}
@ -184,7 +221,10 @@ function updateJunkTargets() {
* of the controlling checkbox.
*/
function updateJunkRetention() {
onCheckItem("server.purgeSpamInterval", ["server.purgeSpam", "server.moveOnSpam"]);
onCheckItem("server.purgeSpamInterval", [
"server.purgeSpam",
"server.moveOnSpam",
]);
}
function onSave() {
@ -210,8 +250,10 @@ function onSaveWhiteList() {
}
}
var wlValue = wlArray.join(" ");
document.getElementById("server.whiteListAbURI").setAttribute("value", wlValue);
document.getElementById("server.useWhiteList").checked = (wlValue != "");
document
.getElementById("server.whiteListAbURI")
.setAttribute("value", wlValue);
document.getElementById("server.useWhiteList").checked = wlValue != "";
}
/**
@ -236,15 +278,20 @@ function buildServerFilterMenuList() {
ispHeaderList.removeAllItems();
// Now walk through the isp directories looking for sfd files.
let ispDirectories = Services.dirsvc.get(KEY_ISP_DIRECTORY_LIST,
Ci.nsISimpleEnumerator);
let ispDirectories = Services.dirsvc.get(
KEY_ISP_DIRECTORY_LIST,
Ci.nsISimpleEnumerator
);
let menuEntries = [];
while (ispDirectories.hasMoreElements()) {
let ispDirectory = ispDirectories.getNext()
.QueryInterface(Ci.nsIFile);
if (ispDirectory)
menuEntries.push.apply(menuEntries, buildServerFilterListFromDir(ispDirectory, menuEntries));
let ispDirectory = ispDirectories.getNext().QueryInterface(Ci.nsIFile);
if (ispDirectory) {
menuEntries.push.apply(
menuEntries,
buildServerFilterListFromDir(ispDirectory, menuEntries)
);
}
}
menuEntries.sort((a, b) => a.localeCompare(b));
@ -265,8 +312,7 @@ function buildServerFilterListFromDir(aDir, aExistingEntries) {
let newEntries = [];
// Now iterate over each file in the directory looking for .sfd files.
const kSuffix = ".sfd";
let entries = aDir.directoryEntries
.QueryInterface(Ci.nsIDirectoryEnumerator);
let entries = aDir.directoryEntries.QueryInterface(Ci.nsIDirectoryEnumerator);
while (entries.hasMoreElements()) {
let entry = entries.nextFile;
@ -274,8 +320,9 @@ function buildServerFilterListFromDir(aDir, aExistingEntries) {
if (entry.isFile() && entry.leafName.endsWith(kSuffix)) {
let fileName = entry.leafName.slice(0, -kSuffix.length);
// If we've already added an item with this name, then don't add it again.
if (!aExistingEntries.includes(fileName))
if (!aExistingEntries.includes(fileName)) {
newEntries.push(fileName);
}
}
}
return newEntries;
@ -285,5 +332,10 @@ function buildServerFilterListFromDir(aDir, aExistingEntries) {
* Open the Preferences dialog on the Junk settings tab.
*/
function showGlobalJunkPrefs() {
openPrefsFromAccountManager("panePrivacy", "privacyJunkCategory", null, "junk_pane");
openPrefsFromAccountManager(
"panePrivacy",
"privacyJunkCategory",
null,
"junk_pane"
);
}

Просмотреть файл

@ -13,10 +13,11 @@ function onInit(aPageId, aServerId) {
var defaultTitle = title.getAttribute("defaultTitle");
var titleValue;
if (accountName.value)
if (accountName.value) {
titleValue = defaultTitle + " - <" + accountName.value + ">";
else
} else {
titleValue = defaultTitle;
}
title.setAttribute("value", titleValue);
document.title = titleValue;
@ -34,8 +35,9 @@ function manageIdentities() {
// UI. This ensures that the changes are reflected in the identity list dialog
// onSave();
if (!gAccount)
if (!gAccount) {
return;
}
var accountName = document.getElementById("server.prettyName").value;
@ -46,7 +48,12 @@ function manageIdentities() {
var identity = gAccount.defaultIdentity;
saveIdentitySettings(identity);
window.openDialog("am-identities-list.xul", "", "chrome,modal,resizable=no,centerscreen", args);
window.openDialog(
"am-identities-list.xul",
"",
"chrome,modal,resizable=no,centerscreen",
args
);
if (args.result) {
// now re-initialize the default identity settings in case they changed

Просмотреть файл

@ -6,8 +6,10 @@
/* import-globals-from am-prefs.js */
/* import-globals-from ../../content/retention.js */
var {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm");
var {fixIterator} = ChromeUtils.import("resource:///modules/iteratorUtils.jsm");
var { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm");
var { fixIterator } = ChromeUtils.import(
"resource:///modules/iteratorUtils.jsm"
);
var gIncomingServer;
var gServerType;
@ -15,7 +17,7 @@ var gImapIncomingServer;
var gPref = null;
var gLockedPref = {};
var gOfflineMap = null; // map of folder URLs to offline flags
var gOfflineFolders; // initial state of allFoldersOffline checkbox
var gOfflineFolders; // initial state of allFoldersOffline checkbox
var gToggleOccurred = false;
function onInit(aPageId, aServerId) {
@ -44,16 +46,23 @@ function initOfflineSettings() {
}
function initServerSettings() {
document.getElementById("offline.notDownload").checked = gIncomingServer.limitOfflineMessageSize;
document.getElementById("autosync.notDownload").checked = gIncomingServer.limitOfflineMessageSize;
if (gIncomingServer.maxMessageSize > 0)
document.getElementById("offline.notDownloadMin").value = gIncomingServer.maxMessageSize;
else
document.getElementById("offline.notDownload").checked =
gIncomingServer.limitOfflineMessageSize;
document.getElementById("autosync.notDownload").checked =
gIncomingServer.limitOfflineMessageSize;
if (gIncomingServer.maxMessageSize > 0) {
document.getElementById("offline.notDownloadMin").value =
gIncomingServer.maxMessageSize;
} else {
document.getElementById("offline.notDownloadMin").value = "50";
}
if (gServerType == "imap") {
gImapIncomingServer = gIncomingServer.QueryInterface(Ci.nsIImapIncomingServer);
document.getElementById("offline.folders").checked = gImapIncomingServer.offlineDownload;
gImapIncomingServer = gIncomingServer.QueryInterface(
Ci.nsIImapIncomingServer
);
document.getElementById("offline.folders").checked =
gImapIncomingServer.offlineDownload;
}
}
@ -61,18 +70,24 @@ function initRetentionSettings() {
let retentionSettings = gIncomingServer.retentionSettings;
initCommonRetentionSettings(retentionSettings);
document.getElementById("nntp.removeBody").checked = retentionSettings.cleanupBodiesByDays;
document.getElementById("nntp.removeBody").checked =
retentionSettings.cleanupBodiesByDays;
document.getElementById("nntp.removeBodyMin").value =
(retentionSettings.daysToKeepBodies > 0) ? retentionSettings.daysToKeepBodies : 30;
retentionSettings.daysToKeepBodies > 0
? retentionSettings.daysToKeepBodies
: 30;
}
function initDownloadSettings() {
let downloadSettings = gIncomingServer.downloadSettings;
document.getElementById("nntp.downloadMsg").checked = downloadSettings.downloadByDate;
document.getElementById("nntp.notDownloadRead").checked = downloadSettings.downloadUnreadOnly;
document.getElementById("nntp.downloadMsg").checked =
downloadSettings.downloadByDate;
document.getElementById("nntp.notDownloadRead").checked =
downloadSettings.downloadUnreadOnly;
document.getElementById("nntp.downloadMsgMin").value =
(downloadSettings.ageLimitOfMsgsToDownload > 0) ?
downloadSettings.ageLimitOfMsgsToDownload : 30;
downloadSettings.ageLimitOfMsgsToDownload > 0
? downloadSettings.ageLimitOfMsgsToDownload
: 30;
// Figure out what the most natural division of the autosync pref into
// a value and an interval is.
@ -80,8 +95,8 @@ function initDownloadSettings() {
let autosyncInterval = document.getElementById("autosyncInterval");
let autosyncValue = document.getElementById("autosyncValue");
let autosyncPref = document.getElementById("imap.autoSyncMaxAgeDays");
let autosyncPrefValue = (autosyncPref.value == "") ? -1 :
parseInt(autosyncPref.value, 10);
let autosyncPrefValue =
autosyncPref.value == "" ? -1 : parseInt(autosyncPref.value, 10);
// Clear the preference until we're done initializing.
autosyncPref.value = "";
@ -98,8 +113,9 @@ function initDownloadSettings() {
// Otherwise, get the list of possible intervals, in order from
// largest to smallest.
let valuesToTest = [];
for (let i = autosyncInterval.itemCount - 1; i >= 0; i--)
for (let i = autosyncInterval.itemCount - 1; i >= 0; i--) {
valuesToTest.push(autosyncInterval.getItemAtIndex(i).value);
}
// and find the first one that divides the preference evenly.
for (let i in valuesToTest) {
@ -116,21 +132,30 @@ function initDownloadSettings() {
autosyncPref.value = autosyncPrefValue;
}
function onPreInit(account, accountValues) {
gServerType = top.getAccountValue(account, accountValues, "server", "type", null, false);
gServerType = top.getAccountValue(
account,
accountValues,
"server",
"type",
null,
false
);
hideShowControls(gServerType);
gIncomingServer = account.incomingServer;
gIncomingServer.type = gServerType;
// 10 is OFFLINE_SUPPORT_LEVEL_REGULAR, see nsIMsgIncomingServer.idl
// currently, there is no offline without diskspace
var titleStringID = (gIncomingServer.offlineSupportLevel >= 10) ?
"prefPanel-synchronization" : "prefPanel-diskspace";
var titleStringID =
gIncomingServer.offlineSupportLevel >= 10
? "prefPanel-synchronization"
: "prefPanel-diskspace";
var prefBundle = document.getElementById("bundle_prefs");
document.querySelector("#headertitle > .dialogheader-title")
.setAttribute("value", prefBundle.getString(titleStringID));
document
.querySelector("#headertitle > .dialogheader-title")
.setAttribute("value", prefBundle.getString(titleStringID));
document.title = prefBundle.getString(titleStringID);
if (gServerType == "pop3") {
@ -141,15 +166,20 @@ function onPreInit(account, accountValues) {
retentionRadio.setAttribute("hidden", "true");
var retentionLabel = document.getElementById("retentionDescriptionPop");
retentionLabel.setAttribute("hidden", "true");
var applyToFlaggedCheckbox = document.getElementById("retention.applyToFlagged");
var applyToFlaggedCheckbox = document.getElementById(
"retention.applyToFlagged"
);
applyToFlaggedCheckbox.setAttribute("hidden", "true");
}
}
}
function onClickSelect() {
top.window.openDialog("chrome://messenger/content/msgSelectOfflineFolders.xul",
"", "centerscreen,chrome,modal,titlebar,resizable=yes");
top.window.openDialog(
"chrome://messenger/content/msgSelectOfflineFolders.xul",
"",
"centerscreen,chrome,modal,titlebar,resizable=yes"
);
return true;
}
@ -164,8 +194,9 @@ function onAutosyncChange() {
// If we're not done initializing, don't do anything.
// (See initDownloadSettings() for more details.)
if (autosyncPref.value == "")
if (autosyncPref.value == "") {
return;
}
// If the user selected the All option, disable the autosync and the
// textbox.
@ -176,10 +207,11 @@ function onAutosyncChange() {
return;
}
let max = 0x7FFFFFFF / (60 * 60 * 24 * autosyncInterval.value);
let max = 0x7fffffff / (60 * 60 * 24 * autosyncInterval.value);
autosyncValue.setAttribute("max", max);
if (autosyncValue.value > max)
if (autosyncValue.value > max) {
autosyncValue.value = Math.floor(max);
}
autosyncInterval.disabled = false;
autosyncValue.disabled = false;
@ -190,8 +222,9 @@ function onAutosyncNotDownload() {
// This function is called when the autosync version of offline.notDownload
// is changed it simply copies the new checkbox value over to the element
// driving the preference.
document.getElementById("offline.notDownload").checked =
document.getElementById("autosync.notDownload").checked;
document.getElementById(
"offline.notDownload"
).checked = document.getElementById("autosync.notDownload").checked;
onCheckItem1("offline.notDownloadMin", "offline.notDownload");
}
@ -209,8 +242,10 @@ function onLeave() {
if (gToggleOccurred) {
let allFolders = gIncomingServer.rootFolder.descendants;
for (let folder of fixIterator(allFolders, Ci.nsIMsgFolder)) {
if (gOfflineMap[folder.folderURL] !=
folder.getFlag(Ci.nsMsgFolderFlags.Offline)) {
if (
gOfflineMap[folder.folderURL] !=
folder.getFlag(Ci.nsMsgFolderFlags.Offline)
) {
// A change to the Offline flag to a folder was made.
changed = true;
break;
@ -227,12 +262,18 @@ function onLeave() {
let title = prefBundle.getString("confirmSyncChangesTitle");
let question = prefBundle.getString("confirmSyncChanges");
let discard = prefBundle.getString("confirmSyncChangesDiscard");
let result = Services.prompt
.confirmEx(window, title, question,
(Services.prompt.BUTTON_TITLE_SAVE * Services.prompt.BUTTON_POS_0) +
(Services.prompt.BUTTON_TITLE_IS_STRING * Services.prompt.BUTTON_POS_1),
null, discard, null,
null, {value: 0});
let result = Services.prompt.confirmEx(
window,
title,
question,
Services.prompt.BUTTON_TITLE_SAVE * Services.prompt.BUTTON_POS_0 +
Services.prompt.BUTTON_TITLE_IS_STRING * Services.prompt.BUTTON_POS_1,
null,
discard,
null,
null,
{ value: 0 }
);
if (result == 1) {
// User clicked Discard button, so restore the online/offline changes for
// the current account. Changes made through the "Advanced..." dialog to
@ -245,27 +286,46 @@ function onLeave() {
}
function onSave() {
var downloadSettings = Cc["@mozilla.org/msgDatabase/downloadSettings;1"]
.createInstance(Ci.nsIMsgDownloadSettings);
var downloadSettings = Cc[
"@mozilla.org/msgDatabase/downloadSettings;1"
].createInstance(Ci.nsIMsgDownloadSettings);
gIncomingServer.limitOfflineMessageSize = document.getElementById("offline.notDownload").checked;
gIncomingServer.maxMessageSize = document.getElementById("offline.notDownloadMin").value;
gIncomingServer.limitOfflineMessageSize = document.getElementById(
"offline.notDownload"
).checked;
gIncomingServer.maxMessageSize = document.getElementById(
"offline.notDownloadMin"
).value;
var retentionSettings = saveCommonRetentionSettings(gIncomingServer.retentionSettings);
var retentionSettings = saveCommonRetentionSettings(
gIncomingServer.retentionSettings
);
retentionSettings.daysToKeepBodies = document.getElementById("nntp.removeBodyMin").value;
retentionSettings.cleanupBodiesByDays = document.getElementById("nntp.removeBody").checked;
retentionSettings.daysToKeepBodies = document.getElementById(
"nntp.removeBodyMin"
).value;
retentionSettings.cleanupBodiesByDays = document.getElementById(
"nntp.removeBody"
).checked;
downloadSettings.downloadByDate = document.getElementById("nntp.downloadMsg").checked;
downloadSettings.downloadUnreadOnly = document.getElementById("nntp.notDownloadRead").checked;
downloadSettings.ageLimitOfMsgsToDownload = document.getElementById("nntp.downloadMsgMin").value;
downloadSettings.downloadByDate = document.getElementById(
"nntp.downloadMsg"
).checked;
downloadSettings.downloadUnreadOnly = document.getElementById(
"nntp.notDownloadRead"
).checked;
downloadSettings.ageLimitOfMsgsToDownload = document.getElementById(
"nntp.downloadMsgMin"
).value;
gIncomingServer.retentionSettings = retentionSettings;
gIncomingServer.downloadSettings = downloadSettings;
if (gImapIncomingServer) {
// Set the pref on the incomingserver, and set the flag on all folders.
gImapIncomingServer.offlineDownload = document.getElementById("offline.folders").checked;
gImapIncomingServer.offlineDownload = document.getElementById(
"offline.folders"
).checked;
}
}
@ -308,7 +368,10 @@ function onLockPreference() {
{ prefstring: "cleanupBodies", id: "nntp.removeBody" },
{ prefstring: "applyToFlagged", id: "retention.applyToFlagged" },
{ prefstring: "disable_button.selectFolder", id: "selectNewsgroupsButton" },
{ prefstring: "disable_button.selectFolder", id: "selectImapFoldersButton" },
{
prefstring: "disable_button.selectFolder",
id: "selectImapFoldersButton",
},
];
finalPrefString = initPrefString + "." + gIncomingServer.key + ".";
@ -332,10 +395,11 @@ function toggleOffline() {
let offline = document.getElementById("offline.folders").checked;
let allFolders = gIncomingServer.rootFolder.descendants;
for (let folder of fixIterator(allFolders, Ci.nsIMsgFolder)) {
if (offline)
if (offline) {
folder.setFlag(Ci.nsMsgFolderFlags.Offline);
else
} else {
folder.clearFlag(Ci.nsMsgFolderFlags.Offline);
}
}
gToggleOccurred = true;
}
@ -343,8 +407,11 @@ function toggleOffline() {
function collectOfflineFolders() {
let offlineFolderMap = {};
let allFolders = gIncomingServer.rootFolder.descendants;
for (let folder of fixIterator(allFolders, Ci.nsIMsgFolder))
offlineFolderMap[folder.folderURL] = folder.getFlag(Ci.nsMsgFolderFlags.Offline);
for (let folder of fixIterator(allFolders, Ci.nsIMsgFolder)) {
offlineFolderMap[folder.folderURL] = folder.getFlag(
Ci.nsMsgFolderFlags.Offline
);
}
return offlineFolderMap;
}
@ -352,10 +419,11 @@ function collectOfflineFolders() {
function restoreOfflineFolders(offlineFolderMap) {
let allFolders = gIncomingServer.rootFolder.descendants;
for (let folder of fixIterator(allFolders, Ci.nsIMsgFolder)) {
if (offlineFolderMap[folder.folderURL])
if (offlineFolderMap[folder.folderURL]) {
folder.setFlag(Ci.nsMsgFolderFlags.Offline);
else
} else {
folder.clearFlag(Ci.nsMsgFolderFlags.Offline);
}
}
}
@ -368,7 +436,11 @@ function restoreOfflineFolders(offlineFolderMap) {
function warnServerRemove(aRadio) {
let confirmFor = aRadio.getAttribute("confirmfor");
if (confirmFor && confirmFor.split(",").includes(gServerType) && aRadio.value != 1) {
if (
confirmFor &&
confirmFor.split(",").includes(gServerType) &&
aRadio.value != 1
) {
let prefBundle = document.getElementById("bundle_prefs");
let title = prefBundle.getString("removeFromServerTitle");
let question = prefBundle.getString("removeFromServer");

Просмотреть файл

@ -6,7 +6,7 @@
/* functions for disabling front end elements when the appropriate
back-end preference is locked. */
var {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm");
var { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm");
/**
* Prefs in MailNews require dynamic portions to indicate
@ -34,21 +34,24 @@ function substPrefTokens(aStr, aElement) {
the xul object */
for (let i = 0; i < prefPartsArray.length; i++) {
token = prefPartsArray[i].match(tokenpat);
if (token) { /* we've got a %% match */
if (token) {
/* we've got a %% match */
if (token[1]) {
if (aElement[token[1]]) {
newprefstr += aElement[token[1]] + "."; // here's where we get the info
} else { /* all we got was this stinkin % */
} else {
/* all we got was this stinkin % */
newprefstr += prefPartsArray[i] + ".";
}
}
} else /* if (token) */ {
} /* if (token) */ else {
newprefstr += prefPartsArray[i] + ".";
}
}
newprefstr = newprefstr.slice(0, -1); // remove the last char, a dot
if (newprefstr.length <= 0)
if (newprefstr.length <= 0) {
newprefstr = null;
}
return newprefstr;
}
@ -67,8 +70,9 @@ function getAccountValueIsLocked(aElement) {
if (prefstring) {
let prefstr = substPrefTokens(prefstring, aElement);
// see if the prefstring is locked
if (prefstr)
if (prefstr) {
return Services.prefs.prefIsLocked(prefstr);
}
}
return false;
}
@ -91,12 +95,13 @@ function onCheckItem(aChangeElementId, aCheckElementIds) {
for (let notifyId of aCheckElementIds) {
let notifyElement = document.getElementById(notifyId);
let notifyElementState = null;
if ("checked" in notifyElement)
if ("checked" in notifyElement) {
notifyElementState = notifyElement.checked;
else if ("selected" in notifyElement)
} else if ("selected" in notifyElement) {
notifyElementState = notifyElement.selected;
else
} else {
Cu.reportError("Unknown type of control element: " + notifyElement.id);
}
if (!notifyElementState) {
disabled = true;
@ -104,8 +109,9 @@ function onCheckItem(aChangeElementId, aCheckElementIds) {
}
}
if (!disabled && getAccountValueIsLocked(elementToControl))
if (!disabled && getAccountValueIsLocked(elementToControl)) {
disabled = true;
}
elementToControl.disabled = disabled;
}
@ -131,9 +137,10 @@ function hideShowControls(serverType) {
}
}
if (hide)
if (hide) {
control.setAttribute("hidden", "true");
else
} else {
control.removeAttribute("hidden");
}
}
}

Просмотреть файл

@ -3,8 +3,10 @@
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
var {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm");
var {MailServices} = ChromeUtils.import("resource:///modules/MailServices.jsm");
var { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm");
var { MailServices } = ChromeUtils.import(
"resource:///modules/MailServices.jsm"
);
document.addEventListener("dialogaccept", onOk);
@ -16,23 +18,26 @@ var gFirstDeferredAccount;
var gControls;
function getControls() {
if (!gControls)
if (!gControls) {
gControls = document.getElementsByAttribute("amsa_persist", "true");
}
return gControls;
}
function getLocalFoldersAccount() {
return MailServices.accounts
.FindAccountForServer(MailServices.accounts.localFoldersServer);
return MailServices.accounts.FindAccountForServer(
MailServices.accounts.localFoldersServer
);
}
function onLoad() {
var prettyName = gServerSettings.serverPrettyName;
if (prettyName)
document.getElementById("serverPrettyName").value =
document.getElementById("bundle_prefs")
.getFormattedString("forAccount", [prettyName]);
if (prettyName) {
document.getElementById("serverPrettyName").value = document
.getElementById("bundle_prefs")
.getFormattedString("forAccount", [prettyName]);
}
if (gServerSettings.serverType == "imap") {
document.getElementById("pop3Panel").hidden = true;
@ -46,8 +51,10 @@ function onLoad() {
// The current account should not be shown in the folder picker
// of the "other account" option.
folderPopup._teardown();
folderPopup.setAttribute("excludeServers",
gServerSettings.account.incomingServer.key);
folderPopup.setAttribute(
"excludeServers",
gServerSettings.account.incomingServer.key
);
folderPopup._ensureInitialized();
if (gFirstDeferredAccount.length) {
@ -77,10 +84,11 @@ function onLoad() {
for (let i = 0; i < controls.length; i++) {
var slot = controls[i].id;
if (slot in gServerSettings) {
if (controls[i].localName == "checkbox")
if (controls[i].localName == "checkbox") {
controls[i].checked = gServerSettings[slot];
else
} else {
controls[i].value = gServerSettings[slot];
}
}
}
}
@ -95,11 +103,13 @@ function onOk(event) {
// This account wasn't previously deferred, but is now deferred.
if (radioGroup.value != "currentAccount" && !gFirstDeferredAccount.length) {
// If the user hasn't selected a folder, keep the default.
if (!picker.selectedItem)
if (!picker.selectedItem) {
return;
}
var confirmDeferAccount =
gPrefsBundle.getString("confirmDeferAccountWarning");
var confirmDeferAccount = gPrefsBundle.getString(
"confirmDeferAccountWarning"
);
var confirmTitle = gPrefsBundle.getString("confirmDeferAccountTitle");
@ -125,17 +135,19 @@ function onOk(event) {
for (let i = 0; i < controls.length; i++) {
var slot = controls[i].id;
if (slot in gServerSettings) {
if (controls[i].localName == "checkbox")
if (controls[i].localName == "checkbox") {
gServerSettings[slot] = controls[i].checked;
else
} else {
gServerSettings[slot] = controls[i].value;
}
}
}
}
// Set radio element choices and picker states
function updateInboxAccount(enablePicker) {
document.getElementById("deferredServerFolderPicker").disabled = !enablePicker;
document.getElementById(
"deferredServerFolderPicker"
).disabled = !enablePicker;
document.getElementById("deferGetNewMail").disabled = !enablePicker;
}

Просмотреть файл

@ -6,10 +6,14 @@
/* import-globals-from am-prefs.js */
/* import-globals-from amUtils.js */
var {fixIterator} = ChromeUtils.import("resource:///modules/iteratorUtils.jsm");
var {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm");
var {MailUtils} = ChromeUtils.import("resource:///modules/MailUtils.jsm");
var {BrowserUtils} = ChromeUtils.import("resource://gre/modules/BrowserUtils.jsm");
var { fixIterator } = ChromeUtils.import(
"resource:///modules/iteratorUtils.jsm"
);
var { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm");
var { MailUtils } = ChromeUtils.import("resource:///modules/MailUtils.jsm");
var { BrowserUtils } = ChromeUtils.import(
"resource://gre/modules/BrowserUtils.jsm"
);
var gServer;
var gOriginalStoreType;
@ -28,9 +32,14 @@ function clickStoreTypeMenu(aStoreTypeElement) {
// otherwise 'response.newRootFolder' will be null.
let response = { newRootFolder: null };
// Send 'response' as an argument to converterDialog.xhtml.
window.openDialog("converterDialog.xhtml", "mailnews:mailstoreconverter",
"modal,centerscreen,resizable=no,width=700,height=130", gServer,
aStoreTypeElement.value, response);
window.openDialog(
"converterDialog.xhtml",
"mailnews:mailstoreconverter",
"modal,centerscreen,resizable=no,width=700,height=130",
gServer,
aStoreTypeElement.value,
response
);
changeStoreType(response);
}
@ -48,29 +57,32 @@ function changeStoreType(aResponse) {
if (gServer.type == "nntp") {
let newRootFolder = aResponse.newRootFolder;
let lastSlash = newRootFolder.lastIndexOf("/");
let newsrc = newRootFolder.slice(0, lastSlash) + "/newsrc-" +
newRootFolder.slice(lastSlash + 1);
let newsrc =
newRootFolder.slice(0, lastSlash) +
"/newsrc-" +
newRootFolder.slice(lastSlash + 1);
document.getElementById("nntp.newsrcFilePath").value = newsrc;
}
document.getElementById("server.localPath").value = aResponse.newRootFolder;
gOriginalStoreType = document.getElementById("server.storeTypeMenulist")
.value;
.value;
BrowserUtils.restartApplication();
} else {
// The conversion failed or was cancelled.
// Restore selected item to what was selected before conversion.
document.getElementById("server.storeTypeMenulist").value =
gOriginalStoreType;
document.getElementById(
"server.storeTypeMenulist"
).value = gOriginalStoreType;
}
}
function onSave() {
let storeContractID = document.getElementById("server.storeTypeMenulist")
.selectedItem
.value;
document.getElementById("server.storeContractID")
.setAttribute("value", storeContractID);
.selectedItem.value;
document
.getElementById("server.storeContractID")
.setAttribute("value", storeContractID);
}
function onInit(aPageId, aServerId) {
@ -81,12 +93,13 @@ function onInit(aPageId, aServerId) {
setupMailOnServerUI();
setupFixedUI();
let serverType = document.getElementById("server.type").getAttribute("value");
if (serverType == "imap")
if (serverType == "imap") {
setupImapDeleteUI(aServerId);
}
// TLS Cert (External) and OAuth2 are only supported on IMAP.
document.getElementById("authMethod-oauth2").hidden = (serverType != "imap");
document.getElementById("authMethod-external").hidden = (serverType != "imap");
document.getElementById("authMethod-oauth2").hidden = serverType != "imap";
document.getElementById("authMethod-external").hidden = serverType != "imap";
// "STARTTLS, if available" is vulnerable to MITM attacks so we shouldn't
// allow users to choose it anymore. Hide the option unless the user already
@ -96,27 +109,45 @@ function onInit(aPageId, aServerId) {
// UI for account store type.
let storeTypeElement = document.getElementById("server.storeTypeMenulist");
// set the menuitem to match the account
let currentStoreID = document.getElementById("server.storeContractID")
.getAttribute("value");
let targetItem = storeTypeElement.getElementsByAttribute("value", currentStoreID);
let currentStoreID = document
.getElementById("server.storeContractID")
.getAttribute("value");
let targetItem = storeTypeElement.getElementsByAttribute(
"value",
currentStoreID
);
storeTypeElement.selectedItem = targetItem[0];
// Disable store type change if store has not been used yet.
storeTypeElement.setAttribute("disabled",
gServer.getBoolValue("canChangeStoreType") ?
"false" : !Services.prefs.getBoolPref("mail.store_conversion_enabled"));
storeTypeElement.setAttribute(
"disabled",
gServer.getBoolValue("canChangeStoreType")
? "false"
: !Services.prefs.getBoolPref("mail.store_conversion_enabled")
);
// Initialise 'gOriginalStoreType' to the item that was originally selected.
gOriginalStoreType = storeTypeElement.value;
}
function onPreInit(account, accountValues) {
var type = parent.getAccountValue(account, accountValues, "server", "type", null, false);
var type = parent.getAccountValue(
account,
accountValues,
"server",
"type",
null,
false
);
hideShowControls(type);
gServer = account.incomingServer;
if (!account.incomingServer.canEmptyTrashOnExit) {
document.getElementById("server.emptyTrashOnExit").setAttribute("hidden", "true");
document.getElementById("imap.deleteModel.box").setAttribute("hidden", "true");
document
.getElementById("server.emptyTrashOnExit")
.setAttribute("hidden", "true");
document
.getElementById("imap.deleteModel.box")
.setAttribute("hidden", "true");
}
}
@ -138,8 +169,10 @@ function initServerType() {
setLabelFromStringBundle("authMethod-oauth2", "authOAuth2");
setLabelFromStringBundle("authMethod-anysecure", "authAnySecure");
setLabelFromStringBundle("authMethod-any", "authAny");
setLabelFromStringBundle("authMethod-password-encrypted",
"authPasswordEncrypted");
setLabelFromStringBundle(
"authMethod-password-encrypted",
"authPasswordEncrypted"
);
// authMethod-password-cleartext already set in secureSelect()
// Hide deprecated/hidden auth options, unless selected
@ -154,18 +187,19 @@ function hideUnlessSelected(element) {
}
function setLabelFromStringBundle(elementID, stringName) {
document.getElementById(elementID).label =
document.getElementById("bundle_messenger").getString(stringName);
document.getElementById(elementID).label = document
.getElementById("bundle_messenger")
.getString(stringName);
}
function setDivText(divname, value) {
var div = document.getElementById(divname);
if (!div)
if (!div) {
return;
}
div.setAttribute("value", value);
}
function onAdvanced() {
// Store the server type and, if an IMAP or POP3 server,
// the settings needed for the IMAP/POP3 tab into the array
@ -177,43 +211,86 @@ function onAdvanced() {
serverSettings.account = top.getCurrentAccount();
if (serverType == "imap") {
serverSettings.dualUseFolders = document.getElementById("imap.dualUseFolders").checked;
serverSettings.usingSubscription = document.getElementById("imap.usingSubscription").checked;
serverSettings.maximumConnectionsNumber = document.getElementById("imap.maximumConnectionsNumber").getAttribute("value");
serverSettings.dualUseFolders = document.getElementById(
"imap.dualUseFolders"
).checked;
serverSettings.usingSubscription = document.getElementById(
"imap.usingSubscription"
).checked;
serverSettings.maximumConnectionsNumber = document
.getElementById("imap.maximumConnectionsNumber")
.getAttribute("value");
// string prefs
serverSettings.personalNamespace = document.getElementById("imap.personalNamespace").getAttribute("value");
serverSettings.publicNamespace = document.getElementById("imap.publicNamespace").getAttribute("value");
serverSettings.serverDirectory = document.getElementById("imap.serverDirectory").getAttribute("value");
serverSettings.otherUsersNamespace = document.getElementById("imap.otherUsersNamespace").getAttribute("value");
serverSettings.overrideNamespaces = document.getElementById("imap.overrideNamespaces").checked;
serverSettings.personalNamespace = document
.getElementById("imap.personalNamespace")
.getAttribute("value");
serverSettings.publicNamespace = document
.getElementById("imap.publicNamespace")
.getAttribute("value");
serverSettings.serverDirectory = document
.getElementById("imap.serverDirectory")
.getAttribute("value");
serverSettings.otherUsersNamespace = document
.getElementById("imap.otherUsersNamespace")
.getAttribute("value");
serverSettings.overrideNamespaces = document.getElementById(
"imap.overrideNamespaces"
).checked;
} else if (serverType == "pop3") {
serverSettings.deferGetNewMail = document.getElementById("pop3.deferGetNewMail").checked;
serverSettings.deferredToAccount = document.getElementById("pop3.deferredToAccount").getAttribute("value");
serverSettings.deferGetNewMail = document.getElementById(
"pop3.deferGetNewMail"
).checked;
serverSettings.deferredToAccount = document
.getElementById("pop3.deferredToAccount")
.getAttribute("value");
}
window.openDialog("chrome://messenger/content/am-server-advanced.xul",
"_blank", "chrome,modal,titlebar", serverSettings);
window.openDialog(
"chrome://messenger/content/am-server-advanced.xul",
"_blank",
"chrome,modal,titlebar",
serverSettings
);
if (serverType == "imap") {
document.getElementById("imap.dualUseFolders").checked = serverSettings.dualUseFolders;
document.getElementById("imap.usingSubscription").checked = serverSettings.usingSubscription;
document.getElementById("imap.maximumConnectionsNumber").setAttribute("value", serverSettings.maximumConnectionsNumber);
document.getElementById("imap.dualUseFolders").checked =
serverSettings.dualUseFolders;
document.getElementById("imap.usingSubscription").checked =
serverSettings.usingSubscription;
document
.getElementById("imap.maximumConnectionsNumber")
.setAttribute("value", serverSettings.maximumConnectionsNumber);
// string prefs
document.getElementById("imap.personalNamespace").setAttribute("value", serverSettings.personalNamespace);
document.getElementById("imap.publicNamespace").setAttribute("value", serverSettings.publicNamespace);
document.getElementById("imap.serverDirectory").setAttribute("value", serverSettings.serverDirectory);
document.getElementById("imap.otherUsersNamespace").setAttribute("value", serverSettings.otherUsersNamespace);
document.getElementById("imap.overrideNamespaces").checked = serverSettings.overrideNamespaces;
document
.getElementById("imap.personalNamespace")
.setAttribute("value", serverSettings.personalNamespace);
document
.getElementById("imap.publicNamespace")
.setAttribute("value", serverSettings.publicNamespace);
document
.getElementById("imap.serverDirectory")
.setAttribute("value", serverSettings.serverDirectory);
document
.getElementById("imap.otherUsersNamespace")
.setAttribute("value", serverSettings.otherUsersNamespace);
document.getElementById("imap.overrideNamespaces").checked =
serverSettings.overrideNamespaces;
} else if (serverType == "pop3") {
document.getElementById("pop3.deferGetNewMail").checked = serverSettings.deferGetNewMail;
document.getElementById("pop3.deferredToAccount").setAttribute("value", serverSettings.deferredToAccount);
document.getElementById("pop3.deferGetNewMail").checked =
serverSettings.deferGetNewMail;
document
.getElementById("pop3.deferredToAccount")
.setAttribute("value", serverSettings.deferredToAccount);
let pop3Server = gServer.QueryInterface(Ci.nsIPop3IncomingServer);
// we're explicitly setting this so we'll go through the SetDeferredToAccount method
pop3Server.deferredToAccount = serverSettings.deferredToAccount;
// Setting the server to be deferred causes a rebuild of the account tree,
// losing the current selection. Reselect the current server again as it
// didn't really disappear.
parent.selectServer(parent.getCurrentAccount().incomingServer, parent.currentPageId);
parent.selectServer(
parent.getCurrentAccount().incomingServer,
parent.currentPageId
);
// Iterate over all accounts to see if any of their junk targets are now
// invalid (pointed to the account that is now deferred).
@ -222,39 +299,91 @@ function onAdvanced() {
// to that folder (moveOnSpam = true) then moving junk is disabled
// (so that the user notices it and checks the settings).
// This is the same sanitization as in am-junk.js, just applied to all POP accounts.
let deferredURI = serverSettings.deferredToAccount &&
MailServices.accounts.getAccount(serverSettings.deferredToAccount)
.incomingServer.serverURI;
let deferredURI =
serverSettings.deferredToAccount &&
MailServices.accounts.getAccount(serverSettings.deferredToAccount)
.incomingServer.serverURI;
for (let account of fixIterator(MailServices.accounts.accounts,
Ci.nsIMsgAccount)) {
for (let account of fixIterator(
MailServices.accounts.accounts,
Ci.nsIMsgAccount
)) {
let accountValues = parent.getValueArrayFor(account);
let type = parent.getAccountValue(account, accountValues, "server", "type",
null, false);
let type = parent.getAccountValue(
account,
accountValues,
"server",
"type",
null,
false
);
// Try to keep this list of account types not having Junk settings
// synchronized with the list in AccountManager.js.
if (type != "nntp" && type != "rss" && type != "im") {
let spamActionTargetAccount = parent.getAccountValue(account, accountValues,
"server", "spamActionTargetAccount", "string", true);
let spamActionTargetFolder = parent.getAccountValue(account, accountValues,
"server", "spamActionTargetFolder", "string", true);
let moveOnSpam = parent.getAccountValue(account, accountValues,
"server", "moveOnSpam", "bool", true);
let spamActionTargetAccount = parent.getAccountValue(
account,
accountValues,
"server",
"spamActionTargetAccount",
"string",
true
);
let spamActionTargetFolder = parent.getAccountValue(
account,
accountValues,
"server",
"spamActionTargetFolder",
"string",
true
);
let moveOnSpam = parent.getAccountValue(
account,
accountValues,
"server",
"moveOnSpam",
"bool",
true
);
// Check if there are any invalid junk targets and fix them.
[ spamActionTargetAccount, spamActionTargetFolder, moveOnSpam ] =
sanitizeJunkTargets(spamActionTargetAccount,
spamActionTargetFolder,
deferredURI || account.incomingServer.serverURI,
parent.getAccountValue(account, accountValues, "server", "moveTargetMode", "int", true),
account.incomingServer.spamSettings,
moveOnSpam);
[
spamActionTargetAccount,
spamActionTargetFolder,
moveOnSpam,
] = sanitizeJunkTargets(
spamActionTargetAccount,
spamActionTargetFolder,
deferredURI || account.incomingServer.serverURI,
parent.getAccountValue(
account,
accountValues,
"server",
"moveTargetMode",
"int",
true
),
account.incomingServer.spamSettings,
moveOnSpam
);
parent.setAccountValue(accountValues, "server", "moveOnSpam", moveOnSpam);
parent.setAccountValue(accountValues, "server", "spamActionTargetAccount",
spamActionTargetAccount);
parent.setAccountValue(accountValues, "server", "spamActionTargetFolder",
spamActionTargetFolder);
parent.setAccountValue(
accountValues,
"server",
"moveOnSpam",
moveOnSpam
);
parent.setAccountValue(
accountValues,
"server",
"spamActionTargetAccount",
spamActionTargetAccount
);
parent.setAccountValue(
accountValues,
"server",
"spamActionTargetFolder",
spamActionTargetFolder
);
}
}
}
@ -270,19 +399,34 @@ function secureSelect(aLoading) {
if (socketType == Ci.nsMsgSocketType.SSL) {
portDefault.value = defaultPortSecure;
if (port.value == "" || (!aLoading && port.value == defaultPort && prevDefaultPort != portDefault.value))
if (
port.value == "" ||
(!aLoading &&
port.value == defaultPort &&
prevDefaultPort != portDefault.value)
) {
port.value = defaultPortSecure;
}
} else {
portDefault.value = defaultPort;
if (port.value == "" || (!aLoading && port.value == defaultPortSecure && prevDefaultPort != portDefault.value))
if (
port.value == "" ||
(!aLoading &&
port.value == defaultPortSecure &&
prevDefaultPort != portDefault.value)
) {
port.value = defaultPort;
}
}
// switch "insecure password" label
setLabelFromStringBundle("authMethod-password-cleartext",
setLabelFromStringBundle(
"authMethod-password-cleartext",
socketType == Ci.nsMsgSocketType.SSL ||
socketType == Ci.nsMsgSocketType.alwaysSTARTTLS ?
"authPasswordCleartextViaSSL" : "authPasswordCleartextInsecurely");
socketType == Ci.nsMsgSocketType.alwaysSTARTTLS
? "authPasswordCleartextViaSSL"
: "authPasswordCleartextInsecurely"
);
}
function setupMailOnServerUI() {
@ -299,14 +443,18 @@ function setupAgeMsgOnServerUI() {
}
function setupFixedUI() {
var controls = [document.getElementById("fixedServerName"),
document.getElementById("fixedUserName"),
document.getElementById("fixedServerPort")];
var controls = [
document.getElementById("fixedServerName"),
document.getElementById("fixedUserName"),
document.getElementById("fixedServerPort"),
];
var len = controls.length;
for (let i = 0; i < len; i++) {
var fixedElement = controls[i];
var otherElement = document.getElementById(fixedElement.getAttribute("use"));
var otherElement = document.getElementById(
fixedElement.getAttribute("use")
);
fixedElement.setAttribute("collapsed", "true");
otherElement.removeAttribute("collapsed");
@ -319,14 +467,15 @@ function BrowseForNewsrc() {
var newsrcTextBox = document.getElementById("nntp.newsrcFilePath");
var fp = Cc["@mozilla.org/filepicker;1"].createInstance(nsIFilePicker);
fp.init(window,
document.getElementById("browseForNewsrc").getAttribute("filepickertitle"),
nsIFilePicker.modeSave);
fp.init(
window,
document.getElementById("browseForNewsrc").getAttribute("filepickertitle"),
nsIFilePicker.modeSave
);
var currentNewsrcFile;
try {
currentNewsrcFile = Cc["@mozilla.org/file/local;1"]
.createInstance(nsIFile);
currentNewsrcFile = Cc["@mozilla.org/file/local;1"].createInstance(nsIFile);
currentNewsrcFile.initWithPath(newsrcTextBox.value);
} catch (e) {
dump("Failed to create nsIFile instance for the current newsrc file.\n");
@ -349,7 +498,9 @@ function BrowseForNewsrc() {
function setupImapDeleteUI(aServerId) {
// read delete_model preference
var deleteModel = document.getElementById("imap.deleteModel").getAttribute("value");
var deleteModel = document
.getElementById("imap.deleteModel")
.getAttribute("value");
selectImapDeleteModel(deleteModel);
// read trash folder path preference
@ -362,10 +513,13 @@ function setupImapDeleteUI(aServerId) {
trashPopup._ensureInitialized();
// Convert the folder path in Unicode to MUTF-7.
let manager = Cc["@mozilla.org/charset-converter-manager;1"]
.getService(Ci.nsICharsetConverterManager);
let manager = Cc["@mozilla.org/charset-converter-manager;1"].getService(
Ci.nsICharsetConverterManager
);
// Escape backslash and double-quote with another backslash before encoding.
let trashMutf7 = manager.unicodeToMutf7(trashFolderName.replace(/([\\"])/g, "\\$1"));
let trashMutf7 = manager.unicodeToMutf7(
trashFolderName.replace(/([\\"])/g, "\\$1")
);
// TODO: There is something wrong here, selectFolder() fails even if the
// folder does exist. Try to fix in bug 802609.
let trashFolder = MailUtils.getOrCreateFolder(aServerId + "/" + trashMutf7);
@ -382,19 +536,25 @@ function selectImapDeleteModel(choice) {
document.getElementById("imap.deleteModel").setAttribute("value", choice);
switch (choice) {
case "0" : // markDeleted
case "0": // markDeleted
// disable folderPicker
document.getElementById("msgTrashFolderPicker").setAttribute("disabled", "true");
document
.getElementById("msgTrashFolderPicker")
.setAttribute("disabled", "true");
break;
case "1" : // moveToTrashFolder
case "1": // moveToTrashFolder
// enable folderPicker
document.getElementById("msgTrashFolderPicker").removeAttribute("disabled");
document
.getElementById("msgTrashFolderPicker")
.removeAttribute("disabled");
break;
case "2" : // deleteImmediately
case "2": // deleteImmediately
// disable folderPicker
document.getElementById("msgTrashFolderPicker").setAttribute("disabled", "true");
document
.getElementById("msgTrashFolderPicker")
.setAttribute("disabled", "true");
break;
default :
default:
dump("Error in enabling/disabling server.TrashFolderPicker\n");
break;
}
@ -408,14 +568,17 @@ function folderPickerChange(aEvent) {
// Note that the path is returned with a leading slash which we need to remove.
var folderPath = Services.io.newURI(folder.URI).pathQueryRef.substring(1);
// We need to convert that from MUTF-7 to Unicode.
var manager = Cc["@mozilla.org/charset-converter-manager;1"]
.getService(Ci.nsICharsetConverterManager);
var manager = Cc["@mozilla.org/charset-converter-manager;1"].getService(
Ci.nsICharsetConverterManager
);
var trashUnicode = manager.mutf7ToUnicode(
Services.netUtils.unescapeString(folderPath, Ci.nsINetUtil.ESCAPE_URL_PATH));
Services.netUtils.unescapeString(folderPath, Ci.nsINetUtil.ESCAPE_URL_PATH)
);
// Set the value to be persisted.
document.getElementById("imap.trashFolderName")
.setAttribute("value", trashUnicode);
document
.getElementById("imap.trashFolderName")
.setAttribute("value", trashUnicode);
// Update the widget to show/do correct things even for subfolders.
var trashFolderPicker = document.getElementById("msgTrashFolderPicker");
@ -425,11 +588,15 @@ function folderPickerChange(aEvent) {
// Get trash_folder_name from prefs. Despite its name this returns
// a folder path, for example INBOX/Trash.
function getTrashFolderName() {
var trashFolderName = document.getElementById("imap.trashFolderName").getAttribute("value");
var trashFolderName = document
.getElementById("imap.trashFolderName")
.getAttribute("value");
// if the preference hasn't been set, set it to a sane default
if (!trashFolderName) {
trashFolderName = "Trash"; // XXX Is this a useful default?
document.getElementById("imap.trashFolderName").setAttribute("value", trashFolderName);
trashFolderName = "Trash"; // XXX Is this a useful default?
document
.getElementById("imap.trashFolderName")
.setAttribute("value", trashFolderName);
}
return trashFolderName;
}

Просмотреть файл

@ -3,8 +3,10 @@
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
var {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm");
var {BrowserUtils} = ChromeUtils.import("resource://gre/modules/BrowserUtils.jsm");
var { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm");
var { BrowserUtils } = ChromeUtils.import(
"resource://gre/modules/BrowserUtils.jsm"
);
var gAccount;
var gOriginalStoreType;
@ -23,10 +25,14 @@ function clickStoreTypeMenu(aStoreTypeElement) {
// otherwise 'response.newRootFolder' will be null.
let response = { newRootFolder: null };
// Send 'response' as an argument to converterDialog.xhtml.
window.openDialog("converterDialog.xhtml", "mailnews:mailstoreconverter",
"modal,centerscreen,resizable=no,width=700,height=130",
gAccount.incomingServer,
aStoreTypeElement.value, response);
window.openDialog(
"converterDialog.xhtml",
"mailnews:mailstoreconverter",
"modal,centerscreen,resizable=no,width=700,height=130",
gAccount.incomingServer,
aStoreTypeElement.value,
response
);
changeStoreType(response);
}
@ -43,13 +49,14 @@ function changeStoreType(aResponse) {
// in 'aResponse.newRootFolder'.
document.getElementById("server.localPath").value = aResponse.newRootFolder;
gOriginalStoreType = document.getElementById("server.storeTypeMenulist")
.value;
.value;
BrowserUtils.restartApplication();
} else {
// The conversion failed or was cancelled.
// Restore selected item to what was selected before conversion.
document.getElementById("server.storeTypeMenulist").value =
gOriginalStoreType;
document.getElementById(
"server.storeTypeMenulist"
).value = gOriginalStoreType;
}
}
@ -57,14 +64,21 @@ function onInit(aPageId, aServerId) {
// UI for account store type
let storeTypeElement = document.getElementById("server.storeTypeMenulist");
// set the menuitem to match the account
let currentStoreID = document.getElementById("server.storeContractID")
.getAttribute("value");
let targetItem = storeTypeElement.getElementsByAttribute("value", currentStoreID);
let currentStoreID = document
.getElementById("server.storeContractID")
.getAttribute("value");
let targetItem = storeTypeElement.getElementsByAttribute(
"value",
currentStoreID
);
storeTypeElement.selectedItem = targetItem[0];
// Disable store type change if store has not been used yet.
storeTypeElement.setAttribute("disabled",
gAccount.incomingServer.getBoolValue("canChangeStoreType") ?
"false" : !Services.prefs.getBoolPref("mail.store_conversion_enabled"));
storeTypeElement.setAttribute(
"disabled",
gAccount.incomingServer.getBoolValue("canChangeStoreType")
? "false"
: !Services.prefs.getBoolPref("mail.store_conversion_enabled")
);
// Initialise 'gOriginalStoreType' to the item that was originally selected.
gOriginalStoreType = storeTypeElement.value;
}
@ -75,9 +89,8 @@ function onPreInit(account, accountValues) {
function onSave() {
let storeContractID = document.getElementById("server.storeTypeMenulist")
.selectedItem
.value;
document.getElementById("server.storeContractID")
.setAttribute("value", storeContractID);
.selectedItem.value;
document
.getElementById("server.storeContractID")
.setAttribute("value", storeContractID);
}

Просмотреть файл

@ -5,8 +5,10 @@
/* import-globals-from amUtils.js */
var {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm");
var {MailServices} = ChromeUtils.import("resource:///modules/MailServices.jsm");
var { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm");
var { MailServices } = ChromeUtils.import(
"resource:///modules/MailServices.jsm"
);
var gSmtpServerListWindow = {
mBundle: null,
@ -33,8 +35,9 @@ var gSmtpServerListWindow = {
onSelectionChanged(aEvent) {
var server = this.getSelectedServer();
if (!server)
if (!server) {
return;
}
this.updateButtons();
this.updateServerInfoBox(server);
@ -42,21 +45,34 @@ var gSmtpServerListWindow = {
onDeleteServer(aEvent) {
var server = this.getSelectedServer();
if (!server)
if (!server) {
return;
}
// confirm deletion
let cancel = Services.prompt.confirmEx(window,
let cancel = Services.prompt.confirmEx(
window,
this.mBundle.getString("smtpServers-confirmServerDeletionTitle"),
this.mBundle.getFormattedString("smtpServers-confirmServerDeletion",
[server.hostname], 1),
Services.prompt.STD_YES_NO_BUTTONS, null, null, null, null, { });
this.mBundle.getFormattedString(
"smtpServers-confirmServerDeletion",
[server.hostname],
1
),
Services.prompt.STD_YES_NO_BUTTONS,
null,
null,
null,
null,
{}
);
if (!cancel) {
// Remove password information first.
try {
server.forgetPassword();
} catch (e) { /* It is OK if this fails. */ }
} catch (e) {
/* It is OK if this fails. */
}
// Remove the server.
MailServices.smtp.deleteServer(server);
parent.replaceWithDefaultSmtpServer(server.key);
@ -70,16 +86,18 @@ var gSmtpServerListWindow = {
onEditServer(aEvent) {
let server = this.getSelectedServer();
if (!server)
if (!server) {
return;
}
this.openServerEditor(server);
},
onSetDefaultServer(aEvent) {
let server = this.getSelectedServer();
if (!server)
if (!server) {
return;
}
MailServices.smtp.defaultServer = server;
this.refreshServerList(MailServices.smtp.defaultServer.key, true);
@ -97,22 +115,27 @@ var gSmtpServerListWindow = {
this.mDeleteButton.removeAttribute("disabled");
}
if (!server)
if (!server) {
this.mEditButton.setAttribute("disabled", "true");
else
} else {
this.mEditButton.removeAttribute("disabled");
}
},
updateServerInfoBox(aServer) {
var noneSelected = this.mBundle.getString("smtpServerList-NotSpecified");
document.getElementById("nameValue").value = aServer.hostname;
document.getElementById("descriptionValue").value = aServer.description || noneSelected;
document.getElementById("descriptionValue").value =
aServer.description || noneSelected;
document.getElementById("portValue").value = aServer.port;
document.getElementById("userNameValue").value = aServer.username || noneSelected;
document.getElementById("useSecureConnectionValue").value =
this.mBundle.getString("smtpServer-ConnectionSecurityType-" +
aServer.socketType);
document.getElementById("userNameValue").value =
aServer.username || noneSelected;
document.getElementById(
"useSecureConnectionValue"
).value = this.mBundle.getString(
"smtpServer-ConnectionSecurityType-" + aServer.socketType
);
const AuthMethod = Ci.nsMsgAuthMethod;
const SocketType = Ci.nsMsgSocketType;
@ -134,51 +157,67 @@ var gSmtpServerListWindow = {
authStr = "authAnySecure";
break;
case AuthMethod.passwordCleartext:
authStr = (aServer.socketType == SocketType.SSL ||
aServer.socketType == SocketType.alwaysSTARTTLS)
? "authPasswordCleartextViaSSL"
: "authPasswordCleartextInsecurely";
authStr =
aServer.socketType == SocketType.SSL ||
aServer.socketType == SocketType.alwaysSTARTTLS
? "authPasswordCleartextViaSSL"
: "authPasswordCleartextInsecurely";
break;
case AuthMethod.OAuth2:
authStr = "authOAuth2";
break;
default:
// leave empty
Cu.reportError("Warning: unknown value for smtpserver... authMethod: " +
aServer.authMethod);
Cu.reportError(
"Warning: unknown value for smtpserver... authMethod: " +
aServer.authMethod
);
}
if (authStr) {
document.getElementById("authMethodValue").value = this.mBundle.getString(
authStr
);
}
if (authStr)
document.getElementById("authMethodValue").value =
this.mBundle.getString(authStr);
},
refreshServerList(aServerKeyToSelect, aFocusList) {
// remove all children
while (this.mServerList.hasChildNodes())
while (this.mServerList.hasChildNodes()) {
this.mServerList.lastChild.remove();
}
this.fillSmtpServers(this.mServerList,
MailServices.smtp.servers,
MailServices.smtp.defaultServer);
this.fillSmtpServers(
this.mServerList,
MailServices.smtp.servers,
MailServices.smtp.defaultServer
);
if (aServerKeyToSelect)
this.setSelectedServer(this.mServerList.querySelector('[key="' + aServerKeyToSelect + '"]'));
else // select the default server
this.setSelectedServer(this.mServerList.querySelector('[default="true"]'));
if (aServerKeyToSelect) {
this.setSelectedServer(
this.mServerList.querySelector('[key="' + aServerKeyToSelect + '"]')
);
} // select the default server
else {
this.setSelectedServer(
this.mServerList.querySelector('[default="true"]')
);
}
if (aFocusList)
if (aFocusList) {
this.mServerList.focus();
}
},
fillSmtpServers(aListBox, aServers, aDefaultServer) {
if (!aListBox || !aServers)
if (!aListBox || !aServers) {
return;
}
while (aServers.hasMoreElements()) {
var server = aServers.getNext();
if (server instanceof Ci.nsISmtpServer) {
var isDefault = (aDefaultServer.key == server.key);
var isDefault = aDefaultServer.key == server.key;
var listitem = this.createSmtpListItem(server, isDefault);
aListBox.appendChild(listitem);
@ -190,10 +229,11 @@ var gSmtpServerListWindow = {
var listitem = document.createXULElement("richlistitem");
var serverName = "";
if (aServer.description)
if (aServer.description) {
serverName = aServer.description + " - ";
else if (aServer.username)
} else if (aServer.username) {
serverName = aServer.username + " - ";
}
serverName += aServer.hostname;
@ -217,20 +257,26 @@ var gSmtpServerListWindow = {
let args = editSMTPServer(aServer);
// now re-select the server which was just added
if (args.result)
if (args.result) {
this.refreshServerList(aServer ? aServer.key : args.addSmtpServer, true);
}
return args.result;
},
setSelectedServer(aServer) {
if (!aServer)
if (!aServer) {
return;
}
setTimeout(function(aServerList) {
aServerList.ensureElementIsVisible(aServer);
aServerList.selectItem(aServer);
}, 0, this.mServerList);
setTimeout(
function(aServerList) {
aServerList.ensureElementIsVisible(aServer);
aServerList.selectItem(aServer);
},
0,
this.mServerList
);
},
getSelectedServer() {
@ -238,8 +284,9 @@ var gSmtpServerListWindow = {
// therefore 1 item is always selected.
// But if there are no SMTP servers defined yet, nothing will be selected.
let selection = this.mServerList.selectedItem;
if (!selection)
if (!selection) {
return null;
}
let serverKey = selection.getAttribute("key");
return MailServices.smtp.getServerByKey(serverKey);

Просмотреть файл

@ -3,26 +3,31 @@
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
var {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm");
var {MailServices} = ChromeUtils.import("resource:///modules/MailServices.jsm");
var {MailUtils} = ChromeUtils.import("resource:///modules/MailUtils.jsm");
var {fixIterator} = ChromeUtils.import("resource:///modules/iteratorUtils.jsm");
var { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm");
var { MailServices } = ChromeUtils.import(
"resource:///modules/MailServices.jsm"
);
var { MailUtils } = ChromeUtils.import("resource:///modules/MailUtils.jsm");
var { fixIterator } = ChromeUtils.import(
"resource:///modules/iteratorUtils.jsm"
);
function BrowseForLocalFolders() {
const nsIFilePicker = Ci.nsIFilePicker;
const nsIFile = Ci.nsIFile;
var currentFolderTextBox = document.getElementById("server.localPath");
var fp = Cc["@mozilla.org/filepicker;1"]
.createInstance(nsIFilePicker);
var fp = Cc["@mozilla.org/filepicker;1"].createInstance(nsIFilePicker);
fp.init(window,
document.getElementById("browseForLocalFolder")
.getAttribute("filepickertitle"),
nsIFilePicker.modeGetFolder);
fp.init(
window,
document
.getElementById("browseForLocalFolder")
.getAttribute("filepickertitle"),
nsIFilePicker.modeGetFolder
);
var currentFolder = Cc["@mozilla.org/file/local;1"]
.createInstance(nsIFile);
var currentFolder = Cc["@mozilla.org/file/local;1"].createInstance(nsIFile);
currentFolder.initWithPath(currentFolderTextBox.value);
fp.displayDirectory = currentFolder;
@ -34,8 +39,9 @@ function BrowseForLocalFolders() {
let selectedFolder = fp.file;
// Check if the folder can be used for mail storage.
if (!top.checkDirectoryIsUsable(selectedFolder))
if (!top.checkDirectoryIsUsable(selectedFolder)) {
return;
}
currentFolderTextBox.value = selectedFolder.path;
});
@ -49,13 +55,16 @@ function BrowseForLocalFolders() {
* Otherwise return the name as "<foldername> on <servername>".
*/
function prettyFolderName(aTargetFolder) {
if (aTargetFolder.isServer)
if (aTargetFolder.isServer) {
return aTargetFolder.prettyName;
}
return document.getElementById("bundle_messenger")
.getFormattedString("verboseFolderFormat",
[aTargetFolder.prettyName,
aTargetFolder.server.prettyName]);
return document
.getElementById("bundle_messenger")
.getFormattedString("verboseFolderFormat", [
aTargetFolder.prettyName,
aTargetFolder.server.prettyName,
]);
}
/**
@ -77,8 +86,9 @@ function checkJunkTargetFolder(aTargetURI, aIsServer) {
}
// If the target server has deferred storage, Junk can't be stored into it.
if (targetServer.rootFolder != targetServer.rootMsgFolder)
if (targetServer.rootFolder != targetServer.rootMsgFolder) {
return null;
}
} catch (e) {
return null;
}
@ -100,12 +110,17 @@ function chooseJunkTargetFolder(aTargetURI, aIsServer) {
if (aTargetURI) {
server = MailUtils.getOrCreateFolder(aTargetURI).server;
if (!server.canCreateFoldersOnServer || !server.canSearchMessages ||
(server.rootFolder != server.rootMsgFolder))
if (
!server.canCreateFoldersOnServer ||
!server.canSearchMessages ||
server.rootFolder != server.rootMsgFolder
) {
server = null;
}
}
if (!server)
if (!server) {
server = MailServices.accounts.localFoldersServer;
}
return server.serverURI + (!aIsServer ? "/Junk" : "");
}
@ -128,36 +143,46 @@ function chooseJunkTargetFolder(aTargetURI, aIsServer) {
* newTargetAccount new safe junk target folder
* newMoveOnSpam new moveOnSpam value
*/
function sanitizeJunkTargets(aSpamActionTargetAccount,
aSpamActionTargetFolder,
aProposedTarget,
aMoveTargetModeValue,
aServerSpamSettings,
aMoveOnSpam) {
function sanitizeJunkTargets(
aSpamActionTargetAccount,
aSpamActionTargetFolder,
aProposedTarget,
aMoveTargetModeValue,
aServerSpamSettings,
aMoveOnSpam
) {
// Check if folder targets are valid.
aSpamActionTargetAccount = checkJunkTargetFolder(aSpamActionTargetAccount, true);
aSpamActionTargetAccount = checkJunkTargetFolder(
aSpamActionTargetAccount,
true
);
if (!aSpamActionTargetAccount) {
// If aSpamActionTargetAccount is not valid,
// reset to default behavior to NOT move junk messages...
if (aMoveTargetModeValue == aServerSpamSettings.MOVE_TARGET_MODE_ACCOUNT)
if (aMoveTargetModeValue == aServerSpamSettings.MOVE_TARGET_MODE_ACCOUNT) {
aMoveOnSpam = false;
}
// ... and find a good default target.
aSpamActionTargetAccount = chooseJunkTargetFolder(aProposedTarget, true);
}
aSpamActionTargetFolder = checkJunkTargetFolder(aSpamActionTargetFolder, false);
aSpamActionTargetFolder = checkJunkTargetFolder(
aSpamActionTargetFolder,
false
);
if (!aSpamActionTargetFolder) {
// If aSpamActionTargetFolder is not valid,
// reset to default behavior to NOT move junk messages...
if (aMoveTargetModeValue == aServerSpamSettings.MOVE_TARGET_MODE_FOLDER)
if (aMoveTargetModeValue == aServerSpamSettings.MOVE_TARGET_MODE_FOLDER) {
aMoveOnSpam = false;
}
// ... and find a good default target.
aSpamActionTargetFolder = chooseJunkTargetFolder(aProposedTarget, false);
}
return [ aSpamActionTargetAccount, aSpamActionTargetFolder, aMoveOnSpam ];
return [aSpamActionTargetAccount, aSpamActionTargetFolder, aMoveOnSpam];
}
/**
@ -169,19 +194,28 @@ function sanitizeJunkTargets(aSpamActionTargetAccount,
* @param aTBOtherArgs Other arguments to send to the pref tab.
* @param aSMPaneId Seamonkey pref pane to open.
*/
function openPrefsFromAccountManager(aTBPaneId, aTBScrollPaneTo, aTBOtherArgs, aSMPaneId) {
let win = Services.wm.getMostRecentWindow("mail:3pane") ||
Services.wm.getMostRecentWindow("mail:messageWindow") ||
Services.wm.getMostRecentWindow("msgcompose");
if (!win)
function openPrefsFromAccountManager(
aTBPaneId,
aTBScrollPaneTo,
aTBOtherArgs,
aSMPaneId
) {
let win =
Services.wm.getMostRecentWindow("mail:3pane") ||
Services.wm.getMostRecentWindow("mail:messageWindow") ||
Services.wm.getMostRecentWindow("msgcompose");
if (!win) {
return;
}
// If openOptionsDialog() exists, we are in Thunderbird.
if (typeof win.openOptionsDialog == "function")
if (typeof win.openOptionsDialog == "function") {
win.openOptionsDialog(aTBPaneId, aTBScrollPaneTo, aTBOtherArgs);
}
// If goPreferences() exists, we are in Seamonkey.
if (typeof win.goPreferences == "function")
if (typeof win.goPreferences == "function") {
win.goPreferences(aSMPaneId);
}
}
/**
@ -192,10 +226,15 @@ function openPrefsFromAccountManager(aTBPaneId, aTBScrollPaneTo, aTBOtherArgs, a
* searching the name. If unset, do not skip any account.
*/
function accountNameExists(aAccountName, aAccountKey) {
for (let account of fixIterator(MailServices.accounts.accounts,
Ci.nsIMsgAccount)) {
if (account.key != aAccountKey && account.incomingServer &&
aAccountName == account.incomingServer.prettyName) {
for (let account of fixIterator(
MailServices.accounts.accounts,
Ci.nsIMsgAccount
)) {
if (
account.key != aAccountKey &&
account.incomingServer &&
aAccountName == account.incomingServer.prettyName
) {
return true;
}
}
@ -211,12 +250,14 @@ function accountNameExists(aAccountName, aAccountKey) {
* was clicked and addSmtpServer with key of newly created server.
*/
function editSMTPServer(aServer) {
let args = { server: aServer,
result: false,
addSmtpServer: "" };
let args = { server: aServer, result: false, addSmtpServer: "" };
window.openDialog("chrome://messenger/content/SmtpServerEdit.xul",
"smtpEdit", "chrome,titlebar,modal,centerscreen", args);
window.openDialog(
"chrome://messenger/content/SmtpServerEdit.xul",
"smtpEdit",
"chrome,titlebar,modal,centerscreen",
args
);
return args;
}

Просмотреть файл

@ -13,8 +13,9 @@ function acctNamePageValidate() {
// Check if this accountname already exists. If so, return false so that
// user can enter a different unique account name.
if (canAdvance && accountNameExists(accountname))
if (canAdvance && accountNameExists(accountname)) {
canAdvance = false;
}
document.documentElement.canAdvance = canAdvance;
}
@ -29,18 +30,19 @@ function acctNamePageUnload() {
}
function acctNamePageInit() {
gPrefsBundle = document.getElementById("bundle_prefs");
var accountNameInput = document.getElementById("prettyName");
if (accountNameInput.value == "") {
var pageData = parent.GetPageData();
var type = parent.getCurrentServerType(pageData);
var accountName;
gPrefsBundle = document.getElementById("bundle_prefs");
var accountNameInput = document.getElementById("prettyName");
if (accountNameInput.value == "") {
var pageData = parent.GetPageData();
var type = parent.getCurrentServerType(pageData);
var accountName;
if (type == "nntp")
accountName = pageData.newsserver.hostname.value;
else
accountName = pageData.identity.email.value;
accountNameInput.value = accountName;
if (type == "nntp") {
accountName = pageData.newsserver.hostname.value;
} else {
accountName = pageData.identity.email.value;
}
acctNamePageValidate();
accountNameInput.value = accountName;
}
acctNamePageValidate();
}

Просмотреть файл

@ -20,9 +20,9 @@ function setAccountTypeData() {
}
function acctTypePageUnload() {
setAccountTypeData();
setupWizardPanels();
return true;
setAccountTypeData();
setupWizardPanels();
return true;
}
function setupWizardPanels() {
@ -40,10 +40,16 @@ function setupWizardPanels() {
let isMailAccount = pageData.accounttype.mailaccount;
let isNewsAccount = pageData.accounttype.newsaccount;
if (isMailAccount && isMailAccount.value) {
wizardPanels = ["identitypage", "incomingpage", "outgoingpage", "accnamepage"];
wizardPanels = [
"identitypage",
"incomingpage",
"outgoingpage",
"accnamepage",
];
} else if (isNewsAccount && isNewsAccount.value) {
wizardPanels = ["identitypage", "newsserver", "accnamepage"];
} else { // An account created by an extension and XUL overlays
} else {
// An account created by an extension and XUL overlays
let pages = document.getElementById("acctyperadio").selectedItem.value;
if (pages == "movemail") {
wizardPanels = ["identitypage", "outgoingpage", "accnamepage"];
@ -57,11 +63,11 @@ function setupWizardPanels() {
wizardPanels.push("done");
// Set up order of panels
for (let i = 0; i < (wizardPanels.length - 1); i++)
for (let i = 0; i < wizardPanels.length - 1; i++) {
setNextPage(wizardPanels[i], wizardPanels[i + 1]);
}
// make the account type page go to the very first of our approved wizard panels...this is usually going to
// be accounttype --> identitypage unless we were configured to skip the identity page
setNextPage("accounttype", wizardPanels[0]);
}

Просмотреть файл

@ -5,7 +5,9 @@
/* import-globals-from AccountWizard.js */
var {MailServices} = ChromeUtils.import("resource:///modules/MailServices.jsm");
var { MailServices } = ChromeUtils.import(
"resource:///modules/MailServices.jsm"
);
var gPrefsBundle;
@ -14,8 +16,8 @@ function donePageInit() {
gPrefsBundle = document.getElementById("bundle_prefs");
// Find out if we need to hide details for incoming servers
var hideIncoming = pageData.server &&
pageData.server.servertype.value == "movemail";
var hideIncoming =
pageData.server && pageData.server.servertype.value == "movemail";
var email = "";
if (pageData.identity && pageData.identity.email) {
@ -25,20 +27,24 @@ function donePageInit() {
setDivTextFromForm("identity.email", email);
let userName = "";
if (pageData.login && pageData.login.username)
if (pageData.login && pageData.login.username) {
userName = pageData.login.username.value;
if (!userName && email)
}
if (!userName && email) {
userName = getUsernameFromEmail(email);
}
// Hide the "username" field if we don't want to show information
// on the incoming server.
setDivTextFromForm("server.username", hideIncoming ? null : userName);
let smtpUserName = "";
if (pageData.login && pageData.login.smtpusername)
if (pageData.login && pageData.login.smtpusername) {
smtpUserName = pageData.login.smtpusername.value;
if (!smtpUserName && email)
}
if (!smtpUserName && email) {
smtpUserName = getUsernameFromEmail(email);
}
setDivTextFromForm("smtpServer.username", smtpUserName);
if (pageData.accname && pageData.accname.prettyName) {
@ -57,7 +63,10 @@ function donePageInit() {
// Hide the incoming server name field if the user specified
// wizardHideIncoming in the ISP defaults file
setDivTextFromForm("server.name", hideIncoming ? null : incomingServerName);
setDivTextFromForm("server.port", pageData.server.port ? pageData.server.port.value : null);
setDivTextFromForm(
"server.port",
pageData.server.port ? pageData.server.port.value : null
);
let incomingServerType = "";
if (pageData.server && pageData.server.servertype) {
incomingServerType = pageData.server.servertype.value;
@ -68,8 +77,9 @@ function donePageInit() {
if (pageData.server && pageData.server.smtphostname) {
let smtpServer = MailServices.smtp.defaultServer;
smtpServerName = pageData.server.smtphostname.value;
if (!smtpServerName && smtpServer && smtpServer.hostname)
smtpServerName = smtpServer.hostname;
if (!smtpServerName && smtpServer && smtpServer.hostname) {
smtpServerName = smtpServer.hostname;
}
}
setDivTextFromForm("smtpServer.name", smtpServerName);
} else {
@ -81,8 +91,9 @@ function donePageInit() {
if (serverIsNntp(pageData)) {
let newsServerName = "";
if (pageData.newsserver && pageData.newsserver.hostname)
if (pageData.newsserver && pageData.newsserver.hostname) {
newsServerName = pageData.newsserver.hostname.value;
}
if (newsServerName) {
// No need to show username for news account
setDivTextFromForm("server.username", null);
@ -95,7 +106,7 @@ function donePageInit() {
var isPop = false;
if (pageData.server && pageData.server.servertype) {
isPop = (pageData.server.servertype.value == "pop3");
isPop = pageData.server.servertype.value == "pop3";
}
hideShowDownloadMsgsUI(isPop);
@ -108,7 +119,10 @@ function hideShowDownloadMsgsUI(isPop) {
var downloadMsgs = document.getElementById("downloadMsgs");
if (isPop) {
if (!Services.io.offline) {
if (window.opener.location.href == "chrome://messenger/content/messenger.xul") {
if (
window.opener.location.href ==
"chrome://messenger/content/messenger.xul"
) {
downloadMsgs.hidden = false;
return;
}
@ -131,8 +145,9 @@ function setDivTextFromForm(divid, value) {
// otherwise fill in the .text element
div = document.getElementById(divid + ".text");
if (!div)
if (!div) {
return;
}
// set the value
div.setAttribute("value", value);

Просмотреть файл

@ -14,7 +14,9 @@ function identityPageValidate() {
let email = document.getElementById("email").value.trim();
if (name && email) {
canAdvance = gCurrentDomain ? emailNameIsLegal(email) : emailNameAndDomainAreLegal(email);
canAdvance = gCurrentDomain
? emailNameIsLegal(email)
: emailNameAndDomainAreLegal(email);
if (gCurrentDomain && canAdvance) {
// For prefilled ISP data we must check if the account already exists as
@ -24,9 +26,12 @@ function identityPageValidate() {
var serverType = parent.getCurrentServerType(pageData);
var hostName = parent.getCurrentHostname(pageData);
var usernameWithDomain = email + "@" + gCurrentDomain;
if (parent.AccountExists(email, hostName, serverType) ||
parent.AccountExists(usernameWithDomain, hostName, serverType))
if (
parent.AccountExists(email, hostName, serverType) ||
parent.AccountExists(usernameWithDomain, hostName, serverType)
) {
canAdvance = false;
}
}
}
@ -87,8 +92,9 @@ function identityPageInit() {
function clearEmailTextItems() {
var emailDescText = document.getElementById("emailDescText");
if (emailDescText.hasChildNodes())
if (emailDescText.hasChildNodes()) {
emailDescText.firstChild.remove();
}
var postEmailText = document.getElementById("postEmailText");
postEmailText.setAttribute("value", "");
@ -99,30 +105,37 @@ function clearEmailTextItems() {
// for the choice user has made, will be read into CurrentAccountData.
// Default example data from properties will be used when the info is missing.
function setEmailDescriptionText() {
var emailDescText = document.getElementById("emailDescText");
var emailFieldLabel = document.getElementById("emailFieldLabel");
var emailDescText = document.getElementById("emailDescText");
var emailFieldLabel = document.getElementById("emailFieldLabel");
// Set the default field label
emailFieldLabel.setAttribute("value", gPrefsBundle.getString("emailFieldText"));
// Set the default field label
emailFieldLabel.setAttribute(
"value",
gPrefsBundle.getString("emailFieldText")
);
// Check for obtained values and set with default values if needed
var username = gPrefsBundle.getString("exampleEmailUserName");
var domain = gPrefsBundle.getString("exampleEmailDomain");
// Check for obtained values and set with default values if needed
var username = gPrefsBundle.getString("exampleEmailUserName");
var domain = gPrefsBundle.getString("exampleEmailDomain");
let displayText = gPrefsBundle.getFormattedString("defaultEmailText",
[username, domain]);
let displayText = gPrefsBundle.getFormattedString("defaultEmailText", [
username,
domain,
]);
// Create a text nodes with text to be displayed
var emailDescTextNode = document.createTextNode(displayText);
// Create a text nodes with text to be displayed
var emailDescTextNode = document.createTextNode(displayText);
// Display the dynamically generated text for email description
emailDescText.appendChild(emailDescTextNode);
// Display the dynamically generated text for email description
emailDescText.appendChild(emailDescTextNode);
}
function checkForFullName() {
var name = document.getElementById("fullName");
if (name.value == "" && "@mozilla.org/userinfo;1" in Cc) {
name.value = Cc["@mozilla.org/userinfo;1"].getService(Ci.nsIUserInfo).fullname;
name.value = Cc["@mozilla.org/userinfo;1"].getService(
Ci.nsIUserInfo
).fullname;
}
}
@ -133,6 +146,8 @@ function checkForEmail() {
email.value = pageData.identity.email.value;
}
if (email.value == "" && "@mozilla.org/userinfo;1" in Cc) {
email.value = Cc["@mozilla.org/userinfo;1"].getService(Ci.nsIUserInfo).emailAddress;
email.value = Cc["@mozilla.org/userinfo;1"].getService(
Ci.nsIUserInfo
).emailAddress;
}
}

Просмотреть файл

@ -5,7 +5,9 @@
/* import-globals-from AccountWizard.js */
var {cleanUpHostName, isLegalHostNameOrIP} = ChromeUtils.import("resource:///modules/hostnameUtils.jsm");
var { cleanUpHostName, isLegalHostNameOrIP } = ChromeUtils.import(
"resource:///modules/hostnameUtils.jsm"
);
var gOnMailServersPage;
var gOnNewsServerPage;
@ -17,22 +19,27 @@ function incomingPageValidate() {
if (gOnMailServersPage) {
hostName = document.getElementById("incomingServer").value;
if (!isLegalHostNameOrIP(cleanUpHostName(hostName)))
if (!isLegalHostNameOrIP(cleanUpHostName(hostName))) {
canAdvance = false;
}
}
if (gOnNewsServerPage) {
hostName = document.getElementById("newsServer").value;
if (!isLegalHostNameOrIP(cleanUpHostName(hostName)))
if (!isLegalHostNameOrIP(cleanUpHostName(hostName))) {
canAdvance = false;
}
}
if (canAdvance) {
var pageData = parent.GetPageData();
var serverType = parent.getCurrentServerType(pageData);
var username = document.getElementById("username").value;
if (gProtocolInfo && gProtocolInfo.requiresUsername && !username ||
parent.AccountExists(username, hostName, serverType))
if (
(gProtocolInfo && gProtocolInfo.requiresUsername && !username) ||
parent.AccountExists(username, hostName, serverType)
) {
canAdvance = false;
}
}
document.documentElement.canAdvance = canAdvance;
@ -43,27 +50,39 @@ function incomingPageUnload() {
if (gOnMailServersPage) {
var incomingServerName = document.getElementById("incomingServer");
setPageData(pageData, "server", "hostname", cleanUpHostName(incomingServerName.value));
setPageData(
pageData,
"server",
"hostname",
cleanUpHostName(incomingServerName.value)
);
var serverport = document.getElementById("serverPort").value;
setPageData(pageData, "server", "port", serverport);
var username = document.getElementById("username").value;
setPageData(pageData, "login", "username", username);
} else if (gOnNewsServerPage) {
var newsServerName = document.getElementById("newsServer");
setPageData(pageData, "newsserver", "hostname", cleanUpHostName(newsServerName.value));
setPageData(
pageData,
"newsserver",
"hostname",
cleanUpHostName(newsServerName.value)
);
}
return true;
}
function incomingPageInit() {
gOnMailServersPage = (document.documentElement.currentPage.id == "incomingpage");
gOnNewsServerPage = (document.documentElement.currentPage.id == "newsserver");
gOnMailServersPage =
document.documentElement.currentPage.id == "incomingpage";
gOnNewsServerPage = document.documentElement.currentPage.id == "newsserver";
var pageData = parent.GetPageData();
if (gOnNewsServerPage) {
var newsServer = document.getElementById("newsServer");
if (pageData.newsserver && pageData.newsserver.hostname)
if (pageData.newsserver && pageData.newsserver.hostname) {
newsServer.value = pageData.newsserver.hostname.value;
}
}
var incomingServerbox = document.getElementById("incomingServerbox");
@ -93,10 +112,14 @@ function incomingPageInit() {
* we preset the server type radio group accordingly,
* otherwise, use pop3 as the default.
*/
var serverTypeRadioItem = document.getElementById(pageData.server &&
pageData.server.servertype && pageData.server.servertype.value == "imap" ?
"imap" : "pop3");
serverTypeRadioGroup.selectedItem = serverTypeRadioItem; // Set pop3 server type as default selection
var serverTypeRadioItem = document.getElementById(
pageData.server &&
pageData.server.servertype &&
pageData.server.servertype.value == "imap"
? "imap"
: "pop3"
);
serverTypeRadioGroup.selectedItem = serverTypeRadioItem; // Set pop3 server type as default selection
}
var leaveMessages = document.getElementById("leaveMessagesOnServer");
var deferStorage = document.getElementById("deferStorage");
@ -109,21 +132,25 @@ function incomingPageInit() {
if (pageData.server && pageData.server.hostname) {
var incomingServerTextBox = document.getElementById("incomingServer");
if (incomingServerTextBox && incomingServerTextBox.value == "")
if (incomingServerTextBox && incomingServerTextBox.value == "") {
incomingServerTextBox.value = pageData.server.hostname.value;
}
}
// pageData.server is not a real nsMsgIncomingServer so it does not have
// protocolInfo property implemented.
let type = parent.getCurrentServerType(pageData);
gProtocolInfo = Cc["@mozilla.org/messenger/protocol/info;1?type=" + type]
.getService(Ci.nsIMsgProtocolInfo);
gProtocolInfo = Cc[
"@mozilla.org/messenger/protocol/info;1?type=" + type
].getService(Ci.nsIMsgProtocolInfo);
var loginNameInput = document.getElementById("username");
if (loginNameInput.value == "") {
if (gProtocolInfo.requiresUsername) {
// since we require a username, use the uid from the email address
loginNameInput.value = parent.getUsernameFromEmail(pageData.identity.email.value);
loginNameInput.value = parent.getUsernameFromEmail(
pageData.identity.email.value
);
}
}
incomingPageValidate();

Просмотреть файл

@ -5,8 +5,12 @@
/* import-globals-from AccountWizard.js */
var {cleanUpHostName, isLegalHostNameOrIP} = ChromeUtils.import("resource:///modules/hostnameUtils.jsm");
var {MailServices} = ChromeUtils.import("resource:///modules/MailServices.jsm");
var { cleanUpHostName, isLegalHostNameOrIP } = ChromeUtils.import(
"resource:///modules/hostnameUtils.jsm"
);
var { MailServices } = ChromeUtils.import(
"resource:///modules/MailServices.jsm"
);
var gProtocolInfo = null;
var gPrefsBundle;
@ -16,8 +20,9 @@ function outgoingPageValidate() {
let smtpServer = document.getElementById("smtphostname").value;
let usingDefaultSMTP = document.getElementById("noSmtp").hidden;
if (!usingDefaultSMTP && !isLegalHostNameOrIP(cleanUpHostName(smtpServer)))
if (!usingDefaultSMTP && !isLegalHostNameOrIP(cleanUpHostName(smtpServer))) {
canAdvance = false;
}
document.documentElement.canAdvance = canAdvance;
}
@ -39,69 +44,71 @@ function outgoingPageUnload() {
}
function outgoingPageInit() {
gPrefsBundle = document.getElementById("bundle_prefs");
var pageData = parent.GetPageData();
gPrefsBundle = document.getElementById("bundle_prefs");
var pageData = parent.GetPageData();
var smtpServer = null;
var smtpServer = null;
// If we're reusing the default smtp we should not set the smtp hostname.
if (MailServices.smtp.defaultServer) {
smtpServer = MailServices.smtp.defaultServer;
setPageData(pageData, "identity", "smtpServerKey", "");
}
var noSmtpBox = document.getElementById("noSmtp");
var haveSmtpBox = document.getElementById("haveSmtp");
var boxToHide;
var boxToShow;
if (smtpServer && smtpServer.hostname) {
// we have a hostname, so modify and show the static text and
// store the value of the default smtp server in the textbox.
modifyStaticText(smtpServer.hostname, "1");
boxToShow = haveSmtpBox;
boxToHide = noSmtpBox;
} else {
// no default hostname yet
boxToShow = noSmtpBox;
boxToHide = haveSmtpBox;
}
if (boxToHide)
boxToHide.setAttribute("hidden", "true");
if (boxToShow)
boxToShow.removeAttribute("hidden");
var smtpNameInput = document.getElementById("smtpusername");
// If we're reusing the default smtp we should not set the smtp hostname.
if (MailServices.smtp.defaultServer) {
smtpServer = MailServices.smtp.defaultServer;
if (smtpServer && smtpServer.hostname && smtpServer.username) {
// we have a default SMTP server, so modify and show the static text
// and store the username for the default server in the textbox.
modifyStaticText(smtpServer.username, "2");
hideShowLoginSettings(2, 1, 3);
smtpNameInput.value = smtpServer.username;
setPageData(pageData, "identity", "smtpServerKey", "");
}
var noSmtpBox = document.getElementById("noSmtp");
var haveSmtpBox = document.getElementById("haveSmtp");
var boxToHide;
var boxToShow;
if (smtpServer && smtpServer.hostname) {
// we have a hostname, so modify and show the static text and
// store the value of the default smtp server in the textbox.
modifyStaticText(smtpServer.hostname, "1");
boxToShow = haveSmtpBox;
boxToHide = noSmtpBox;
} else {
// no default hostname yet
boxToShow = noSmtpBox;
boxToHide = haveSmtpBox;
}
if (boxToHide) {
boxToHide.setAttribute("hidden", "true");
}
if (boxToShow) {
boxToShow.removeAttribute("hidden");
}
var smtpNameInput = document.getElementById("smtpusername");
smtpServer = MailServices.smtp.defaultServer;
if (smtpServer && smtpServer.hostname && smtpServer.username) {
// we have a default SMTP server, so modify and show the static text
// and store the username for the default server in the textbox.
modifyStaticText(smtpServer.username, "2");
hideShowLoginSettings(2, 1, 3);
smtpNameInput.value = smtpServer.username;
} else {
// no default SMTP server yet, so need to compare
// incoming and outgoing server names
var smtpServerName = pageData.server.smtphostname.value;
var incomingServerName = pageData.server.hostname.value;
if (smtpServerName == incomingServerName) {
// incoming and outgoing server names are the same, so show
// the static text and make sure textbox blank for later tests.
modifyStaticText(smtpServerName, "3");
hideShowLoginSettings(3, 1, 2);
smtpNameInput.value = "";
} else {
// no default SMTP server yet, so need to compare
// incoming and outgoing server names
var smtpServerName = pageData.server.smtphostname.value;
var incomingServerName = pageData.server.hostname.value;
if (smtpServerName == incomingServerName) {
// incoming and outgoing server names are the same, so show
// the static text and make sure textbox blank for later tests.
modifyStaticText(smtpServerName, "3");
hideShowLoginSettings(3, 1, 2);
smtpNameInput.value = "";
} else {
// incoming and outgoing server names are different, so set smtp
// username's textbox to be the same as incoming's one, unless already set.
hideShowLoginSettings(1, 2, 3);
var loginNameInput = document.getElementById("username");
smtpNameInput.value = smtpNameInput.value || loginNameInput.value;
}
// incoming and outgoing server names are different, so set smtp
// username's textbox to be the same as incoming's one, unless already set.
hideShowLoginSettings(1, 2, 3);
var loginNameInput = document.getElementById("username");
smtpNameInput.value = smtpNameInput.value || loginNameInput.value;
}
outgoingPageValidate();
}
outgoingPageValidate();
}
function modifyStaticText(smtpMod, smtpBox) {
@ -109,30 +116,35 @@ function modifyStaticText(smtpMod, smtpBox) {
// smtp server so that the single string displays the hostname
// or username for the smtp server.
var smtpStatic = document.getElementById("smtpStaticText" + smtpBox);
if (smtpStatic && smtpStatic.hasChildNodes())
smtpStatic.childNodes[0].nodeValue = smtpStatic.getAttribute("prefix") +
smtpMod + smtpStatic.getAttribute("suffix");
if (smtpStatic && smtpStatic.hasChildNodes()) {
smtpStatic.childNodes[0].nodeValue =
smtpStatic.getAttribute("prefix") +
smtpMod +
smtpStatic.getAttribute("suffix");
}
}
function hideShowLoginSettings(aEle, bEle, cEle) {
document.getElementById("loginSet" + aEle).hidden = false;
document.getElementById("loginSet" + bEle).hidden = true;
document.getElementById("loginSet" + cEle).hidden = true;
document.getElementById("loginSet" + aEle).hidden = false;
document.getElementById("loginSet" + bEle).hidden = true;
document.getElementById("loginSet" + cEle).hidden = true;
}
var savedPassword = "";
function onSavePassword(target) {
dump("savePassword changed! (" + target.checked + ")\n");
var passwordField = document.getElementById("server.password");
if (!passwordField) return;
dump("savePassword changed! (" + target.checked + ")\n");
var passwordField = document.getElementById("server.password");
if (!passwordField) {
return;
}
if (target.checked) {
passwordField.removeAttribute("disabled");
passwordField.value = savedPassword;
} else {
passwordField.setAttribute("disabled", "true");
savedPassword = passwordField.value;
passwordField.value = "";
}
if (target.checked) {
passwordField.removeAttribute("disabled");
passwordField.value = savedPassword;
} else {
passwordField.setAttribute("disabled", "true");
savedPassword = passwordField.value;
passwordField.value = "";
}
}

Просмотреть файл

@ -7,12 +7,16 @@
* type conversion.
*/
var {MailUtils} = ChromeUtils.import("resource:///modules/MailUtils.jsm");
var {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm");
var {FileUtils} = ChromeUtils.import("resource://gre/modules/FileUtils.jsm");
var {Log} = ChromeUtils.import("resource://gre/modules/Log.jsm");
var {allAccountsSorted} = ChromeUtils.import("resource:///modules/folderUtils.jsm");
var MailstoreConverter = ChromeUtils.import("resource:///modules/mailstoreConverter.jsm");
var { MailUtils } = ChromeUtils.import("resource:///modules/MailUtils.jsm");
var { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm");
var { FileUtils } = ChromeUtils.import("resource://gre/modules/FileUtils.jsm");
var { Log } = ChromeUtils.import("resource://gre/modules/Log.jsm");
var { allAccountsSorted } = ChromeUtils.import(
"resource:///modules/folderUtils.jsm"
);
var MailstoreConverter = ChromeUtils.import(
"resource:///modules/mailstoreConverter.jsm"
);
var log = Log.repository.getLogger("MailStoreConverter");
// {nsIMsgIncomingServer} server for the account to be migrated.
@ -35,8 +39,9 @@ var gOriginalOffline;
function placeAccountName(aServer) {
gOriginalOffline = Services.io.offline;
let bundle = Services.strings
.createBundle("chrome://messenger/locale/converterDialog.properties");
let bundle = Services.strings.createBundle(
"chrome://messenger/locale/converterDialog.properties"
);
let brandShortName = Services.strings
.createBundle("chrome://branding/locale/brand.properties")
@ -53,12 +58,14 @@ function placeAccountName(aServer) {
let accounts = allAccountsSorted(true);
for (let account of accounts) {
if (account.incomingServer.rootFolder.filePath.path ==
deferredToRootFolder) {
if (
account.incomingServer.rootFolder.filePath.path == deferredToRootFolder
) {
// Other accounts may be deferred to this account.
deferredToAccount = account;
} else if (account.incomingServer.rootMsgFolder.filePath.path ==
deferredToRootFolder) {
} else if (
account.incomingServer.rootMsgFolder.filePath.path == deferredToRootFolder
) {
// This is a deferred account.
gDeferredAccounts.push(account);
}
@ -71,8 +78,10 @@ function placeAccountName(aServer) {
// Add account names to 'accountsToConvert' and 'deferredAccountsString'.
for (let i = 0; i < gDeferredAccounts.length; i++) {
if (i < gDeferredAccounts.length - 1) {
accountsToConvert += gDeferredAccounts[i].incomingServer.username + ", ";
deferredAccountsString += gDeferredAccounts[i].incomingServer.username + ", ";
accountsToConvert +=
gDeferredAccounts[i].incomingServer.username + ", ";
deferredAccountsString +=
gDeferredAccounts[i].incomingServer.username + ", ";
} else {
accountsToConvert += gDeferredAccounts[i].incomingServer.username;
deferredAccountsString += gDeferredAccounts[i].incomingServer.username;
@ -88,8 +97,9 @@ function placeAccountName(aServer) {
accountsToConvert += ", " + deferredToAccount.incomingServer.prettyName;
}
log.info(accountsToConvert + " will be converted");
let storeContractId = Services.prefs.getCharPref("mail.server." +
deferredToAccount.incomingServer.key + ".storeContractID");
let storeContractId = Services.prefs.getCharPref(
"mail.server." + deferredToAccount.incomingServer.key + ".storeContractID"
);
if (storeContractId == "@mozilla.org/msgstore/berkeleystore;1") {
storeContractId = "maildir";
@ -106,29 +116,47 @@ function placeAccountName(aServer) {
}
if (aServer.rootFolder.filePath.path != deferredToRootFolder) {
document.getElementById("warningSpan").textContent =
bundle.formatStringFromName(
"converterDialog.warningForDeferredAccount",
[aServer.username, deferredToAccountName, deferredToAccountName,
document.getElementById(
"warningSpan"
).textContent = bundle.formatStringFromName(
"converterDialog.warningForDeferredAccount",
[
aServer.username,
deferredToAccountName,
deferredToAccountName,
deferredAccountsString,
accountsToConvert, storeContractId, brandShortName]);
accountsToConvert,
storeContractId,
brandShortName,
]
);
} else {
document.getElementById("warningSpan").textContent =
bundle.formatStringFromName(
"converterDialog.warningForDeferredToAccount",
[deferredToAccountName,
document.getElementById(
"warningSpan"
).textContent = bundle.formatStringFromName(
"converterDialog.warningForDeferredToAccount",
[
deferredToAccountName,
deferredAccountsString,
accountsToConvert, storeContractId, brandShortName]);
accountsToConvert,
storeContractId,
brandShortName,
]
);
}
document.getElementById("messageSpan").textContent =
bundle.formatStringFromName("converterDialog.messageForDeferredAccount",
[accountsToConvert, storeContractId]);
document.getElementById(
"messageSpan"
).textContent = bundle.formatStringFromName(
"converterDialog.messageForDeferredAccount",
[accountsToConvert, storeContractId]
);
gServer = deferredToAccount.incomingServer;
} else {
// No account is deferred.
let storeContractId = Services.prefs.getCharPref(
"mail.server." + aServer.key + ".storeContractID");
"mail.server." + aServer.key + ".storeContractID"
);
if (storeContractId == "@mozilla.org/msgstore/berkeleystore;1") {
storeContractId = "maildir";
} else {
@ -142,12 +170,19 @@ function placeAccountName(aServer) {
tempName = aServer.hostName;
}
document.getElementById("warningSpan").textContent =
bundle.formatStringFromName("converterDialog.warning",
[tempName, storeContractId, brandShortName]);
document.getElementById("messageSpan").textContent =
bundle.formatStringFromName("converterDialog.message",
[tempName, storeContractId]);
document.getElementById(
"warningSpan"
).textContent = bundle.formatStringFromName("converterDialog.warning", [
tempName,
storeContractId,
brandShortName,
]);
document.getElementById(
"messageSpan"
).textContent = bundle.formatStringFromName("converterDialog.message", [
tempName,
storeContractId,
]);
gServer = aServer;
}
@ -164,13 +199,17 @@ function startContinue(aSelectedStoreType, aResponse) {
gResponse = aResponse;
gFolder = gServer.rootFolder.filePath;
let bundle = Services.strings
.createBundle("chrome://messenger/locale/converterDialog.properties");
let bundle = Services.strings.createBundle(
"chrome://messenger/locale/converterDialog.properties"
);
document.getElementById("progress").addEventListener("progress", function(e) {
document.getElementById("progress").value = e.detail;
document.getElementById("progressPrcnt").textContent =
bundle.formatStringFromName("converterDialog.percentDone", [e.detail]);
document.getElementById("progress").value = e.detail;
document.getElementById(
"progressPrcnt"
).textContent = bundle.formatStringFromName("converterDialog.percentDone", [
e.detail,
]);
});
document.getElementById("warning").setAttribute("hidden", "hidden");
@ -204,7 +243,7 @@ function startContinue(aSelectedStoreType, aResponse) {
document.getElementById("messageSpan").style.display = "none";
document.getElementById("errorSpan").style.display = "block";
gResponse.newRootFolder = null;
gResponse.newRootFolder = null;
// Revert prefs.
Services.prefs.setCharPref(p1, originalDirectoryPref);
@ -215,8 +254,9 @@ function startContinue(aSelectedStoreType, aResponse) {
}
Services.prefs.setCharPref(p5, originalStoreContractID);
Services.prefs.savePrefFile(null);
if (gServer.rootFolder.filePath.path != originalRootFolderPath)
if (gServer.rootFolder.filePath.path != originalRootFolderPath) {
gServer.rootFolder.filePath = new FileUtils.File(originalRootFolderPath);
}
Services.io.offline = gOriginalOffline;
}
@ -232,8 +272,10 @@ function startContinue(aSelectedStoreType, aResponse) {
for (let deferredAccount of gDeferredAccounts) {
let defServer = deferredAccount.incomingServer;
defServer.rootMsgFolder.filePath = new FileUtils.File(aVal);
Services.prefs.setCharPref("mail.server." + defServer.key +
".storeContractID", aSelectedStoreType);
Services.prefs.setCharPref(
"mail.server." + defServer.key + ".storeContractID",
aSelectedStoreType
);
}
Services.io.offline = gOriginalOffline;
@ -248,13 +290,15 @@ function startContinue(aSelectedStoreType, aResponse) {
* @param {nsIMsgFolder} aFolder - mbox folder that is to be checked.
*/
function canCompact(aFolder) {
if (aFolder.expungedBytes != 0)
if (aFolder.expungedBytes != 0) {
return true;
}
if (aFolder.hasSubFolders) {
let subFolders = aFolder.subFolders;
while (subFolders.hasMoreElements()) {
if (canCompact(subFolders.getNext().QueryInterface(Ci.nsIMsgFolder)))
if (canCompact(subFolders.getNext().QueryInterface(Ci.nsIMsgFolder))) {
return true;
}
}
}
return false;
@ -266,32 +310,45 @@ function startContinue(aSelectedStoreType, aResponse) {
// 2. Messages are moved out of some descendant folder of the folder.
// If the account root folder can be compacted, start the conversion after
// compacting it.
if (originalStoreContractID == "@mozilla.org/msgstore/berkeleystore;1"
&&
canCompact(gServer.rootFolder)) {
if (
originalStoreContractID == "@mozilla.org/msgstore/berkeleystore;1" &&
canCompact(gServer.rootFolder)
) {
let urlListener = {
OnStartRunningUrl(aUrl) {
},
OnStartRunningUrl(aUrl) {},
OnStopRunningUrl(aUrl, aExitCode) {
let pConvert = MailstoreConverter.convertMailStoreTo(originalStoreContractID,
gServer, document.getElementById("progress"));
pConvert.then(function(val) {
promiseResolved(val);
}).catch(function(reason) {
promiseRejected(reason);
});
let pConvert = MailstoreConverter.convertMailStoreTo(
originalStoreContractID,
gServer,
document.getElementById("progress")
);
pConvert
.then(function(val) {
promiseResolved(val);
})
.catch(function(reason) {
promiseRejected(reason);
});
},
};
gServer.rootFolder.compactAll(urlListener, null, gServer.type == "imap" ||
gServer.type == "nntp");
gServer.rootFolder.compactAll(
urlListener,
null,
gServer.type == "imap" || gServer.type == "nntp"
);
} else {
let pConvert = MailstoreConverter.convertMailStoreTo(originalStoreContractID,
gServer, document.getElementById("progress"));
pConvert.then(function(val) {
promiseResolved(val);
}).catch(function(reason) {
promiseRejected(reason);
});
let pConvert = MailstoreConverter.convertMailStoreTo(
originalStoreContractID,
gServer,
document.getElementById("progress")
);
pConvert
.then(function(val) {
promiseResolved(val);
})
.catch(function(reason) {
promiseRejected(reason);
});
}
}

Просмотреть файл

@ -3,8 +3,10 @@
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
var {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm");
var {MailServices} = ChromeUtils.import("resource:///modules/MailServices.jsm");
var { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm");
var { MailServices } = ChromeUtils.import(
"resource:///modules/MailServices.jsm"
);
var gServer;
var gDialog;
@ -17,8 +19,9 @@ function onLoad(event) {
gDialog = document.documentElement;
let bundle = document.getElementById("bundle_removeAccount");
let removeQuestion = bundle.getFormattedString("removeQuestion",
[gServer.prettyName]);
let removeQuestion = bundle.getFormattedString("removeQuestion", [
gServer.prettyName,
]);
document.getElementById("accountName").textContent = removeQuestion;
// Allow to remove account data if it has a local storage.
@ -32,10 +35,12 @@ function onLoad(event) {
// TODO: bug 77652, decide what to do for deferred accounts.
// And inform the user if the account localPath is outside the profile.
if ((gServer.isDeferredTo ||
(gServer instanceof Ci.nsIPop3IncomingServer &&
gServer.deferredToAccount)) ||
!profilePath.contains(localDirectory)) {
if (
gServer.isDeferredTo ||
(gServer instanceof Ci.nsIPop3IncomingServer &&
gServer.deferredToAccount) ||
!profilePath.contains(localDirectory)
) {
document.getElementById("removeData").disabled = true;
}
} else {
@ -54,16 +59,19 @@ function onLoad(event) {
function enableRemove() {
gDialog.getButton("accept").disabled =
(!document.getElementById("removeAccount").checked &&
!document.getElementById("removeData").checked);
!document.getElementById("removeAccount").checked &&
!document.getElementById("removeData").checked;
}
/**
* Show the local directory.
*/
function openLocalDirectory() {
let nsLocalFile = Components.Constructor("@mozilla.org/file/local;1",
"nsIFile", "initWithPath");
let nsLocalFile = Components.Constructor(
"@mozilla.org/file/local;1",
"nsIFile",
"initWithPath"
);
let localDir = gServer.localPath.path;
try {
new nsLocalFile(localDir).reveal();
@ -104,7 +112,9 @@ function removeAccount() {
try {
// Remove password information first.
account.incomingServer.forgetPassword();
} catch (e) { /* It is OK if this fails. */ }
} catch (e) {
/* It is OK if this fails. */
}
// Remove account
MailServices.accounts.removeAccount(account, removeData);
account = null;
@ -117,11 +127,13 @@ function removeAccount() {
window.arguments[0].result = false;
}
document.getElementById("status").selectedPanel =
document.getElementById("success");
document.getElementById("status").selectedPanel = document.getElementById(
"success"
);
} catch (ex) {
document.getElementById("status").selectedPanel =
document.getElementById("failure");
document.getElementById("status").selectedPanel = document.getElementById(
"failure"
);
Cu.reportError("Failure to remove account: " + ex);
window.arguments[0].result = false;
}
@ -130,8 +142,9 @@ function removeAccount() {
function onAccept(event) {
// If Cancel is disabled, we already tried to remove the account
// and can only close the dialog.
if (gDialog.getButton("cancel").disabled)
if (gDialog.getButton("cancel").disabled) {
return;
}
gDialog.getButton("accept").disabled = true;
gDialog.getButton("cancel").disabled = true;

Просмотреть файл

@ -3,7 +3,7 @@
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
var {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm");
var { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm");
var gAddButton;
var gRemoveButton;
@ -19,48 +19,52 @@ document.addEventListener("dialogextra1", onAddHeader);
document.addEventListener("dialogextra2", onRemoveHeader);
function onLoad() {
let hdrs = Services.prefs.getCharPref("mailnews.customHeaders");
gHeaderInputElement = document.getElementById("headerInput");
gHeaderInputElement.focus();
let hdrs = Services.prefs.getCharPref("mailnews.customHeaders");
gHeaderInputElement = document.getElementById("headerInput");
gHeaderInputElement.focus();
gHdrsList = document.getElementById("headerList");
gArrayHdrs = [];
gAddButton = document.getElementById("addButton");
gRemoveButton = document.getElementById("removeButton");
gHdrsList = document.getElementById("headerList");
gArrayHdrs = [];
gAddButton = document.getElementById("addButton");
gRemoveButton = document.getElementById("removeButton");
initializeDialog(hdrs);
updateAddButton(true);
updateRemoveButton();
initializeDialog(hdrs);
updateAddButton(true);
updateRemoveButton();
}
function initializeDialog(hdrs) {
if (hdrs) {
hdrs = hdrs.replace(/\s+/g, ""); // remove white spaces before splitting
hdrs = hdrs.replace(/\s+/g, ""); // remove white spaces before splitting
gArrayHdrs = hdrs.split(":");
for (var i = 0; i < gArrayHdrs.length; i++)
if (!gArrayHdrs[i])
gArrayHdrs.splice(i, 1); // remove any null elements
for (var i = 0; i < gArrayHdrs.length; i++) {
if (!gArrayHdrs[i]) {
gArrayHdrs.splice(i, 1);
}
} // remove any null elements
initializeRows();
}
}
function initializeRows() {
for (var i = 0; i < gArrayHdrs.length; i++)
for (var i = 0; i < gArrayHdrs.length; i++) {
addRow(TrimString(gArrayHdrs[i]));
}
}
function onTextInput() {
// enable the add button if the user has started to type text
updateAddButton((gHeaderInputElement.value == ""));
updateAddButton(gHeaderInputElement.value == "");
}
function onOk() {
if (gArrayHdrs.length) {
var hdrs;
if (gArrayHdrs.length == 1)
if (gArrayHdrs.length == 1) {
hdrs = gArrayHdrs;
else
} else {
hdrs = gArrayHdrs.join(": ");
}
Services.prefs.setCharPref("mailnews.customHeaders", hdrs);
// flush prefs to disk, in case we crash, to avoid dataloss and problems with filters that use the custom headers
Services.prefs.savePrefFile(null);
@ -68,14 +72,22 @@ function onOk() {
Services.prefs.clearUserPref("mailnews.customHeaders"); // clear the pref, no custom headers
}
window.arguments[0].selectedVal = gHdrsList.selectedItem ? gHdrsList.selectedItem.label : null;
window.arguments[0].selectedVal = gHdrsList.selectedItem
? gHdrsList.selectedItem.label
: null;
}
function customHeaderOverflow() {
var nsMsgSearchAttrib = Ci.nsMsgSearchAttrib;
if (gArrayHdrs.length >= (nsMsgSearchAttrib.kNumMsgSearchAttributes - nsMsgSearchAttrib.OtherHeader - 1)) {
if (!gFilterBundle)
if (
gArrayHdrs.length >=
nsMsgSearchAttrib.kNumMsgSearchAttributes -
nsMsgSearchAttrib.OtherHeader -
1
) {
if (!gFilterBundle) {
gFilterBundle = document.getElementById("bundle_filter");
}
var alertText = gFilterBundle.getString("customHeaderOverflow");
Services.prompt.alert(window, null, alertText);
@ -87,9 +99,11 @@ function customHeaderOverflow() {
function onAddHeader() {
var newHdr = TrimString(gHeaderInputElement.value);
if (!isRFC2822Header(newHdr)) { // if user entered an invalid rfc822 header field name, bail out.
if (!gCustomBundle)
if (!isRFC2822Header(newHdr)) {
// if user entered an invalid rfc822 header field name, bail out.
if (!gCustomBundle) {
gCustomBundle = document.getElementById("bundle_custom");
}
var alertText = gCustomBundle.getString("colonInHeaderName");
Services.prompt.alert(window, null, alertText);
@ -97,8 +111,9 @@ function onAddHeader() {
}
gHeaderInputElement.value = "";
if (!newHdr || customHeaderOverflow())
if (!newHdr || customHeaderOverflow()) {
return;
}
if (!duplicateHdrExists(newHdr)) {
gArrayHdrs[gArrayHdrs.length] = newHdr;
var newItem = addRow(newHdr);
@ -115,23 +130,27 @@ function isRFC2822Header(hdr) {
charCode = hdr.charCodeAt(i);
// 58 is for colon and 33 and 126 are us-ascii bounds that should be used for header field name, as per rfc2822
if (charCode < 33 || charCode == 58 || charCode > 126)
if (charCode < 33 || charCode == 58 || charCode > 126) {
return false;
}
}
return true;
}
function duplicateHdrExists(hdr) {
for (var i = 0; i < gArrayHdrs.length; i++) {
if (gArrayHdrs[i] == hdr)
if (gArrayHdrs[i] == hdr) {
return true;
}
}
return false;
}
function onRemoveHeader() {
var listitem = gHdrsList.selectedItems[0];
if (!listitem) return;
if (!listitem) {
return;
}
listitem.remove();
var selectedHdr = GetListItemAttributeStr(listitem);
for (let i = 0; i < gArrayHdrs.length; i++) {
@ -143,10 +162,11 @@ function onRemoveHeader() {
}
function GetListItemAttributeStr(listitem) {
if (listitem)
return TrimString(listitem.getAttribute("label"));
if (listitem) {
return TrimString(listitem.getAttribute("label"));
}
return "";
return "";
}
function addRow(newHdr) {
@ -155,22 +175,26 @@ function addRow(newHdr) {
function updateAddButton(aDisable) {
// only update the button if the disabled state changed
if (aDisable == gAddButton.disabled)
if (aDisable == gAddButton.disabled) {
return;
}
gAddButton.disabled = aDisable;
document.documentElement.defaultButton = aDisable ? "accept" : "extra1";
}
function updateRemoveButton() {
var headerSelected = (gHdrsList.selectedItems.length > 0);
var headerSelected = gHdrsList.selectedItems.length > 0;
gRemoveButton.disabled = !headerSelected;
if (gRemoveButton.disabled)
if (gRemoveButton.disabled) {
gHeaderInputElement.focus();
}
}
// Remove whitespace from both ends of a string
function TrimString(string) {
if (!string) return "";
if (!string) {
return "";
}
return string.trim();
}

Просмотреть файл

@ -5,10 +5,14 @@
/* import-globals-from searchTerm.js */
var {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm");
var {MailServices} = ChromeUtils.import("resource:///modules/MailServices.jsm");
var {MailUtils} = ChromeUtils.import("resource:///modules/MailUtils.jsm");
var {PluralForm} = ChromeUtils.import("resource://gre/modules/PluralForm.jsm");
var { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm");
var { MailServices } = ChromeUtils.import(
"resource:///modules/MailServices.jsm"
);
var { MailUtils } = ChromeUtils.import("resource:///modules/MailUtils.jsm");
var { PluralForm } = ChromeUtils.import(
"resource://gre/modules/PluralForm.jsm"
);
// The actual filter that we're editing if it is a _saved_ filter or prefill;
// void otherwise.
@ -25,12 +29,28 @@ var gCustomActions = null;
var gFilterType;
var gFilterPosition = 0;
var gFilterActionStrings = ["none", "movemessage", "setpriorityto", "deletemessage",
"markasread", "ignorethread", "watchthread", "markasflagged",
"label", "replytomessage", "forwardmessage", "stopexecution",
"deletefrompopserver", "leaveonpopserver", "setjunkscore",
"fetchfrompopserver", "copymessage", "addtagtomessage",
"ignoresubthread", "markasunread"];
var gFilterActionStrings = [
"none",
"movemessage",
"setpriorityto",
"deletemessage",
"markasread",
"ignorethread",
"watchthread",
"markasflagged",
"label",
"replytomessage",
"forwardmessage",
"stopexecution",
"deletefrompopserver",
"leaveonpopserver",
"setjunkscore",
"fetchfrompopserver",
"copymessage",
"addtagtomessage",
"ignoresubthread",
"markasunread",
];
// A temporary filter with the current state of actions in the UI.
var gTempFilter = null;
@ -40,9 +60,9 @@ var gActionListOrdered = null;
var gFilterEditorMsgWindow = null;
var nsMsgFilterAction = Ci.nsMsgFilterAction;
var nsMsgFilterType = Ci.nsMsgFilterType;
var nsIMsgRuleAction = Ci.nsIMsgRuleAction;
var nsMsgSearchScope = Ci.nsMsgSearchScope;
var nsMsgFilterType = Ci.nsMsgFilterType;
var nsIMsgRuleAction = Ci.nsIMsgRuleAction;
var nsMsgSearchScope = Ci.nsMsgSearchScope;
document.addEventListener("dialogaccept", onAccept);
@ -61,8 +81,9 @@ function filterEditorOnLoad() {
// the postPlugin filters cannot be applied to servers that are
// deferred, (you must define them on the deferredTo server instead).
let server = gFilterList.folder.server;
if (server.rootFolder != server.rootMsgFolder)
if (server.rootFolder != server.rootMsgFolder) {
gFilterTypeSelector.disableDeferredAccount();
}
}
if ("filterPosition" in args) {
@ -74,8 +95,9 @@ function filterEditorOnLoad() {
gFilter = window.arguments[0].filter;
initializeDialog(gFilter);
} else {
if (gFilterList)
setSearchScope(getScopeFromFilterList(gFilterList));
if (gFilterList) {
setSearchScope(getScopeFromFilterList(gFilterList));
}
// if doing prefill filter create a new filter and populate it.
if ("filterName" in args) {
gPreFillName = args.filterName;
@ -87,15 +109,18 @@ function filterEditorOnLoad() {
var term = gFilter.createTerm();
term.attrib = Ci.nsMsgSearchAttrib.Default;
if (("fieldName" in args) && args.fieldName) {
if ("fieldName" in args && args.fieldName) {
// fieldName should contain the name of the field in which to search,
// from nsMsgSearchTerm.cpp::SearchAttribEntryTable, e.g. "to" or "cc"
try {
term.attrib = term.getAttributeFromString(args.fieldName);
} catch (e) { /* Invalid string is fine, just ignore it. */ }
} catch (e) {
/* Invalid string is fine, just ignore it. */
}
}
if (term.attrib == Ci.nsMsgSearchAttrib.Default)
if (term.attrib == Ci.nsMsgSearchAttrib.Default) {
term.attrib = Ci.nsMsgSearchAttrib.Sender;
}
term.op = Ci.nsMsgSearchOp.Is;
term.booleanAnd = gSearchBooleanRadiogroup.value == "and";
@ -111,16 +136,19 @@ function filterEditorOnLoad() {
// the default action for news filters is Delete
// for everything else, it's MoveToFolder
var filterAction = gFilter.createAction();
filterAction.type = (getScopeFromFilterList(gFilterList) ==
nsMsgSearchScope.newsFilter) ?
nsMsgFilterAction.Delete : nsMsgFilterAction.MoveToFolder;
filterAction.type =
getScopeFromFilterList(gFilterList) == nsMsgSearchScope.newsFilter
? nsMsgFilterAction.Delete
: nsMsgFilterAction.MoveToFolder;
gFilter.appendAction(filterAction);
initializeDialog(gFilter);
} else if ("copiedFilter" in args) {
// we are copying a filter
let copiedFilter = args.copiedFilter;
let copiedName = gFilterBundle.getFormattedString("copyToNewFilterName",
[copiedFilter.filterName]);
let copiedName = gFilterBundle.getFormattedString(
"copyToNewFilterName",
[copiedFilter.filterName]
);
let newFilter = gFilterList.createFilter(copiedName);
// copy the actions
@ -131,8 +159,10 @@ function filterEditorOnLoad() {
// copy the search terms
for (let i = 0; i < copiedFilter.searchTerms.length; i++) {
let searchTerm = copiedFilter.searchTerms.queryElementAt(i,
Ci.nsIMsgSearchTerm);
let searchTerm = copiedFilter.searchTerms.queryElementAt(
i,
Ci.nsIMsgSearchTerm
);
let newTerm = newFilter.createTerm();
newTerm.attrib = searchTerm.attrib;
@ -162,7 +192,9 @@ function filterEditorOnLoad() {
if (!gFilter) {
// This is a new filter. Set to both Incoming and Manual contexts.
gFilterTypeSelector.setType(nsMsgFilterType.Incoming | nsMsgFilterType.Manual);
gFilterTypeSelector.setType(
nsMsgFilterType.Incoming | nsMsgFilterType.Manual
);
}
// in the case of a new filter, we may not have an action row yet.
@ -204,10 +236,13 @@ function onAccept(event) {
}
function duplicateFilterNameExists(filterName) {
if (gFilterList)
for (var i = 0; i < gFilterList.filterCount; i++)
if (filterName == gFilterList.getFilterAt(i).filterName)
if (gFilterList) {
for (var i = 0; i < gFilterList.filterCount; i++) {
if (filterName == gFilterList.getFilterAt(i).filterName) {
return true;
}
}
}
return false;
}
@ -254,27 +289,33 @@ function initializeFilterTypeSelector() {
getType() {
let type = nsMsgFilterType.None;
if (this.checkBoxManual.checked)
if (this.checkBoxManual.checked) {
type |= nsMsgFilterType.Manual;
}
if (this.checkBoxIncoming.checked) {
if (this.menulistIncoming.selectedItem == this.menuitemAfterPlugins) {
type |= nsMsgFilterType.PostPlugin;
} else if (getScopeFromFilterList(gFilterList) == nsMsgSearchScope.newsFilter) {
} else if (
getScopeFromFilterList(gFilterList) == nsMsgSearchScope.newsFilter
) {
type |= nsMsgFilterType.NewsRule;
} else {
type |= nsMsgFilterType.InboxRule;
}
}
if (this.checkBoxArchive.checked)
if (this.checkBoxArchive.checked) {
type |= nsMsgFilterType.Archive;
}
if (this.checkBoxOutgoing.checked)
if (this.checkBoxOutgoing.checked) {
type |= nsMsgFilterType.PostOutgoing;
}
if (this.checkBoxPeriodic.checked)
if (this.checkBoxPeriodic.checked) {
type |= nsMsgFilterType.Periodic;
}
return type;
},
@ -287,26 +328,32 @@ function initializeFilterTypeSelector() {
*/
setType(aType) {
// If there is no type (event) requested, force "when manually run"
if (aType == nsMsgFilterType.None)
if (aType == nsMsgFilterType.None) {
aType = nsMsgFilterType.Manual;
}
this.checkBoxManual.checked = aType & nsMsgFilterType.Manual;
this.checkBoxManual.checked = aType & nsMsgFilterType.Manual;
this.checkBoxIncoming.checked = aType & (nsMsgFilterType.PostPlugin |
nsMsgFilterType.Incoming);
this.checkBoxIncoming.checked =
aType & (nsMsgFilterType.PostPlugin | nsMsgFilterType.Incoming);
this.menulistIncoming.selectedItem = aType & nsMsgFilterType.PostPlugin ?
this.menuitemAfterPlugins : this.menuitemBeforePlugins;
this.menulistIncoming.selectedItem =
aType & nsMsgFilterType.PostPlugin
? this.menuitemAfterPlugins
: this.menuitemBeforePlugins;
this.checkBoxArchive.checked = aType & nsMsgFilterType.Archive;
this.checkBoxArchive.checked = aType & nsMsgFilterType.Archive;
this.checkBoxOutgoing.checked = aType & nsMsgFilterType.PostOutgoing;
this.checkBoxPeriodic.checked = aType & nsMsgFilterType.Periodic;
const periodMinutes = gFilterList.folder.server.getIntValue("periodicFilterRateMinutes");
document.getElementById("runPeriodic").label =
PluralForm.get(periodMinutes, gFilterBundle.getString("contextPeriodic.label"))
.replace("#1", periodMinutes);
const periodMinutes = gFilterList.folder.server.getIntValue(
"periodicFilterRateMinutes"
);
document.getElementById("runPeriodic").label = PluralForm.get(
periodMinutes,
gFilterBundle.getString("contextPeriodic.label")
).replace("#1", periodMinutes);
this.updateClassificationMenu();
},
@ -338,17 +385,26 @@ function initializeDialog(filter) {
for (let actionIndex = 0; actionIndex < numActions; actionIndex++) {
let filterAction = filter.getActionAt(actionIndex);
let newActionRow = document.createXULElement("richlistitem", { "is": "ruleaction-richlistitem" });
let newActionRow = document.createXULElement("richlistitem", {
is: "ruleaction-richlistitem",
});
newActionRow.setAttribute("initialActionIndex", actionIndex);
newActionRow.className = "ruleaction";
gFilterActionList.appendChild(newActionRow);
newActionRow.setAttribute("value",
filterAction.type == nsMsgFilterAction.Custom ?
filterAction.customId : gFilterActionStrings[filterAction.type]);
newActionRow.setAttribute(
"value",
filterAction.type == nsMsgFilterAction.Custom
? filterAction.customId
: gFilterActionStrings[filterAction.type]
);
newActionRow.setAttribute("onfocus", "this.storeFocus();");
}
var gSearchScope = getFilterScope(getScope(filter), filter.filterType, filter.filterList);
var gSearchScope = getFilterScope(
getScope(filter),
filter.filterType,
filter.filterList
);
initializeSearchRows(gSearchScope, filter.searchTerms);
setFilterScope(filter.filterType, filter.filterList);
}
@ -356,7 +412,9 @@ function initializeDialog(filter) {
function ensureActionRow() {
// make sure we have at least one action row visible to the user
if (!gFilterActionList.getRowCount()) {
let newActionRow = document.createXULElement("richlistitem", { "is": "ruleaction-richlistitem" });
let newActionRow = document.createXULElement("richlistitem", {
is: "ruleaction-richlistitem",
});
newActionRow.className = "ruleaction";
gFilterActionList.appendChild(newActionRow);
newActionRow.mRemoveButton.disabled = true;
@ -367,9 +425,11 @@ function ensureActionRow() {
function saveFilter() {
// See if at least one filter type (activation event) is selected.
if (gFilterType == nsMsgFilterType.None) {
Services.prompt.alert(window,
gFilterBundle.getString("mustHaveFilterTypeTitle"),
gFilterBundle.getString("mustHaveFilterTypeMessage"));
Services.prompt.alert(
window,
gFilterBundle.getString("mustHaveFilterTypeTitle"),
gFilterBundle.getString("mustHaveFilterTypeMessage")
);
return false;
}
@ -378,60 +438,103 @@ function saveFilter() {
// have an original filter name (i.e. we are editing a filter), then
// we must check that the original is not the current as that is what
// the duplicateFilterNameExists function will have picked up.
if ((!gFilter || gFilter.filterName != filterName) && duplicateFilterNameExists(filterName)) {
Services.prompt.alert(window,
gFilterBundle.getString("cannotHaveDuplicateFilterTitle"),
gFilterBundle.getString("cannotHaveDuplicateFilterMessage"));
if (
(!gFilter || gFilter.filterName != filterName) &&
duplicateFilterNameExists(filterName)
) {
Services.prompt.alert(
window,
gFilterBundle.getString("cannotHaveDuplicateFilterTitle"),
gFilterBundle.getString("cannotHaveDuplicateFilterMessage")
);
return false;
}
// Check that all of the search attributes and operators are valid.
function rule_desc(index, obj) {
return (index + 1) + " (" + obj.searchattribute.label + ", " + obj.searchoperator.label + ")";
return (
index +
1 +
" (" +
obj.searchattribute.label +
", " +
obj.searchoperator.label +
")"
);
}
let invalidRule = false;
for (let index = 0; index < gSearchTerms.length; index++) {
let obj = gSearchTerms[index].obj;
// We don't need to check validity of matchAll terms
if (obj.matchAll)
if (obj.matchAll) {
continue;
}
// the term might be an offscreen one that we haven't initialized yet
let searchTerm = obj.searchTerm;
if (!searchTerm && !gSearchTerms[index].initialized)
if (!searchTerm && !gSearchTerms[index].initialized) {
continue;
}
if (isNaN(obj.searchattribute.value)) { // is this a custom term?
let customTerm = MailServices.filters.getCustomTerm(obj.searchattribute.value);
if (isNaN(obj.searchattribute.value)) {
// is this a custom term?
let customTerm = MailServices.filters.getCustomTerm(
obj.searchattribute.value
);
if (!customTerm) {
invalidRule = true;
Cu.reportError("Filter not saved because custom search term '" +
obj.searchattribute.value + "' in rule " + rule_desc(index, obj) + " not found");
} else if (!customTerm.getAvailable(obj.searchScope, obj.searchattribute.value)) {
invalidRule = true;
Cu.reportError("Filter not saved because custom search term '" +
customTerm.name + "' in rule " + rule_desc(index, obj) + " not available");
}
Cu.reportError(
"Filter not saved because custom search term '" +
obj.searchattribute.value +
"' in rule " +
rule_desc(index, obj) +
" not found"
);
} else if (
!customTerm.getAvailable(obj.searchScope, obj.searchattribute.value)
) {
invalidRule = true;
Cu.reportError(
"Filter not saved because custom search term '" +
customTerm.name +
"' in rule " +
rule_desc(index, obj) +
" not available"
);
}
} else {
let otherHeader = Ci.nsMsgSearchAttrib.OtherHeader;
let attribValue = (obj.searchattribute.value > otherHeader) ?
otherHeader : obj.searchattribute.value;
if (!obj.searchattribute
.validityTable
.getAvailable(attribValue, obj.searchoperator.value)) {
let attribValue =
obj.searchattribute.value > otherHeader
? otherHeader
: obj.searchattribute.value;
if (
!obj.searchattribute.validityTable.getAvailable(
attribValue,
obj.searchoperator.value
)
) {
invalidRule = true;
Cu.reportError("Filter not saved because standard search term '" +
attribValue + "' in rule " + rule_desc(index, obj) + " not available in this context");
Cu.reportError(
"Filter not saved because standard search term '" +
attribValue +
"' in rule " +
rule_desc(index, obj) +
" not available in this context"
);
}
}
if (invalidRule) {
Services.prompt.alert(window,
gFilterBundle.getString("searchTermsInvalidTitle"),
gFilterBundle.getFormattedString("searchTermsInvalidRule",
[obj.searchattribute.label,
obj.searchoperator.label]));
Services.prompt.alert(
window,
gFilterBundle.getString("searchTermsInvalidTitle"),
gFilterBundle.getFormattedString("searchTermsInvalidRule", [
obj.searchattribute.label,
obj.searchoperator.label,
])
);
return false;
}
}
@ -440,8 +543,9 @@ function saveFilter() {
// if any of the actions is invalid...
for (let index = 0; index < gFilterActionList.itemCount; index++) {
var listItem = gFilterActionList.getItemAtIndex(index);
if (!listItem.validateAction())
if (!listItem.validateAction()) {
return false;
}
}
// if we made it here, all of the actions are valid, so go ahead and save the filter
@ -467,12 +571,14 @@ function saveFilter() {
}
// add each filteraction to the filter
for (let index = 0; index < gFilterActionList.itemCount; index++)
for (let index = 0; index < gFilterActionList.itemCount; index++) {
gFilterActionList.getItemAtIndex(index).saveToFilter(gFilter);
}
// If we do not have a filter name at this point, generate one.
if (!gFilter.filterName)
if (!gFilter.filterName) {
AssignMeaningfulName();
}
gFilter.filterType = gFilterType;
saveSearchTerms(gFilter.searchTerms, gFilter);
@ -501,13 +607,15 @@ function checkActionsReorder() {
*/
function _checkActionsReorder() {
// Create a temporary disposable filter and add current actions to it.
if (!gTempFilter)
if (!gTempFilter) {
gTempFilter = gFilterList.createFilter("");
else
} else {
gTempFilter.clearActionList();
}
for (let index = 0; index < gFilterActionList.itemCount; index++)
for (let index = 0; index < gFilterActionList.itemCount; index++) {
gFilterActionList.getItemAtIndex(index).saveToFilter(gTempFilter);
}
// Now get the actions out of the filter in the order they will be executed in.
gActionListOrdered = gTempFilter.sortedActionList;
@ -515,8 +623,12 @@ function _checkActionsReorder() {
// Compare the two lists.
let statusBar = document.getElementById("statusbar");
for (let index = 0; index < gActionListOrdered.length; index++) {
if (index != gTempFilter.getActionIndex(
gActionListOrdered.queryElementAt(index, nsIMsgRuleAction))) {
if (
index !=
gTempFilter.getActionIndex(
gActionListOrdered.queryElementAt(index, nsIMsgRuleAction)
)
) {
// If the lists are not the same unhide the status bar and show warning.
statusBar.style.visibility = "visible";
return;
@ -559,16 +671,27 @@ function showActionsOrder() {
let actionList = gFilterBundle.getString("filterActionOrderExplanation");
for (let i = 0; i < gActionListOrdered.length; i++) {
let actionIndex = gTempFilter.getActionIndex(
gActionListOrdered.queryElementAt(i, nsIMsgRuleAction));
gActionListOrdered.queryElementAt(i, nsIMsgRuleAction)
);
let action = actionStrings[actionIndex];
actionList += gFilterBundle.getFormattedString("filterActionItem",
[(i + 1), action.label, action.argument]);
actionList += gFilterBundle.getFormattedString("filterActionItem", [
i + 1,
action.label,
action.argument,
]);
}
Services.prompt.confirmEx(window,
gFilterBundle.getString("filterActionOrderTitle"),
actionList, Services.prompt.BUTTON_TITLE_OK,
null, null, null, null, {value: false});
Services.prompt.confirmEx(
window,
gFilterBundle.getString("filterActionOrderTitle"),
actionList,
Services.prompt.BUTTON_TITLE_OK,
null,
null,
null,
null,
{ value: false }
);
}
function AssignMeaningfulName() {
@ -604,10 +727,11 @@ function AssignMeaningfulName() {
case attribs.HasAttachmentStatus:
case attribs.JunkStatus:
case attribs.JunkScoreOrigin:
if (activeItem)
if (activeItem) {
value = activeItem.label;
else
} else {
value = "";
}
break;
default:
@ -625,8 +749,13 @@ function AssignMeaningfulName() {
// If at this point stub is empty, we know that this is not a Match All Filter
// and is not an "untitledFilterName" Filter, so assign it a name using
// a string format from the Filter Bundle.
if (!stub)
stub = gFilterBundle.getFormattedString("filterAutoNameStr", [term, operator, value]);
if (!stub) {
stub = gFilterBundle.getFormattedString("filterAutoNameStr", [
term,
operator,
value,
]);
}
}
// Whatever name we have used, 'uniquify' it.
@ -648,7 +777,9 @@ function GetFilterEditorMsgWindow() {
if (!gFilterEditorMsgWindow) {
var msgWindowContractID = "@mozilla.org/messenger/msgwindow;1";
var nsIMsgWindow = Ci.nsIMsgWindow;
gFilterEditorMsgWindow = Cc[msgWindowContractID].createInstance(nsIMsgWindow);
gFilterEditorMsgWindow = Cc[msgWindowContractID].createInstance(
nsIMsgWindow
);
gFilterEditorMsgWindow.domWindow = window;
gFilterEditorMsgWindow.rootDocShell.appType = Ci.nsIDocShell.APP_TYPE_MAIL;
}
@ -661,15 +792,15 @@ function SetBusyCursor(window, enable) {
// is a non-chrome window, so check if this window has a
// setCursor method
if ("setCursor" in window) {
if (enable)
window.setCursor("wait");
else
window.setCursor("auto");
if (enable) {
window.setCursor("wait");
} else {
window.setCursor("auto");
}
}
}
} // suite/components/helpviewer/content/contextHelp.js
/* globals openHelp */// suite/components/helpviewer/content/contextHelp.js
function doHelpButton() {
/* globals openHelp */ function doHelpButton() {
openHelp("mail-filters");
}
@ -677,9 +808,11 @@ function getCustomActions() {
if (!gCustomActions) {
gCustomActions = [];
let customActionsEnum = MailServices.filters.getCustomActions();
while (customActionsEnum.hasMoreElements())
gCustomActions.push(customActionsEnum.getNext().QueryInterface(
Ci.nsIMsgFilterCustomAction));
while (customActionsEnum.hasMoreElements()) {
gCustomActions.push(
customActionsEnum.getNext().QueryInterface(Ci.nsIMsgFilterCustomAction)
);
}
}
}
@ -688,15 +821,22 @@ function updateFilterType() {
setFilterScope(gFilterType, gFilterList);
// set valid actions
var ruleActions = gFilterActionList.getElementsByAttribute("class", "ruleaction");
for (var i = 0; i < ruleActions.length; i++)
var ruleActions = gFilterActionList.getElementsByAttribute(
"class",
"ruleaction"
);
for (var i = 0; i < ruleActions.length; i++) {
ruleActions[i].mRuleActionType.hideInvalidActions();
}
}
// Given a filter type, set the global search scope to the filter scope
function setFilterScope(aFilterType, aFilterList) {
let filterScope = getFilterScope(getScopeFromFilterList(aFilterList),
aFilterType, aFilterList);
let filterScope = getFilterScope(
getScopeFromFilterList(aFilterList),
aFilterType,
aFilterList
);
setSearchScope(filterScope);
}
@ -706,13 +846,15 @@ function setFilterScope(aFilterType, aFilterList) {
// hierarchy of contexts, with incoming the most restrictive,
// followed by manual and post-plugin.
function getFilterScope(aServerFilterScope, aFilterType, aFilterList) {
if (aFilterType & nsMsgFilterType.Incoming)
if (aFilterType & nsMsgFilterType.Incoming) {
return aServerFilterScope;
}
// Manual or PostPlugin
// local mail allows body and junk types
if (aServerFilterScope == nsMsgSearchScope.offlineMailFilter)
if (aServerFilterScope == nsMsgSearchScope.offlineMailFilter) {
return nsMsgSearchScope.offlineMail;
}
// IMAP and NEWS online don't allow body
return nsMsgSearchScope.onlineManual;
}
@ -722,10 +864,12 @@ function getFilterScope(aServerFilterScope, aFilterType, aFilterList) {
*/
function setLastActionFocus() {
let lastAction = gFilterActionList.getAttribute("focusedAction");
if (!lastAction || lastAction < 0)
if (!lastAction || lastAction < 0) {
lastAction = 0;
if (lastAction >= gFilterActionList.itemCount)
}
if (lastAction >= gFilterActionList.itemCount) {
lastAction = gFilterActionList.itemCount - 1;
}
gFilterActionList.getItemAtIndex(lastAction).mRuleActionType.focus();
}

Некоторые файлы не были показаны из-за слишком большого количества измененных файлов Показать больше