/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
/* 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/. */
var EXPORTED_SYMBOLS = ["PlacesUIUtils"];
const {XPCOMUtils} = ChromeUtils.import("resource://gre/modules/XPCOMUtils.jsm");
const {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm");
const {clearTimeout, setTimeout} = ChromeUtils.import("resource://gre/modules/Timer.jsm");
Cu.importGlobalProperties(["Element"]);
XPCOMUtils.defineLazyModuleGetters(this, {
OpenInTabsUtils: "resource:///modules/OpenInTabsUtils.jsm",
PlacesUtils: "resource://gre/modules/PlacesUtils.jsm",
PluralForm: "resource://gre/modules/PluralForm.jsm",
PrivateBrowsingUtils: "resource://gre/modules/PrivateBrowsingUtils.jsm",
RecentWindow: "resource:///modules/RecentWindow.jsm",
PromiseUtils: "resource://gre/modules/PromiseUtils.jsm",
PlacesTransactions: "resource://gre/modules/PlacesTransactions.jsm",
});
XPCOMUtils.defineLazyGetter(this, "bundle", function() {
return Services.strings.createBundle("chrome://communicator/locale/places/places.properties");
});
const gInContentProcess = Services.appinfo.processType == Ci.nsIXULRuntime.PROCESS_TYPE_CONTENT;
const FAVICON_REQUEST_TIMEOUT = 60 * 1000;
// Map from windows to arrays of data about pending favicon loads.
var gFaviconLoadDataMap = new Map();
const ITEM_CHANGED_BATCH_NOTIFICATION_THRESHOLD = 10;
// copied from utilityOverlay.js
const TAB_DROP_TYPE = "application/x-moz-tabbrowser-tab";
var InternalFaviconLoader = {
/**
* This gets called for every inner window that is destroyed.
* In the parent process, we process the destruction ourselves. In the child process,
* we notify the parent which will then process it based on that message.
*/
observe(subject, topic, data) {
let innerWindowID = subject.QueryInterface(Ci.nsISupportsPRUint64).data;
this.removeRequestsForInner(innerWindowID);
},
/**
* Actually cancel the request, and clear the timeout for cancelling it.
*/
_cancelRequest({uri, innerWindowID, timerID, callback}, reason) {
// Break cycle
let request = callback.request;
delete callback.request;
// Ensure we don't time out.
clearTimeout(timerID);
try {
request.cancel();
} catch (ex) {
Cu.reportError("When cancelling a request for " + uri.spec + " because " + reason + ", it was already canceled!");
}
},
/**
* Called for every inner that gets destroyed, only in the parent process.
*/
removeRequestsForInner(innerID) {
for (let [window, loadDataForWindow] of gFaviconLoadDataMap) {
let newLoadDataForWindow = loadDataForWindow.filter(loadData => {
let innerWasDestroyed = loadData.innerWindowID == innerID;
if (innerWasDestroyed) {
this._cancelRequest(loadData, "the inner window was destroyed or a new favicon was loaded for it");
}
// Keep the items whose inner is still alive.
return !innerWasDestroyed;
});
// Map iteration with for...of is safe against modification, so
// now just replace the old value:
gFaviconLoadDataMap.set(window, newLoadDataForWindow);
}
},
/**
* Called when a toplevel chrome window unloads. We use this to tidy up after ourselves,
* avoid leaks, and cancel any remaining requests. The last part should in theory be
* handled by the inner-window-destroyed handlers. We clean up just to be on the safe side.
*/
onUnload(win) {
let loadDataForWindow = gFaviconLoadDataMap.get(win);
if (loadDataForWindow) {
for (let loadData of loadDataForWindow) {
this._cancelRequest(loadData, "the chrome window went away");
}
}
gFaviconLoadDataMap.delete(win);
},
/**
* Remove a particular favicon load's loading data from our map tracking
* load data per chrome window.
*
* @param win
* the chrome window in which we should look for this load
* @param filterData ({innerWindowID, uri, callback})
* the data we should use to find this particular load to remove.
*
* @return the loadData object we removed, or null if we didn't find any.
*/
_removeLoadDataFromWindowMap(win, {innerWindowID, uri, callback}) {
let loadDataForWindow = gFaviconLoadDataMap.get(win);
if (loadDataForWindow) {
let itemIndex = loadDataForWindow.findIndex(loadData => {
return loadData.innerWindowID == innerWindowID &&
loadData.uri.equals(uri) &&
loadData.callback.request == callback.request;
});
if (itemIndex != -1) {
let loadData = loadDataForWindow[itemIndex];
loadDataForWindow.splice(itemIndex, 1);
return loadData;
}
}
return null;
},
/**
* Create a function to use as a nsIFaviconDataCallback, so we can remove cancelling
* information when the request succeeds. Note that right now there are some edge-cases,
* such as about: URIs with chrome:// favicons where the success callback is not invoked.
* This is OK: we will 'cancel' the request after the timeout (or when the window goes
* away) but that will be a no-op in such cases.
*/
_makeCompletionCallback(win, id) {
return {
onComplete(uri) {
let loadData = InternalFaviconLoader._removeLoadDataFromWindowMap(win, {
uri,
innerWindowID: id,
callback: this,
});
if (loadData) {
clearTimeout(loadData.timerID);
}
delete this.request;
},
};
},
ensureInitialized() {
if (this._initialized) {
return;
}
this._initialized = true;
Services.obs.addObserver(this, "inner-window-destroyed");
Services.ppmm.addMessageListener("Toolkit:inner-window-destroyed", msg => {
this.removeRequestsForInner(msg.data);
});
},
loadFavicon(browser, principal, uri, requestContextID) {
this.ensureInitialized();
let win = browser.ownerGlobal;
if (!gFaviconLoadDataMap.has(win)) {
gFaviconLoadDataMap.set(win, []);
let unloadHandler = event => {
let doc = event.target;
let eventWin = doc.defaultView;
if (eventWin == win) {
win.removeEventListener("unload", unloadHandler);
this.onUnload(win);
}
};
win.addEventListener("unload", unloadHandler, true);
}
let {innerWindowID, currentURI} = browser;
// First we do the actual setAndFetch call:
let loadType = PrivateBrowsingUtils.isWindowPrivate(win)
? PlacesUtils.favicons.FAVICON_LOAD_PRIVATE
: PlacesUtils.favicons.FAVICON_LOAD_NON_PRIVATE;
let callback = this._makeCompletionCallback(win, innerWindowID);
let request = PlacesUtils.favicons.setAndFetchFaviconForPage(currentURI, uri, false,
loadType, callback, principal,
requestContextID);
// Now register the result so we can cancel it if/when necessary.
if (!request) {
// The favicon service can return with success but no-op (and leave request
// as null) if the icon is the same as the page (e.g. for images) or if it is
// the favicon for an error page. In this case, we do not need to do anything else.
return;
}
callback.request = request;
let loadData = {innerWindowID, uri, callback};
loadData.timerID = setTimeout(() => {
this._cancelRequest(loadData, "it timed out");
this._removeLoadDataFromWindowMap(win, loadData);
}, FAVICON_REQUEST_TIMEOUT);
let loadDataForWindow = gFaviconLoadDataMap.get(win);
loadDataForWindow.push(loadData);
},
};
var PlacesUIUtils = {
ORGANIZER_LEFTPANE_VERSION: 8,
ORGANIZER_FOLDER_ANNO: "PlacesOrganizer/OrganizerFolder",
ORGANIZER_QUERY_ANNO: "PlacesOrganizer/OrganizerQuery",
LOAD_IN_SIDEBAR_ANNO: "bookmarkProperties/loadInSidebar",
DESCRIPTION_ANNO: "bookmarkProperties/description",
/**
* Makes a URI from a spec, and do fixup
* @param aSpec
* The string spec of the URI
* @return A URI object for the spec.
*/
createFixedURI: function PUIU_createFixedURI(aSpec) {
return Services.uriFixup.createFixupURI(aSpec, Ci.nsIURIFixup.FIXUP_FLAG_NONE);
},
getFormattedString: function PUIU_getFormattedString(key, params) {
return bundle.formatStringFromName(key, params, params.length);
},
/**
* Get a localized plural string for the specified key name and numeric value
* substituting parameters.
*
* @param aKey
* String, key for looking up the localized string in the bundle
* @param aNumber
* Number based on which the final localized form is looked up
* @param aParams
* Array whose items will substitute #1, #2,... #n parameters
* in the string.
*
* @see https://developer.mozilla.org/en/Localization_and_Plurals
* @return The localized plural string.
*/
getPluralString: function PUIU_getPluralString(aKey, aNumber, aParams) {
let str = PluralForm.get(aNumber, bundle.GetStringFromName(aKey));
// Replace #1 with aParams[0], #2 with aParams[1], and so on.
return str.replace(/\#(\d+)/g, function(matchedId, matchedNumber) {
let param = aParams[parseInt(matchedNumber, 10) - 1];
return param !== undefined ? param : matchedId;
});
},
getString: function PUIU_getString(key) {
return bundle.GetStringFromName(key);
},
/**
* Shows the bookmark dialog corresponding to the specified info.
*
* @param aInfo
* Describes the item to be edited/added in the dialog.
* See documentation at the top of bookmarkProperties.js
* @param aWindow
* Owner window for the new dialog.
*
* @see documentation at the top of bookmarkProperties.js
* @return true if any transaction has been performed, false otherwise.
*/
showBookmarkDialog(aInfo, aParentWindow) {
// Preserve size attributes differently based on the fact the dialog has
// a folder picker or not, since it needs more horizontal space than the
// other controls.
let hasFolderPicker = !("hiddenRows" in aInfo) ||
!aInfo.hiddenRows.includes("folderPicker");
// Use a different chrome url to persist different sizes.
let dialogURL = hasFolderPicker ?
"chrome://communicator/content/places/bookmarkProperties2.xul" :
"chrome://communicator/content/places/bookmarkProperties.xul";
let features = "centerscreen,chrome,modal,resizable=yes";
let topUndoEntry;
let batchBlockingDeferred;
// Set the transaction manager into batching mode.
topUndoEntry = PlacesTransactions.topUndoEntry;
batchBlockingDeferred = PromiseUtils.defer();
PlacesTransactions.batch(async () => {
await batchBlockingDeferred.promise;
});
aParentWindow.openDialog(dialogURL, "", features, aInfo);
let performed = ("performed" in aInfo && aInfo.performed);
batchBlockingDeferred.resolve();
if (!performed &&
topUndoEntry != PlacesTransactions.topUndoEntry) {
PlacesTransactions.undo().catch(Cu.reportError);
}
return performed;
},
/**
* set and fetch a favicon. Can only be used from the parent process.
* @param browser {Browser} The XUL browser element for which we're fetching a favicon.
* @param principal {Principal} The loading principal to use for the fetch.
* @param uri {URI} The URI to fetch.
*/
loadFavicon(browser, principal, uri, requestContextID) {
if (gInContentProcess) {
throw new Error("Can't track loads from within the child process!");
}
InternalFaviconLoader.loadFavicon(browser, principal, uri, requestContextID);
},
/**
* Returns the closet ancestor places view for the given DOM node
* @param aNode
* a DOM node
* @return the closet ancestor places view if exists, null otherwsie.
*/
getViewForNode: function PUIU_getViewForNode(aNode) {
let node = aNode;
if (node.localName == "panelview" && node._placesView) {
return node._placesView;
}
// The view for a