Bug 1777637 - Part 3: Use plain object for lazy getter in browser/components/urlbar/. r=adw

Differential Revision: https://phabricator.services.mozilla.com/D150934
This commit is contained in:
Tooru Fujisawa 2022-07-05 23:34:10 +00:00
Родитель 60530c5404
Коммит 4191f0cef6
41 изменённых файлов: 1145 добавлений и 973 удалений

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

@ -11,7 +11,8 @@ const { XPCOMUtils } = ChromeUtils.import(
);
const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm");
XPCOMUtils.defineLazyModuleGetters(this, {
const lazy = {};
XPCOMUtils.defineLazyModuleGetters(lazy, {
BrowserWindowTracker: "resource:///modules/BrowserWindowTracker.jsm",
DevToolsShim: "chrome://devtools-startup/content/DevToolsShim.jsm",
UrlbarProviderQuickActions:
@ -22,7 +23,7 @@ const BASE_URL = Services.urlFormatter.formatURLPref("app.support.baseURL");
let openUrlFun = url => () => openUrl(url);
let openUrl = url => {
let window = BrowserWindowTracker.getTopWindow();
let window = lazy.BrowserWindowTracker.getTopWindow();
window.gBrowser.loadOneTab(url, {
inBackground: false,
triggeringPrincipal: Services.scriptSecurityManager.getSystemPrincipal(),
@ -37,7 +38,7 @@ let openUrl = url => {
let currentPageIsWebContentFilter = () =>
currentBrowser().currentURI.spec.startsWith("about:");
let currentBrowser = () =>
BrowserWindowTracker.getTopWindow().gBrowser.selectedBrowser;
lazy.BrowserWindowTracker.getTopWindow().gBrowser.selectedBrowser;
const DEFAULT_ACTIONS = {
clear: {
@ -65,7 +66,7 @@ const DEFAULT_ACTIONS = {
label: "quickactions-print",
isActive: currentPageIsWebContentFilter,
onPick: () => {
BrowserWindowTracker.getTopWindow()
lazy.BrowserWindowTracker.getTopWindow()
.document.getElementById("cmd_print")
.doCommand();
},
@ -113,8 +114,8 @@ const DEFAULT_ACTIONS = {
function openInspector() {
// TODO: This is supposed to be called with an element to start inspecting.
DevToolsShim.inspectNode(
BrowserWindowTracker.getTopWindow().gBrowser.selectedTab
lazy.DevToolsShim.inspectNode(
lazy.BrowserWindowTracker.getTopWindow().gBrowser.selectedTab
);
}
@ -150,7 +151,7 @@ function restartBrowser() {
class QuickActionsLoaderDefault {
static load() {
for (const key in DEFAULT_ACTIONS) {
UrlbarProviderQuickActions.addAction(key, DEFAULT_ACTIONS[key]);
lazy.UrlbarProviderQuickActions.addAction(key, DEFAULT_ACTIONS[key]);
}
}
}

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

@ -13,7 +13,8 @@ const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm");
const { AppConstants } = ChromeUtils.import(
"resource://gre/modules/AppConstants.jsm"
);
XPCOMUtils.defineLazyModuleGetters(this, {
const lazy = {};
XPCOMUtils.defineLazyModuleGetters(lazy, {
BrowserSearchTelemetry: "resource:///modules/BrowserSearchTelemetry.jsm",
FormHistory: "resource://gre/modules/FormHistory.jsm",
PlacesUtils: "resource://gre/modules/PlacesUtils.jsm",
@ -87,7 +88,7 @@ class UrlbarController {
this.input = options.input;
this.browserWindow = options.input.window;
this.manager = options.manager || UrlbarProvidersManager;
this.manager = options.manager || lazy.UrlbarProvidersManager;
this._listeners = new Set();
this._userSelectionBehavior = "none";
@ -369,7 +370,7 @@ class UrlbarController {
this.view.selectBy(
event.keyCode == KeyEvent.DOM_VK_PAGE_DOWN ||
event.keyCode == KeyEvent.DOM_VK_PAGE_UP
? UrlbarUtils.PAGE_UP_DOWN_DELTA
? lazy.UrlbarUtils.PAGE_UP_DOWN_DELTA
: 1,
{
reverse:
@ -448,7 +449,7 @@ class UrlbarController {
if (!this.input || context.isPrivate || !context.results.length) {
return;
}
let { url } = UrlbarUtils.getUrlFromResult(result);
let { url } = lazy.UrlbarUtils.getUrlFromResult(result);
if (!url) {
return;
}
@ -460,22 +461,25 @@ class UrlbarController {
(result == context.results[0] && result.heuristic) ||
result.autofill
) {
if (result.type == UrlbarUtils.RESULT_TYPE.SEARCH) {
if (result.type == lazy.UrlbarUtils.RESULT_TYPE.SEARCH) {
// Speculative connect only if search suggestions are enabled.
if (
UrlbarPrefs.get("suggest.searches") &&
UrlbarPrefs.get("browser.search.suggest.enabled")
lazy.UrlbarPrefs.get("suggest.searches") &&
lazy.UrlbarPrefs.get("browser.search.suggest.enabled")
) {
let engine = Services.search.getEngineByName(
result.payload.engine
);
UrlbarUtils.setupSpeculativeConnection(
lazy.UrlbarUtils.setupSpeculativeConnection(
engine,
this.browserWindow
);
}
} else if (result.autofill) {
UrlbarUtils.setupSpeculativeConnection(url, this.browserWindow);
lazy.UrlbarUtils.setupSpeculativeConnection(
url,
this.browserWindow
);
}
}
return;
@ -483,7 +487,7 @@ class UrlbarController {
case "mousedown": {
// On mousedown, connect only to http/https urls.
if (url.startsWith("http")) {
UrlbarUtils.setupSpeculativeConnection(url, this.browserWindow);
lazy.UrlbarUtils.setupSpeculativeConnection(url, this.browserWindow);
}
return;
}
@ -526,7 +530,7 @@ class UrlbarController {
// will happen when you press the Enter key. Treat it as no selection.
selectedResult = resultIndex > 0 || !result.heuristic ? resultIndex : -1;
}
BrowserSearchTelemetry.recordSearchSuggestionSelectionMethod(
lazy.BrowserSearchTelemetry.recordSearchSuggestionSelectionMethod(
event,
"urlbar",
selectedResult,
@ -553,7 +557,7 @@ class UrlbarController {
let telemetryType =
result.providerName == "UrlbarProviderTopSites"
? "topsite"
: UrlbarUtils.telemetryTypeFromResult(result);
: lazy.UrlbarUtils.telemetryTypeFromResult(result);
Services.telemetry.keyedScalarAdd(
`urlbar.picked.${telemetryType}`,
resultIndex,
@ -608,7 +612,7 @@ class UrlbarController {
}
// First call `provider.blockResult()`.
let provider = UrlbarProvidersManager.getProvider(result.providerName);
let provider = lazy.UrlbarProvidersManager.getProvider(result.providerName);
if (!provider) {
Cu.reportError(`Provider not found: ${result.providerName}`);
}
@ -622,7 +626,7 @@ class UrlbarController {
// is from history.
if (
!blockedByProvider &&
result.source != UrlbarUtils.RESULT_SOURCE.HISTORY
result.source != lazy.UrlbarUtils.RESULT_SOURCE.HISTORY
) {
return false;
}
@ -641,15 +645,15 @@ class UrlbarController {
}
// Form history or url restyled as search.
if (result.type == UrlbarUtils.RESULT_TYPE.SEARCH) {
if (result.type == lazy.UrlbarUtils.RESULT_TYPE.SEARCH) {
if (!queryContext.formHistoryName) {
return false;
}
// Generate the search url to remove it from browsing history.
let { url } = UrlbarUtils.getUrlFromResult(result);
PlacesUtils.history.remove(url).catch(Cu.reportError);
let { url } = lazy.UrlbarUtils.getUrlFromResult(result);
lazy.PlacesUtils.history.remove(url).catch(Cu.reportError);
// Now remove form history.
FormHistory.update(
lazy.FormHistory.update(
{
op: "remove",
fieldname: queryContext.formHistoryName,
@ -665,7 +669,7 @@ class UrlbarController {
}
// Remove browsing history entries from Places.
PlacesUtils.history.remove(result.payload.url).catch(Cu.reportError);
lazy.PlacesUtils.history.remove(result.payload.url).catch(Cu.reportError);
return true;
}
@ -761,7 +765,9 @@ class TelemetryEvent {
if (event.interactionType) {
interactionType = event.interactionType;
} else if (event.type == "input") {
interactionType = UrlbarUtils.isPasteEvent(event) ? "pasted" : "typed";
interactionType = lazy.UrlbarUtils.isPasteEvent(event)
? "pasted"
: "typed";
} else if (event.type == "drop") {
interactionType = "dropped";
} else if (searchString) {
@ -864,7 +870,7 @@ class TelemetryEvent {
// Rather than listening to the pref, just update status when we record an
// event, if the pref changed from the last time.
let recordingEnabled = UrlbarPrefs.get("eventTelemetry.enabled");
let recordingEnabled = lazy.UrlbarPrefs.get("eventTelemetry.enabled");
if (this._eventRecordingEnabled != recordingEnabled) {
this._eventRecordingEnabled = recordingEnabled;
Services.telemetry.setEventRecordingEnabled("urlbar", recordingEnabled);
@ -878,7 +884,7 @@ class TelemetryEvent {
numChars: details.searchString.length.toString(),
numWords: details.searchString
.trim()
.split(UrlbarTokenizer.REGEXP_SPACES)
.split(lazy.UrlbarTokenizer.REGEXP_SPACES)
.filter(t => t)
.length.toString(),
};
@ -909,7 +915,9 @@ class TelemetryEvent {
if (method === "engagement" && queryContext.results?.[0].autofill) {
// Record autofill impressions upon engagement.
const type = UrlbarUtils.telemetryTypeFromResult(queryContext.results[0]);
const type = lazy.UrlbarUtils.telemetryTypeFromResult(
queryContext.results[0]
);
Services.telemetry.scalarAdd(`urlbar.impression.${type}`, 1);
}
@ -946,7 +954,7 @@ class TelemetryEvent {
if (row.result && row.result.providerName != "UrlbarProviderTopSites") {
// Element handlers go here.
if (element.classList.contains("urlbarView-button-help")) {
return row.result.type == UrlbarUtils.RESULT_TYPE.TIP
return row.result.type == lazy.UrlbarUtils.RESULT_TYPE.TIP
? "tiphelp"
: "help";
}
@ -955,6 +963,6 @@ class TelemetryEvent {
}
}
// Now handle the result.
return UrlbarUtils.telemetryTypeFromResult(row.result);
return lazy.UrlbarUtils.telemetryTypeFromResult(row.result);
}
}

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

@ -13,14 +13,15 @@ const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm");
const { AppConstants } = ChromeUtils.import(
"resource://gre/modules/AppConstants.jsm"
);
XPCOMUtils.defineLazyModuleGetters(this, {
const lazy = {};
XPCOMUtils.defineLazyModuleGetters(lazy, {
clearTimeout: "resource://gre/modules/Timer.jsm",
setTimeout: "resource://gre/modules/Timer.jsm",
UrlbarUtils: "resource:///modules/UrlbarUtils.jsm",
});
XPCOMUtils.defineLazyGetter(this, "logger", () =>
UrlbarUtils.getLogger({ prefix: "EventBufferer" })
XPCOMUtils.defineLazyGetter(lazy, "logger", () =>
lazy.UrlbarUtils.getLogger({ prefix: "EventBufferer" })
);
// Maximum time events can be deferred for. In automation providers can be quite
@ -100,7 +101,7 @@ class UrlbarEventBufferer {
context: queryContext,
};
if (this._deferringTimeout) {
clearTimeout(this._deferringTimeout);
lazy.clearTimeout(this._deferringTimeout);
this._deferringTimeout = null;
}
}
@ -126,12 +127,12 @@ class UrlbarEventBufferer {
*/
handleEvent(event) {
if (event.type == "blur") {
logger.debug("Clearing queue on blur");
lazy.logger.debug("Clearing queue on blur");
// The input field was blurred, pending events don't matter anymore.
// Clear the timeout and the queue.
this._eventsQueue.length = 0;
if (this._deferringTimeout) {
clearTimeout(this._deferringTimeout);
lazy.clearTimeout(this._deferringTimeout);
this._deferringTimeout = null;
}
}
@ -172,7 +173,7 @@ class UrlbarEventBufferer {
if (event.urlbarDeferred) {
throw new Error(`Event ${event.type}:${event.keyCode} already deferred!`);
}
logger.debug(`Deferring ${event.type}:${event.keyCode} event`);
lazy.logger.debug(`Deferring ${event.type}:${event.keyCode} event`);
// Mark the event as deferred.
event.urlbarDeferred = true;
// Also store the current search string, as an added safety check. If the
@ -183,7 +184,7 @@ class UrlbarEventBufferer {
if (!this._deferringTimeout) {
let elapsed = Cu.now() - this._lastQuery.startDate;
let remaining = DEFERRING_TIMEOUT_MS - elapsed;
this._deferringTimeout = setTimeout(() => {
this._deferringTimeout = lazy.setTimeout(() => {
this.replayDeferredEvents(false);
this._deferringTimeout = null;
}, Math.max(0, remaining));

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

@ -14,7 +14,9 @@ const { AppConstants } = ChromeUtils.import(
"resource://gre/modules/AppConstants.jsm"
);
XPCOMUtils.defineLazyModuleGetters(this, {
const lazy = {};
XPCOMUtils.defineLazyModuleGetters(lazy, {
BrowserSearchTelemetry: "resource:///modules/BrowserSearchTelemetry.jsm",
BrowserUIUtils: "resource:///modules/BrowserUIUtils.jsm",
CONTEXTUAL_SERVICES_PING_TYPES:
@ -40,7 +42,7 @@ XPCOMUtils.defineLazyModuleGetters(this, {
});
XPCOMUtils.defineLazyServiceGetter(
this,
lazy,
"ClipboardHelper",
"@mozilla.org/widget/clipboardhelper;1",
"nsIClipboardHelper"
@ -70,7 +72,7 @@ class UrlbarInput {
this.textbox = options.textbox;
this.window = this.textbox.ownerGlobal;
this.isPrivate = PrivateBrowsingUtils.isWindowPrivate(this.window);
this.isPrivate = lazy.PrivateBrowsingUtils.isWindowPrivate(this.window);
this.document = this.window.document;
// Create the panel to contain results.
@ -94,16 +96,16 @@ class UrlbarInput {
);
this.panel = this.textbox.querySelector(".urlbarView");
this.searchButton = UrlbarPrefs.get("experimental.searchButton");
this.searchButton = lazy.UrlbarPrefs.get("experimental.searchButton");
if (this.searchButton) {
this.textbox.classList.add("searchButton");
}
this.controller = new UrlbarController({
this.controller = new lazy.UrlbarController({
input: this,
eventTelemetryCategory: options.eventTelemetryCategory,
});
this.view = new UrlbarView(this);
this.view = new lazy.UrlbarView(this);
this.valueIsTyped = false;
this.formHistoryName = DEFAULT_FORM_HISTORY_NAME;
this.lastQueryContextPromise = Promise.resolve();
@ -199,7 +201,7 @@ class UrlbarInput {
this._toolbar = this.textbox.closest("toolbar");
XPCOMUtils.defineLazyGetter(this, "valueFormatter", () => {
return new UrlbarValueFormatter(this);
return new lazy.UrlbarValueFormatter(this);
});
XPCOMUtils.defineLazyGetter(this, "addSearchEngineHelper", () => {
@ -217,7 +219,7 @@ class UrlbarInput {
// muscle memory; for example quickly pressing DOWN+ENTER should end up
// on a predictable result, regardless of the search status. The event
// bufferer will invoke the handling code at the right time.
this.eventBufferer = new UrlbarEventBufferer(this);
this.eventBufferer = new lazy.UrlbarEventBufferer(this);
this._inputFieldEvents = [
"compositionstart",
@ -268,7 +270,7 @@ class UrlbarInput {
this._initPasteAndGo();
// Tracks IME composition.
this._compositionState = UrlbarUtils.COMPOSITION.NONE;
this._compositionState = lazy.UrlbarUtils.COMPOSITION.NONE;
this._compositionClosedPopup = false;
this.editor.newlineHandling =
@ -346,7 +348,7 @@ class UrlbarInput {
// only if there's no opener (bug 370555).
if (
this.window.isInitialPage(uri) &&
BrowserUIUtils.checkEmptyPageOrigin(
lazy.BrowserUIUtils.checkEmptyPageOrigin(
this.window.gBrowser.selectedBrowser,
uri
)
@ -369,7 +371,9 @@ class UrlbarInput {
uri.schemeIs("moz-extension"));
} else if (
this.window.isInitialPage(value) &&
BrowserUIUtils.checkEmptyPageOrigin(this.window.gBrowser.selectedBrowser)
lazy.BrowserUIUtils.checkEmptyPageOrigin(
this.window.gBrowser.selectedBrowser
)
) {
value = "";
valid = true;
@ -443,7 +447,7 @@ class UrlbarInput {
makeURIReadable(uri) {
// Avoid copying 'about:reader?url=', and always provide the original URI:
// Reader mode ensures we call createExposableURI itself.
let readerStrippedURI = ReaderMode.getOriginalUrlObjectForDisplay(
let readerStrippedURI = lazy.ReaderMode.getOriginalUrlObjectForDisplay(
uri.displaySpec
);
if (readerStrippedURI) {
@ -537,7 +541,7 @@ class UrlbarInput {
// when the view is open.
let selectedPrivateResult =
result &&
result.type == UrlbarUtils.RESULT_TYPE.SEARCH &&
result.type == lazy.UrlbarUtils.RESULT_TYPE.SEARCH &&
result.payload.inPrivateWindow;
let selectedPrivateEngineResult =
selectedPrivateResult && result.payload.isPrivateEngine;
@ -552,7 +556,7 @@ class UrlbarInput {
// Use the hidden heuristic if it exists and there's no selection.
if (
UrlbarPrefs.get("experimental.hideHeuristic") &&
lazy.UrlbarPrefs.get("experimental.hideHeuristic") &&
!element &&
!isComposing &&
!oneOffParams?.engine &&
@ -584,13 +588,13 @@ class UrlbarInput {
let searchString =
(result && (result.payload.suggestion || result.payload.query)) ||
this._lastSearchString;
[url, openParams.postData] = UrlbarUtils.getSearchQueryUrl(
[url, openParams.postData] = lazy.UrlbarUtils.getSearchQueryUrl(
oneOffParams.engine,
searchString
);
this._recordSearch(oneOffParams.engine, event, { url });
UrlbarUtils.addToFormHistory(
lazy.UrlbarUtils.addToFormHistory(
this,
searchString,
oneOffParams.engine.name
@ -664,7 +668,7 @@ class UrlbarInput {
// the appropriate engine submission url.
let browser = this.window.gBrowser.selectedBrowser;
let lastLocationChange = browser.lastLocationChange;
UrlbarUtils.getHeuristicResultFor(url)
lazy.UrlbarUtils.getHeuristicResultFor(url)
.then(newResult => {
// Because this happens asynchronously, we must verify that the browser
// location did not change in the meanwhile.
@ -729,7 +733,7 @@ class UrlbarInput {
*/
handoff(searchString, searchEngine, newtabSessionId) {
this._handoffSession = newtabSessionId;
if (UrlbarPrefs.get("shouldHandOffToSearchMode") && searchEngine) {
if (lazy.UrlbarPrefs.get("shouldHandOffToSearchMode") && searchEngine) {
this.search(searchString, {
searchEngine,
searchModeEntry: "handoff",
@ -802,7 +806,7 @@ class UrlbarInput {
if (
urlOverride &&
result.type != UrlbarUtils.RESULT_TYPE.TIP &&
result.type != lazy.UrlbarUtils.RESULT_TYPE.TIP &&
where == "current"
) {
// Open non-tip help links in a new tab unless the user held a modifier.
@ -830,11 +834,11 @@ class UrlbarInput {
let { url, postData } = urlOverride
? { url: urlOverride, postData: null }
: UrlbarUtils.getUrlFromResult(result);
: lazy.UrlbarUtils.getUrlFromResult(result);
openParams.postData = postData;
switch (result.type) {
case UrlbarUtils.RESULT_TYPE.URL: {
case lazy.UrlbarUtils.RESULT_TYPE.URL: {
// Bug 1578856: both the provider and the docshell run heuristics to
// decide how to handle a non-url string, either fixing it to a url, or
// searching for it.
@ -855,20 +859,20 @@ class UrlbarInput {
// the urifixup prefs.
if (
result.heuristic &&
UrlbarPrefs.get("browser.fixup.dns_first_for_single_words") &&
UrlbarUtils.looksLikeSingleWordHost(originalUntrimmedValue)
lazy.UrlbarPrefs.get("browser.fixup.dns_first_for_single_words") &&
lazy.UrlbarUtils.looksLikeSingleWordHost(originalUntrimmedValue)
) {
url = originalUntrimmedValue;
}
break;
}
case UrlbarUtils.RESULT_TYPE.KEYWORD: {
case lazy.UrlbarUtils.RESULT_TYPE.KEYWORD: {
// If this result comes from a bookmark keyword, let it inherit the
// current document's principal, otherwise bookmarklets would break.
openParams.allowInheritPrincipal = true;
break;
}
case UrlbarUtils.RESULT_TYPE.TAB_SWITCH: {
case lazy.UrlbarUtils.RESULT_TYPE.TAB_SWITCH: {
if (this.hasAttribute("actionoverride")) {
where = "current";
break;
@ -877,7 +881,7 @@ class UrlbarInput {
this.handleRevert();
let prevTab = this.window.gBrowser.selectedTab;
let loadOpts = {
adoptIntoActiveWindow: UrlbarPrefs.get(
adoptIntoActiveWindow: lazy.UrlbarPrefs.get(
"switchTabs.adoptIntoActiveWindow"
),
};
@ -903,14 +907,14 @@ class UrlbarInput {
if (switched && !this.isPrivate && !result.heuristic) {
// We don't await for this, because a rejection should not interrupt
// the load. Just reportError it.
UrlbarUtils.addToInputHistory(url, searchString).catch(
lazy.UrlbarUtils.addToInputHistory(url, searchString).catch(
Cu.reportError
);
}
return;
}
case UrlbarUtils.RESULT_TYPE.SEARCH: {
case lazy.UrlbarUtils.RESULT_TYPE.SEARCH: {
if (result.payload.providesSearchMode) {
let searchModeParams = this._searchModeForResult(result);
if (searchModeParams) {
@ -924,12 +928,12 @@ class UrlbarInput {
!this.searchMode &&
result.heuristic &&
// If we asked the DNS earlier, avoid the post-facto check.
!UrlbarPrefs.get("browser.fixup.dns_first_for_single_words") &&
!lazy.UrlbarPrefs.get("browser.fixup.dns_first_for_single_words") &&
// TODO (bug 1642623): for now there is no smart heuristic to skip the
// DNS lookup, so any value above 0 will run it.
UrlbarPrefs.get("dnsResolveSingleWordsAfterSearch") > 0 &&
lazy.UrlbarPrefs.get("dnsResolveSingleWordsAfterSearch") > 0 &&
this.window.gKeywordURIFixup &&
UrlbarUtils.looksLikeSingleWordHost(originalUntrimmedValue)
lazy.UrlbarUtils.looksLikeSingleWordHost(originalUntrimmedValue)
) {
// When fixing a single word to a search, the docShell would also
// query the DNS and if resolved ask the user whether they would
@ -954,7 +958,8 @@ class UrlbarInput {
const actionDetails = {
isSuggestion: !!result.payload.suggestion,
isFormHistory: result.source == UrlbarUtils.RESULT_SOURCE.HISTORY,
isFormHistory:
result.source == lazy.UrlbarUtils.RESULT_SOURCE.HISTORY,
alias: result.payload.keyword,
url,
};
@ -962,7 +967,7 @@ class UrlbarInput {
this._recordSearch(engine, event, actionDetails);
if (!result.payload.inPrivateWindow) {
UrlbarUtils.addToFormHistory(
lazy.UrlbarUtils.addToFormHistory(
this,
result.payload.suggestion || result.payload.query,
engine.name
@ -970,7 +975,7 @@ class UrlbarInput {
}
break;
}
case UrlbarUtils.RESULT_TYPE.TIP: {
case lazy.UrlbarUtils.RESULT_TYPE.TIP: {
let scalarName;
if (element.classList.contains("urlbarView-button-help")) {
url = result.payload.helpUrl;
@ -991,7 +996,7 @@ class UrlbarInput {
selType: "tip",
provider: result.providerName,
});
let provider = UrlbarProvidersManager.getProvider(
let provider = lazy.UrlbarProvidersManager.getProvider(
result.providerName
);
if (!provider) {
@ -1003,7 +1008,7 @@ class UrlbarInput {
}
break;
}
case UrlbarUtils.RESULT_TYPE.DYNAMIC: {
case lazy.UrlbarUtils.RESULT_TYPE.DYNAMIC: {
url = result.payload.url;
// Do not revert the Urlbar if we're going to navigate. We want the URL
// populated so we can navigate to it.
@ -1011,7 +1016,9 @@ class UrlbarInput {
this.handleRevert();
}
let provider = UrlbarProvidersManager.getProvider(result.providerName);
let provider = lazy.UrlbarProvidersManager.getProvider(
result.providerName
);
if (!provider) {
Cu.reportError(`Provider not found: ${result.providerName}`);
return;
@ -1030,7 +1037,7 @@ class UrlbarInput {
}
break;
}
case UrlbarUtils.RESULT_TYPE.OMNIBOX: {
case lazy.UrlbarUtils.RESULT_TYPE.OMNIBOX: {
this.controller.engagementEvent.record(event, {
searchString: this._lastSearchString,
selIndex,
@ -1047,7 +1054,7 @@ class UrlbarInput {
// We pass the keyword and content, that actually is the retrieved value
// prefixed by the keyword. ExtensionSearchHandler uses this keyword
// redundancy as a sanity check.
ExtensionSearchHandler.handleInputEntered(
lazy.ExtensionSearchHandler.handleInputEntered(
result.payload.keyword,
result.payload.content,
where
@ -1072,7 +1079,7 @@ class UrlbarInput {
if (input !== undefined) {
// We don't await for this, because a rejection should not interrupt
// the load. Just reportError it.
UrlbarUtils.addToInputHistory(url, input).catch(Cu.reportError);
lazy.UrlbarUtils.addToInputHistory(url, input).catch(Cu.reportError);
}
}
@ -1084,7 +1091,7 @@ class UrlbarInput {
});
if (result.payload.sendAttributionRequest) {
PartnerLinkAttribution.makeRequest({
lazy.PartnerLinkAttribution.makeRequest({
targetURL: result.payload.url,
source: "urlbar",
campaignID: Services.prefs.getStringPref(
@ -1099,7 +1106,7 @@ class UrlbarInput {
`urlbar_${position}`,
1
);
PartnerLinkAttribution.sendContextualServicesPing(
lazy.PartnerLinkAttribution.sendContextualServicesPing(
{
position,
source: "urlbar",
@ -1107,7 +1114,7 @@ class UrlbarInput {
reporting_url: result.payload.sponsoredClickUrl,
advertiser: result.payload.title.toLocaleLowerCase(),
},
CONTEXTUAL_SERVICES_PING_TYPES.TOPSITES_SELECTION
lazy.CONTEXTUAL_SERVICES_PING_TYPES.TOPSITES_SELECTION
);
}
}
@ -1177,10 +1184,10 @@ class UrlbarInput {
this._setValue(value, allowTrim);
switch (result.type) {
case UrlbarUtils.RESULT_TYPE.TAB_SWITCH:
case lazy.UrlbarUtils.RESULT_TYPE.TAB_SWITCH:
this.setAttribute("actiontype", "switchtab");
break;
case UrlbarUtils.RESULT_TYPE.OMNIBOX:
case lazy.UrlbarUtils.RESULT_TYPE.OMNIBOX:
this.setAttribute("actiontype", "extension");
break;
}
@ -1226,12 +1233,12 @@ class UrlbarInput {
// it would end up executing a search instead of visiting it.
let allowTrim = true;
if (
(urlOverride || result.type == UrlbarUtils.RESULT_TYPE.URL) &&
UrlbarPrefs.get("trimURLs")
(urlOverride || result.type == lazy.UrlbarUtils.RESULT_TYPE.URL) &&
lazy.UrlbarPrefs.get("trimURLs")
) {
let url = urlOverride || result.payload.url;
if (url.startsWith(BrowserUIUtils.trimURLProtocol)) {
let fixupInfo = this._getURIFixupInfo(BrowserUIUtils.trimURL(url));
if (url.startsWith(lazy.BrowserUIUtils.trimURLProtocol)) {
let fixupInfo = this._getURIFixupInfo(lazy.BrowserUIUtils.trimURL(url));
if (fixupInfo?.keywordAsSent) {
allowTrim = false;
}
@ -1398,7 +1405,7 @@ class UrlbarInput {
let options = {
allowAutofill,
isPrivate: this.isPrivate,
maxResults: UrlbarPrefs.get("maxRichResults"),
maxResults: lazy.UrlbarPrefs.get("maxRichResults"),
searchString,
userContextId: this.window.gBrowser.selectedBrowser.getAttribute(
"usercontextid"
@ -1407,8 +1414,9 @@ class UrlbarInput {
formHistoryName: this.formHistoryName,
prohibitRemoteResults:
event &&
UrlbarUtils.isPasteEvent(event) &&
UrlbarPrefs.get("maxCharsForSearchSuggestions") < event.data?.length,
lazy.UrlbarUtils.isPasteEvent(event) &&
lazy.UrlbarPrefs.get("maxCharsForSearchSuggestions") <
event.data?.length,
};
if (this.searchMode) {
@ -1423,7 +1431,7 @@ class UrlbarInput {
// tests are not listening for completion when starting a query through
// other methods than startQuery (input events for example).
this.lastQueryContextPromise = this.controller.startQuery(
new UrlbarQueryContext(options)
new lazy.UrlbarQueryContext(options)
);
}
@ -1448,10 +1456,10 @@ class UrlbarInput {
this.focus();
}
let trimmedValue = value.trim();
let end = trimmedValue.search(UrlbarTokenizer.REGEXP_SPACES);
let end = trimmedValue.search(lazy.UrlbarTokenizer.REGEXP_SPACES);
let firstToken = end == -1 ? trimmedValue : trimmedValue.substring(0, end);
// Enter search mode if the string starts with a restriction token.
let searchMode = UrlbarUtils.searchModeForToken(firstToken);
let searchMode = lazy.UrlbarUtils.searchModeForToken(firstToken);
let firstTokenIsRestriction = !!searchMode;
if (!searchMode && searchEngine) {
searchMode = { engineName: searchEngine.name };
@ -1466,16 +1474,18 @@ class UrlbarInput {
// in search mode.
value = value.replace(firstToken, "");
}
if (UrlbarTokenizer.REGEXP_SPACES.test(value[0])) {
if (lazy.UrlbarTokenizer.REGEXP_SPACES.test(value[0])) {
// If there was a trailing space after the restriction token/alias,
// remove it.
value = value.slice(1);
}
this._revertOnBlurValue = value;
} else if (Object.values(UrlbarTokenizer.RESTRICT).includes(firstToken)) {
} else if (
Object.values(lazy.UrlbarTokenizer.RESTRICT).includes(firstToken)
) {
this.searchMode = null;
// If the entire value is a restricted token, append a space.
if (Object.values(UrlbarTokenizer.RESTRICT).includes(value)) {
if (Object.values(lazy.UrlbarTokenizer.RESTRICT).includes(value)) {
value += " ";
}
this._revertOnBlurValue = value;
@ -1584,7 +1594,7 @@ class UrlbarInput {
let currentSearchMode = this.getSearchMode(browser);
let areSearchModesSame =
(!currentSearchMode && !searchMode) ||
ObjectUtils.deepEqual(currentSearchMode, searchMode);
lazy.ObjectUtils.deepEqual(currentSearchMode, searchMode);
// Exit search mode if the passed-in engine is invalid or hidden.
let engine;
@ -1613,10 +1623,10 @@ class UrlbarInput {
// History results for general-purpose search engines are often not
// useful, so we hide them in search mode. See bug 1658646 for
// discussion.
searchMode.source = UrlbarUtils.RESULT_SOURCE.SEARCH;
searchMode.source = lazy.UrlbarUtils.RESULT_SOURCE.SEARCH;
}
} else if (source) {
let sourceName = UrlbarUtils.getResultSourceName(source);
let sourceName = lazy.UrlbarUtils.getResultSourceName(source);
if (sourceName) {
searchMode = { source };
} else {
@ -1626,7 +1636,7 @@ class UrlbarInput {
if (searchMode) {
searchMode.isPreview = isPreview;
if (UrlbarUtils.SEARCH_MODE_ENTRY.has(entry)) {
if (lazy.UrlbarUtils.SEARCH_MODE_ENTRY.has(entry)) {
searchMode.entry = entry;
} else {
// If we see this value showing up in telemetry, we should review
@ -1658,7 +1668,7 @@ class UrlbarInput {
this.valueIsTyped = true;
if (!searchMode.isPreview && !areSearchModesSame) {
try {
BrowserSearchTelemetry.recordSearchMode(searchMode);
lazy.BrowserSearchTelemetry.recordSearchMode(searchMode);
} catch (ex) {
Cu.reportError(ex);
}
@ -1684,8 +1694,8 @@ class UrlbarInput {
// We restrict to search results when entering search mode from this
// shortcut to honor historical behaviour.
this.searchMode = {
source: UrlbarUtils.RESULT_SOURCE.SEARCH,
engineName: UrlbarSearchUtils.getDefaultEngine(this.isPrivate).name,
source: lazy.UrlbarUtils.RESULT_SOURCE.SEARCH,
engineName: lazy.UrlbarSearchUtils.getDefaultEngine(this.isPrivate).name,
entry: "shortcut",
};
// The searchMode setter clears the input if pageproxystate is valid, so
@ -1781,7 +1791,7 @@ class UrlbarInput {
}
if (Cu.isInAutomation) {
if (UrlbarPrefs.get("disableExtendForTests")) {
if (lazy.UrlbarPrefs.get("disableExtendForTests")) {
this.setAttribute("breakout-extend-disabled", "true");
return;
}
@ -1908,10 +1918,10 @@ class UrlbarInput {
observe(subject, topic, data) {
switch (topic) {
case SearchUtils.TOPIC_ENGINE_MODIFIED: {
case lazy.SearchUtils.TOPIC_ENGINE_MODIFIED: {
switch (data) {
case SearchUtils.MODIFIED_TYPE.CHANGED:
case SearchUtils.MODIFIED_TYPE.REMOVED: {
case lazy.SearchUtils.MODIFIED_TYPE.CHANGED:
case lazy.SearchUtils.MODIFIED_TYPE.REMOVED: {
let searchMode = this.searchMode;
let engine = subject.QueryInterface(Ci.nsISearchEngine);
if (searchMode?.engineName == engine.name) {
@ -1929,7 +1939,11 @@ class UrlbarInput {
// Private methods below.
_addObservers() {
Services.obs.addObserver(this, SearchUtils.TOPIC_ENGINE_MODIFIED, true);
Services.obs.addObserver(
this,
lazy.SearchUtils.TOPIC_ENGINE_MODIFIED,
true
);
}
_getURIFixupInfo(searchString) {
@ -2009,7 +2023,7 @@ class UrlbarInput {
_setValue(val, allowTrim) {
// Don't expose internal about:reader URLs to the user.
let originalUrl = ReaderMode.getOriginalUrlObjectForDisplay(val);
let originalUrl = lazy.ReaderMode.getOriginalUrlObjectForDisplay(val);
if (originalUrl) {
val = originalUrl.displaySpec;
}
@ -2035,9 +2049,9 @@ class UrlbarInput {
_getValueFromResult(result, urlOverride = null) {
switch (result.type) {
case UrlbarUtils.RESULT_TYPE.KEYWORD:
case lazy.UrlbarUtils.RESULT_TYPE.KEYWORD:
return result.payload.input;
case UrlbarUtils.RESULT_TYPE.SEARCH: {
case lazy.UrlbarUtils.RESULT_TYPE.SEARCH: {
let value = "";
if (result.payload.keyword) {
value += result.payload.keyword + " ";
@ -2045,9 +2059,9 @@ class UrlbarInput {
value += result.payload.suggestion || result.payload.query;
return value;
}
case UrlbarUtils.RESULT_TYPE.OMNIBOX:
case lazy.UrlbarUtils.RESULT_TYPE.OMNIBOX:
return result.payload.content;
case UrlbarUtils.RESULT_TYPE.DYNAMIC:
case lazy.UrlbarUtils.RESULT_TYPE.DYNAMIC:
return result.payload.input || "";
}
@ -2090,7 +2104,7 @@ class UrlbarInput {
let allowAutofill =
this.selectionEnd == value.length &&
!this.searchMode?.engineName &&
this.searchMode?.source != UrlbarUtils.RESULT_SOURCE.SEARCH;
this.searchMode?.source != lazy.UrlbarUtils.RESULT_SOURCE.SEARCH;
if (!allowAutofill) {
this._autofillPlaceholder = null;
return false;
@ -2113,7 +2127,7 @@ class UrlbarInput {
.toLocaleLowerCase()
.startsWith(value.toLocaleLowerCase());
} else {
canAutofillPlaceholder = UrlbarUtils.canAutofillURL(
canAutofillPlaceholder = lazy.UrlbarUtils.canAutofillURL(
this._autofillPlaceholder.value,
value
);
@ -2263,7 +2277,7 @@ class UrlbarInput {
this.value == selectedVal &&
!uri.schemeIs("javascript") &&
!uri.schemeIs("data") &&
!UrlbarPrefs.get("decodeURLsOnCopy")
!lazy.UrlbarPrefs.get("decodeURLsOnCopy")
) {
return displaySpec;
}
@ -2272,18 +2286,18 @@ class UrlbarInput {
// url. First check for a trimmed value.
if (
!selectedVal.startsWith(BrowserUIUtils.trimURLProtocol) &&
!selectedVal.startsWith(lazy.BrowserUIUtils.trimURLProtocol) &&
// Note _trimValue may also trim a trailing slash, thus we can't just do
// a straight string compare to tell if the protocol was trimmed.
!displaySpec.startsWith(this._trimValue(displaySpec))
) {
selectedVal = BrowserUIUtils.trimURLProtocol + selectedVal;
selectedVal = lazy.BrowserUIUtils.trimURLProtocol + selectedVal;
}
// If selection starts from the beginning and part or all of the URL
// is selected, we check for decoded characters and encode them.
// Unless decodeURLsOnCopy is set. Do not encode data: URIs.
if (!UrlbarPrefs.get("decodeURLsOnCopy") && !uri.schemeIs("data")) {
if (!lazy.UrlbarPrefs.get("decodeURLsOnCopy") && !uri.schemeIs("data")) {
try {
new URL(selectedVal);
// Use encodeURI instead of URL.href because we don't want
@ -2363,7 +2377,7 @@ class UrlbarInput {
source = "urlbar-searchmode";
}
BrowserSearchTelemetry.recordSearch(
lazy.BrowserSearchTelemetry.recordSearch(
this.window.gBrowser.selectedBrowser,
engine,
source,
@ -2384,7 +2398,9 @@ class UrlbarInput {
* The trimmed string
*/
_trimValue(val) {
return UrlbarPrefs.get("trimURLs") ? BrowserUIUtils.trimURL(val) : val;
return lazy.UrlbarPrefs.get("trimURLs")
? lazy.BrowserUIUtils.trimURL(val)
: val;
}
/**
@ -2405,7 +2421,7 @@ class UrlbarInput {
!KeyboardEvent.isInstance(event) ||
event._disableCanonization ||
!event.ctrlKey ||
!UrlbarPrefs.get("ctrlCanonizesURLs") ||
!lazy.UrlbarPrefs.get("ctrlCanonizesURLs") ||
!/^\s*[^.:\/\s]+(?:\/.*|\s*)$/i.test(value)
) {
return null;
@ -2526,7 +2542,7 @@ class UrlbarInput {
}
try {
UrlbarUtils.addToUrlbarHistory(url, this.window);
lazy.UrlbarUtils.addToUrlbarHistory(url, this.window);
} catch (ex) {
// Things may go wrong when adding url to session history,
// but don't let that interfere with the loading of the url.
@ -2632,7 +2648,7 @@ class UrlbarInput {
} else if (
isKeyboardEvent &&
event.ctrlKey &&
UrlbarPrefs.get("ctrlCanonizesURLs")
lazy.UrlbarPrefs.get("ctrlCanonizesURLs")
) {
// If we're allowing canonization, and this is a key event with ctrl
// pressed, open in current tab to allow ctrl-enter to canonize URL.
@ -2640,7 +2656,7 @@ class UrlbarInput {
} else {
where = this.window.whereToOpenLink(event, false, false);
}
if (UrlbarPrefs.get("openintab")) {
if (lazy.UrlbarPrefs.get("openintab")) {
if (where == "current") {
where = "tab";
} else if (where == "tab") {
@ -2745,7 +2761,9 @@ class UrlbarInput {
return null;
}
let searchMode = UrlbarUtils.searchModeForToken(result.payload.keyword);
let searchMode = lazy.UrlbarUtils.searchModeForToken(
result.payload.keyword
);
// If result.originalEngine is set, then the user is Alt+Tabbing
// through the one-offs, so the keyword doesn't match the engine.
if (
@ -2829,7 +2847,7 @@ class UrlbarInput {
{ name: engineName }
);
} else if (source) {
let sourceName = UrlbarUtils.getResultSourceName(source);
let sourceName = lazy.UrlbarUtils.getResultSourceName(source);
let l10nID = `urlbar-search-mode-${sourceName}`;
this.document.l10n.setAttributes(this._searchModeIndicatorTitle, l10nID);
this.document.l10n.setAttributes(this._searchModeLabel, l10nID);
@ -2858,7 +2876,7 @@ class UrlbarInput {
_maybeSelectAll() {
if (
!this._preventClickSelectsAll &&
this._compositionState != UrlbarUtils.COMPOSITION.COMPOSING &&
this._compositionState != lazy.UrlbarUtils.COMPOSITION.COMPOSING &&
this.document.activeElement == this.inputField &&
this.inputField.selectionStart == this.inputField.selectionEnd
) {
@ -2917,13 +2935,13 @@ class UrlbarInput {
// The extension input sessions depends more on blur than on the fact we
// actually cancel a running query, so we do it here.
if (ExtensionSearchHandler.hasActiveInputSession()) {
ExtensionSearchHandler.handleInputCancelled();
if (lazy.ExtensionSearchHandler.hasActiveInputSession()) {
lazy.ExtensionSearchHandler.handleInputCancelled();
}
// Respect the autohide preference for easier inspecting/debugging via
// the browser toolbox.
if (!UrlbarPrefs.get("ui.popup.disable_autohide")) {
if (!lazy.UrlbarPrefs.get("ui.popup.disable_autohide")) {
this.view.close();
}
@ -3032,7 +3050,7 @@ class UrlbarInput {
}
_on_draggableregionleftmousedown(event) {
if (!UrlbarPrefs.get("ui.popup.disable_autohide")) {
if (!lazy.UrlbarPrefs.get("ui.popup.disable_autohide")) {
this.view.close();
}
}
@ -3073,7 +3091,7 @@ class UrlbarInput {
if (event.target.id == SEARCH_BUTTON_ID) {
this._preventClickSelectsAll = true;
this.search(UrlbarTokenizer.RESTRICT.SEARCH);
this.search(lazy.UrlbarTokenizer.RESTRICT.SEARCH);
} else {
// Do not suppress the focus border if we are already focused. If we
// did, we'd hide the focus border briefly then show it again if the
@ -3098,7 +3116,7 @@ class UrlbarInput {
// might not automatically remove focus from the input.
// Respect the autohide preference for easier inspecting/debugging via
// the browser toolbox.
if (!UrlbarPrefs.get("ui.popup.disable_autohide")) {
if (!lazy.UrlbarPrefs.get("ui.popup.disable_autohide")) {
this.view.close();
}
break;
@ -3121,8 +3139,8 @@ class UrlbarInput {
let compositionClosedPopup = this._compositionClosedPopup;
// Clear composition values if we're no more composing.
if (this._compositionState != UrlbarUtils.COMPOSITION.COMPOSING) {
this._compositionState = UrlbarUtils.COMPOSITION.NONE;
if (this._compositionState != lazy.UrlbarUtils.COMPOSITION.COMPOSING) {
this._compositionState = lazy.UrlbarUtils.COMPOSITION.NONE;
this._compositionClosedPopup = false;
}
@ -3142,7 +3160,7 @@ class UrlbarInput {
if (!this.view.isOpen) {
this.view.clear();
} else if (!value && !UrlbarPrefs.get("suggest.topsites")) {
} else if (!value && !lazy.UrlbarPrefs.get("suggest.topsites")) {
this.view.clear();
if (!this.searchMode || !this.view.oneOffSearchButtons.hasView) {
this.view.close();
@ -3161,9 +3179,9 @@ class UrlbarInput {
// We should do nothing during composition or if composition was canceled
// and we didn't close the popup on composition start.
if (
!UrlbarPrefs.get("keepPanelOpenDuringImeComposition") &&
(compositionState == UrlbarUtils.COMPOSITION.COMPOSING ||
(compositionState == UrlbarUtils.COMPOSITION.CANCELED &&
!lazy.UrlbarPrefs.get("keepPanelOpenDuringImeComposition") &&
(compositionState == lazy.UrlbarUtils.COMPOSITION.COMPOSING ||
(compositionState == lazy.UrlbarUtils.COMPOSITION.CANCELED &&
!compositionClosedPopup))
) {
return;
@ -3172,10 +3190,10 @@ class UrlbarInput {
// Autofill only when text is inserted (i.e., event.data is not empty) and
// it's not due to pasting.
const allowAutofill =
(!UrlbarPrefs.get("keepPanelOpenDuringImeComposition") ||
compositionState !== UrlbarUtils.COMPOSITION.COMPOSING) &&
(!lazy.UrlbarPrefs.get("keepPanelOpenDuringImeComposition") ||
compositionState !== lazy.UrlbarUtils.COMPOSITION.COMPOSING) &&
!!event.data &&
!UrlbarUtils.isPasteEvent(event) &&
!lazy.UrlbarUtils.isPasteEvent(event) &&
this._maybeAutofillPlaceholder(value);
this.startQuery({
@ -3214,7 +3232,7 @@ class UrlbarInput {
return;
}
ClipboardHelper.copyStringToClipboard(
lazy.ClipboardHelper.copyStringToClipboard(
val,
Services.clipboard.kSelectionClipboard
);
@ -3281,7 +3299,7 @@ class UrlbarInput {
? originalPasteData.replace(/[\r\n]/g, "")
: originalPasteData.replace(/\s/g, " ");
pasteData = UrlbarUtils.stripUnsafeProtocolOnPaste(pasteData);
pasteData = lazy.UrlbarUtils.stripUnsafeProtocolOnPaste(pasteData);
if (originalPasteData != pasteData) {
// Unfortunately we're not allowed to set the bits being pasted
@ -3326,7 +3344,7 @@ class UrlbarInput {
if (this._keyDownEnterDeferred) {
this._keyDownEnterDeferred.reject();
}
this._keyDownEnterDeferred = PromiseUtils.defer();
this._keyDownEnterDeferred = lazy.PromiseUtils.defer();
event._disableCanonization = this._isKeyDownWithCtrl;
} else if (event.keyCode !== KeyEvent.DOM_VK_CONTROL && event.ctrlKey) {
this._isKeyDownWithCtrl = true;
@ -3385,12 +3403,12 @@ class UrlbarInput {
}
_on_compositionstart(event) {
if (this._compositionState == UrlbarUtils.COMPOSITION.COMPOSING) {
if (this._compositionState == lazy.UrlbarUtils.COMPOSITION.COMPOSING) {
throw new Error("Trying to start a nested composition?");
}
this._compositionState = UrlbarUtils.COMPOSITION.COMPOSING;
this._compositionState = lazy.UrlbarUtils.COMPOSITION.COMPOSING;
if (UrlbarPrefs.get("keepPanelOpenDuringImeComposition")) {
if (lazy.UrlbarPrefs.get("keepPanelOpenDuringImeComposition")) {
return;
}
@ -3416,11 +3434,11 @@ class UrlbarInput {
}
_on_compositionend(event) {
if (this._compositionState != UrlbarUtils.COMPOSITION.COMPOSING) {
if (this._compositionState != lazy.UrlbarUtils.COMPOSITION.COMPOSING) {
throw new Error("Trying to stop a non existing composition?");
}
if (!UrlbarPrefs.get("keepPanelOpenDuringImeComposition")) {
if (!lazy.UrlbarPrefs.get("keepPanelOpenDuringImeComposition")) {
// Clear the selection and the cached result, since they refer to the
// state before this composition. A new input even will be generated
// after this.
@ -3431,8 +3449,8 @@ class UrlbarInput {
// We can't yet retrieve the committed value from the editor, since it isn't
// completely committed yet. We'll handle it at the next input event.
this._compositionState = event.data
? UrlbarUtils.COMPOSITION.COMMIT
: UrlbarUtils.COMPOSITION.CANCELED;
? lazy.UrlbarUtils.COMPOSITION.COMMIT
: lazy.UrlbarUtils.COMPOSITION.CANCELED;
}
_on_dragstart(event) {
@ -3535,7 +3553,7 @@ function getDroppableData(event) {
if (links.length && links[0].url) {
event.preventDefault();
let href = links[0].url;
if (UrlbarUtils.stripUnsafeProtocolOnPaste(href) != href) {
if (lazy.UrlbarUtils.stripUnsafeProtocolOnPaste(href) != href) {
// We may have stripped an unsafe protocol like javascript: and if so
// there's no point in handling a partial drop.
event.stopImmediatePropagation();
@ -3700,7 +3718,7 @@ class CopyCutController {
urlbar.inputField.dispatchEvent(event);
}
ClipboardHelper.copyString(val);
lazy.ClipboardHelper.copyString(val);
}
/**
@ -3772,7 +3790,7 @@ class AddSearchEngineHelper {
if (engines1?.length != engines2?.length) {
return false;
}
return ObjectUtils.deepEqual(
return lazy.ObjectUtils.deepEqual(
engines1.map(e => e.title),
engines2.map(e => e.title)
);
@ -3861,7 +3879,7 @@ class AddSearchEngineHelper {
}
async _onCommand(event) {
let added = await SearchUIUtils.addOpenSearchEngine(
let added = await lazy.SearchUIUtils.addOpenSearchEngine(
event.target.getAttribute("uri"),
event.target.getAttribute("image"),
this.browsingContext

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

@ -19,7 +19,9 @@ const { UrlbarMuxer, UrlbarUtils } = ChromeUtils.import(
"resource:///modules/UrlbarUtils.jsm"
);
XPCOMUtils.defineLazyModuleGetters(this, {
const lazy = {};
XPCOMUtils.defineLazyModuleGetters(lazy, {
UrlbarPrefs: "resource:///modules/UrlbarPrefs.jsm",
UrlbarProviderQuickSuggest:
"resource:///modules/UrlbarProviderQuickSuggest.jsm",
@ -28,7 +30,7 @@ XPCOMUtils.defineLazyModuleGetters(this, {
UrlbarSearchUtils: "resource:///modules/UrlbarSearchUtils.jsm",
});
XPCOMUtils.defineLazyGetter(this, "logger", () =>
XPCOMUtils.defineLazyGetter(lazy, "logger", () =>
UrlbarUtils.getLogger({ prefix: "MuxerUnifiedComplete" })
);
@ -119,7 +121,7 @@ class MuxerUnifiedComplete extends UrlbarMuxer {
);
}
if (state.maxHeuristicResultSpan) {
if (UrlbarPrefs.get("experimental.hideHeuristic")) {
if (lazy.UrlbarPrefs.get("experimental.hideHeuristic")) {
// The heuristic is hidden. The muxer will include it but the view will
// hide it. Increase the available span to compensate so that the total
// visible span accurately reflects `context.maxResults`.
@ -137,9 +139,9 @@ class MuxerUnifiedComplete extends UrlbarMuxer {
// Determine the result groups to use for this sort. In search mode with
// an engine, show search suggestions first.
let rootGroup = context.searchMode?.engineName
? UrlbarPrefs.makeResultGroups({ showSearchSuggestionsFirst: true })
: UrlbarPrefs.get("resultGroups");
logger.debug(`Groups: ${rootGroup}`);
? lazy.UrlbarPrefs.makeResultGroups({ showSearchSuggestionsFirst: true })
: lazy.UrlbarPrefs.get("resultGroups");
lazy.logger.debug(`Groups: ${rootGroup}`);
// Fill the root group.
let [sortedResults] = this._fillGroup(
@ -539,7 +541,7 @@ class MuxerUnifiedComplete extends UrlbarMuxer {
while (summedFillableLimit != fillableLimit) {
if (!fractionalDataArray.length) {
// This shouldn't happen, but don't let it break us.
logger.error("fractionalDataArray is empty!");
lazy.logger.error("fractionalDataArray is empty!");
break;
}
let data = flexDataArray[fractionalDataArray.shift().index];
@ -586,7 +588,7 @@ class MuxerUnifiedComplete extends UrlbarMuxer {
// are ignored and we use the flex defined on the form history group.
if (
groupConst == UrlbarUtils.RESULT_GROUP.FORM_HISTORY &&
!UrlbarPrefs.get("maxHistoricalSearchSuggestions")
!lazy.UrlbarPrefs.get("maxHistoricalSearchSuggestions")
) {
// Create a new `limits` object so we don't modify the caller's.
limits = { ...limits };
@ -644,7 +646,7 @@ class MuxerUnifiedComplete extends UrlbarMuxer {
_canAddResult(result, state) {
// Never discard quick suggest results. We may want to change this logic at
// some point, but for all current use cases, they should always be shown.
if (result.providerName == UrlbarProviderQuickSuggest.name) {
if (result.providerName == lazy.UrlbarProviderQuickSuggest.name) {
return true;
}
@ -702,7 +704,7 @@ class MuxerUnifiedComplete extends UrlbarMuxer {
!result.autofill &&
state.context.heuristicResult.payload?.url == result.payload.url &&
state.context.heuristicResult.type == result.type &&
!UrlbarPrefs.get("experimental.hideHeuristic")
!lazy.UrlbarPrefs.get("experimental.hideHeuristic")
) {
return false;
}
@ -717,7 +719,7 @@ class MuxerUnifiedComplete extends UrlbarMuxer {
return false;
}
if (result.providerName == UrlbarProviderTabToSearch.name) {
if (result.providerName == lazy.UrlbarProviderTabToSearch.name) {
// Discard the result if a tab-to-search result was added already.
if (!state.canAddTabToSearch) {
return false;
@ -846,7 +848,10 @@ class MuxerUnifiedComplete extends UrlbarMuxer {
submission.terms
);
if (
UrlbarSearchUtils.serpsAreEquivalent(result.payload.url, newSerpURL)
lazy.UrlbarSearchUtils.serpsAreEquivalent(
result.payload.url,
newSerpURL
)
) {
return false;
}
@ -861,7 +866,7 @@ class MuxerUnifiedComplete extends UrlbarMuxer {
state.context.searchMode.engineName
);
if (engine) {
let searchModeRootDomain = UrlbarSearchUtils.getRootDomainFromEngine(
let searchModeRootDomain = lazy.UrlbarSearchUtils.getRootDomainFromEngine(
engine
);
let resultUrl = new URL(result.payload.url);
@ -880,7 +885,7 @@ class MuxerUnifiedComplete extends UrlbarMuxer {
state.quickSuggestResult &&
!result.heuristic &&
result.type == UrlbarUtils.RESULT_TYPE.URL &&
UrlbarProviderQuickSuggest.isURLEquivalentToResultURL(
lazy.UrlbarProviderQuickSuggest.isURLEquivalentToResultURL(
result.payload.url,
state.quickSuggestResult
)
@ -969,7 +974,7 @@ class MuxerUnifiedComplete extends UrlbarMuxer {
this._canAddResult(result, state)
) {
let span = UrlbarUtils.getSpanForResult(result);
if (result.providerName == UrlbarProviderTabToSearch.name) {
if (result.providerName == lazy.UrlbarProviderTabToSearch.name) {
state.maxTabToSearchResultSpan = Math.max(
state.maxTabToSearchResultSpan,
span
@ -987,7 +992,7 @@ class MuxerUnifiedComplete extends UrlbarMuxer {
(result.type == UrlbarUtils.RESULT_TYPE.URL ||
result.type == UrlbarUtils.RESULT_TYPE.KEYWORD) &&
result.payload.url &&
(!result.heuristic || !UrlbarPrefs.get("experimental.hideHeuristic"))
(!result.heuristic || !lazy.UrlbarPrefs.get("experimental.hideHeuristic"))
) {
let [strippedUrl, prefix] = UrlbarUtils.stripPrefixAndTrim(
result.payload.url,
@ -1009,7 +1014,7 @@ class MuxerUnifiedComplete extends UrlbarMuxer {
// the quick suggest: The URL is added to history and later both a
// history result and the quick suggest may match a query.
(topPrefixRank == prefixRank &&
result.providerName == UrlbarProviderQuickSuggest.name)
result.providerName == lazy.UrlbarProviderQuickSuggest.name)
) {
// strippedUrl => { prefix, title, rank, providerName }
state.strippedUrlToTopPrefixAndTitle.set(strippedUrl, {
@ -1044,7 +1049,7 @@ class MuxerUnifiedComplete extends UrlbarMuxer {
state.canShowTailSuggestions = false;
}
if (result.providerName == UrlbarProviderQuickSuggest.name) {
if (result.providerName == lazy.UrlbarProviderQuickSuggest.name) {
state.quickSuggestResult = result;
}
@ -1069,7 +1074,7 @@ class MuxerUnifiedComplete extends UrlbarMuxer {
if (
result.type == UrlbarUtils.RESULT_TYPE.SEARCH &&
result.payload.query &&
!UrlbarPrefs.get("experimental.hideHeuristic")
!lazy.UrlbarPrefs.get("experimental.hideHeuristic")
) {
let query = result.payload.query.trim().toLocaleLowerCase();
if (query) {
@ -1103,17 +1108,17 @@ class MuxerUnifiedComplete extends UrlbarMuxer {
// Avoid multiple tab-to-search results.
// TODO (Bug 1670185): figure out better strategies to manage this case.
if (result.providerName == UrlbarProviderTabToSearch.name) {
if (result.providerName == lazy.UrlbarProviderTabToSearch.name) {
state.canAddTabToSearch = false;
// We want to record in urlbar.tips once per engagement per engine. Since
// whether these results are shown is dependent on the Muxer, we must
// add to `enginesShown` here.
if (result.payload.dynamicType) {
UrlbarProviderTabToSearch.enginesShown.onboarding.add(
lazy.UrlbarProviderTabToSearch.enginesShown.onboarding.add(
result.payload.engine
);
} else {
UrlbarProviderTabToSearch.enginesShown.regular.add(
lazy.UrlbarProviderTabToSearch.enginesShown.regular.add(
result.payload.engine
);
}
@ -1186,16 +1191,16 @@ class MuxerUnifiedComplete extends UrlbarMuxer {
// If same suggestedIndex, change the displaying order along to following
// provider priority.
// TabToSearch > QuickSuggest > Other providers
if (a.providerName === UrlbarProviderTabToSearch.name) {
if (a.providerName === lazy.UrlbarProviderTabToSearch.name) {
return 1;
}
if (b.providerName === UrlbarProviderTabToSearch.name) {
if (b.providerName === lazy.UrlbarProviderTabToSearch.name) {
return -1;
}
if (a.providerName === UrlbarProviderQuickSuggest.name) {
if (a.providerName === lazy.UrlbarProviderQuickSuggest.name) {
return 1;
}
if (b.providerName === UrlbarProviderQuickSuggest.name) {
if (b.providerName === lazy.UrlbarProviderQuickSuggest.name) {
return -1;
}

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

@ -17,7 +17,9 @@ const { XPCOMUtils } = ChromeUtils.import(
"resource://gre/modules/XPCOMUtils.jsm"
);
XPCOMUtils.defineLazyModuleGetters(this, {
const lazy = {};
XPCOMUtils.defineLazyModuleGetters(lazy, {
NimbusFeatures: "resource://nimbus/ExperimentAPI.jsm",
Region: "resource://gre/modules/Region.jsm",
UrlbarUtils: "resource:///modules/UrlbarUtils.jsm",
@ -436,22 +438,22 @@ function makeResultGroups({ showSearchSuggestionsFirst }) {
{
maxResultCount: 1,
children: [
{ group: UrlbarUtils.RESULT_GROUP.HEURISTIC_TEST },
{ group: UrlbarUtils.RESULT_GROUP.HEURISTIC_EXTENSION },
{ group: UrlbarUtils.RESULT_GROUP.HEURISTIC_SEARCH_TIP },
{ group: UrlbarUtils.RESULT_GROUP.HEURISTIC_OMNIBOX },
{ group: UrlbarUtils.RESULT_GROUP.HEURISTIC_ENGINE_ALIAS },
{ group: UrlbarUtils.RESULT_GROUP.HEURISTIC_BOOKMARK_KEYWORD },
{ group: UrlbarUtils.RESULT_GROUP.HEURISTIC_AUTOFILL },
{ group: UrlbarUtils.RESULT_GROUP.HEURISTIC_PRELOADED },
{ group: UrlbarUtils.RESULT_GROUP.HEURISTIC_TOKEN_ALIAS_ENGINE },
{ group: UrlbarUtils.RESULT_GROUP.HEURISTIC_FALLBACK },
{ group: lazy.UrlbarUtils.RESULT_GROUP.HEURISTIC_TEST },
{ group: lazy.UrlbarUtils.RESULT_GROUP.HEURISTIC_EXTENSION },
{ group: lazy.UrlbarUtils.RESULT_GROUP.HEURISTIC_SEARCH_TIP },
{ group: lazy.UrlbarUtils.RESULT_GROUP.HEURISTIC_OMNIBOX },
{ group: lazy.UrlbarUtils.RESULT_GROUP.HEURISTIC_ENGINE_ALIAS },
{ group: lazy.UrlbarUtils.RESULT_GROUP.HEURISTIC_BOOKMARK_KEYWORD },
{ group: lazy.UrlbarUtils.RESULT_GROUP.HEURISTIC_AUTOFILL },
{ group: lazy.UrlbarUtils.RESULT_GROUP.HEURISTIC_PRELOADED },
{ group: lazy.UrlbarUtils.RESULT_GROUP.HEURISTIC_TOKEN_ALIAS_ENGINE },
{ group: lazy.UrlbarUtils.RESULT_GROUP.HEURISTIC_FALLBACK },
],
},
// extensions using the omnibox API
{
group: UrlbarUtils.RESULT_GROUP.OMNIBOX,
availableSpan: UrlbarUtils.MAX_OMNIBOX_RESULT_COUNT - 1,
group: lazy.UrlbarUtils.RESULT_GROUP.OMNIBOX,
availableSpan: lazy.UrlbarUtils.MAX_OMNIBOX_RESULT_COUNT - 1,
},
],
};
@ -470,52 +472,52 @@ function makeResultGroups({ showSearchSuggestionsFirst }) {
// If `maxHistoricalSearchSuggestions` == 0, the muxer forces
// `maxResultCount` to be zero and flex is ignored, per query.
flex: 2,
group: UrlbarUtils.RESULT_GROUP.FORM_HISTORY,
group: lazy.UrlbarUtils.RESULT_GROUP.FORM_HISTORY,
},
{
flex: 4,
group: UrlbarUtils.RESULT_GROUP.REMOTE_SUGGESTION,
group: lazy.UrlbarUtils.RESULT_GROUP.REMOTE_SUGGESTION,
},
],
},
{
group: UrlbarUtils.RESULT_GROUP.TAIL_SUGGESTION,
group: lazy.UrlbarUtils.RESULT_GROUP.TAIL_SUGGESTION,
},
],
},
// general
{
group: UrlbarUtils.RESULT_GROUP.GENERAL_PARENT,
group: lazy.UrlbarUtils.RESULT_GROUP.GENERAL_PARENT,
children: [
{
availableSpan: 3,
group: UrlbarUtils.RESULT_GROUP.INPUT_HISTORY,
group: lazy.UrlbarUtils.RESULT_GROUP.INPUT_HISTORY,
},
{
flexChildren: true,
children: [
{
flex: 1,
group: UrlbarUtils.RESULT_GROUP.REMOTE_TAB,
group: lazy.UrlbarUtils.RESULT_GROUP.REMOTE_TAB,
},
{
flex: 2,
group: UrlbarUtils.RESULT_GROUP.GENERAL,
group: lazy.UrlbarUtils.RESULT_GROUP.GENERAL,
},
{
// We show relatively many about-page results because they're
// only added for queries starting with "about:".
flex: 2,
group: UrlbarUtils.RESULT_GROUP.ABOUT_PAGES,
group: lazy.UrlbarUtils.RESULT_GROUP.ABOUT_PAGES,
},
{
flex: 1,
group: UrlbarUtils.RESULT_GROUP.PRELOADED,
group: lazy.UrlbarUtils.RESULT_GROUP.PRELOADED,
},
],
},
{
group: UrlbarUtils.RESULT_GROUP.INPUT_HISTORY,
group: lazy.UrlbarUtils.RESULT_GROUP.INPUT_HISTORY,
},
],
},
@ -570,7 +572,7 @@ class Preferences {
// prevent re-entry due to pref observers.
this._updatingFirefoxSuggestScenario = false;
NimbusFeatures.urlbar.onUpdate(() => this._onNimbusUpdate());
lazy.NimbusFeatures.urlbar.onUpdate(() => this._onNimbusUpdate());
}
/**
@ -693,8 +695,8 @@ class Preferences {
// depend on them. Also note that pref migrations may depend on the
// scenario, and since each migration is performed only once, at startup,
// prefs can end up wrong if their migrations use the wrong scenario.
await Region.init();
await NimbusFeatures.urlbar.ready();
await lazy.Region.init();
await lazy.NimbusFeatures.urlbar.ready();
this._clearNimbusCache();
this._updateFirefoxSuggestScenarioHelper(isStartup, testOverrides);
@ -848,7 +850,7 @@ class Preferences {
let scenario = this._nimbus.quickSuggestScenario;
if (!scenario) {
if (
Region.home == "US" &&
lazy.Region.home == "US" &&
Services.locale.appLocaleAsBCP47.substring(0, 2) == "en"
) {
// offline rollout for en locales in the US region
@ -1296,7 +1298,7 @@ class Preferences {
get _nimbus() {
if (!this.__nimbus) {
this.__nimbus = NimbusFeatures.urlbar.getAllVariables({
this.__nimbus = lazy.NimbusFeatures.urlbar.getAllVariables({
defaultValues: NIMBUS_DEFAULTS,
});
}

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

@ -18,7 +18,9 @@ const { UrlbarProvider, UrlbarUtils } = ChromeUtils.import(
"resource:///modules/UrlbarUtils.jsm"
);
XPCOMUtils.defineLazyModuleGetters(this, {
const lazy = {};
XPCOMUtils.defineLazyModuleGetters(lazy, {
AboutPagesUtils: "resource://gre/modules/AboutPagesUtils.jsm",
UrlbarResult: "resource:///modules/UrlbarResult.jsm",
});
@ -65,12 +67,12 @@ class ProviderAboutPages extends UrlbarProvider {
*/
startQuery(queryContext, addCallback) {
let searchString = queryContext.trimmedSearchString.toLowerCase();
for (const aboutUrl of AboutPagesUtils.visibleAboutUrls) {
for (const aboutUrl of lazy.AboutPagesUtils.visibleAboutUrls) {
if (aboutUrl.startsWith(searchString)) {
let result = new UrlbarResult(
let result = new lazy.UrlbarResult(
UrlbarUtils.RESULT_TYPE.URL,
UrlbarUtils.RESULT_SOURCE.HISTORY,
...UrlbarResult.payloadAndSimpleHighlights(queryContext.tokens, {
...lazy.UrlbarResult.payloadAndSimpleHighlights(queryContext.tokens, {
title: [aboutUrl, UrlbarUtils.HIGHLIGHT.TYPED],
url: [aboutUrl, UrlbarUtils.HIGHLIGHT.TYPED],
icon: UrlbarUtils.getIconForUrl(aboutUrl),

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

@ -19,7 +19,9 @@ const { UrlbarProvider, UrlbarUtils } = ChromeUtils.import(
"resource:///modules/UrlbarUtils.jsm"
);
XPCOMUtils.defineLazyModuleGetters(this, {
const lazy = {};
XPCOMUtils.defineLazyModuleGetters(lazy, {
UrlbarResult: "resource:///modules/UrlbarResult.jsm",
UrlbarSearchUtils: "resource:///modules/UrlbarSearchUtils.jsm",
UrlbarTokenizer: "resource:///modules/UrlbarTokenizer.jsm",
@ -55,7 +57,7 @@ class ProviderAliasEngines extends UrlbarProvider {
isActive(queryContext) {
return (
(!queryContext.restrictSource ||
queryContext.restrictSource == UrlbarTokenizer.RESTRICT.SEARCH) &&
queryContext.restrictSource == lazy.UrlbarTokenizer.RESTRICT.SEARCH) &&
!queryContext.searchMode &&
queryContext.tokens.length
);
@ -70,7 +72,7 @@ class ProviderAliasEngines extends UrlbarProvider {
async startQuery(queryContext, addCallback) {
let instance = this.queryInstance;
let alias = queryContext.tokens[0]?.value;
let engine = await UrlbarSearchUtils.engineForAlias(
let engine = await lazy.UrlbarSearchUtils.engineForAlias(
alias,
queryContext.searchString
);
@ -78,10 +80,10 @@ class ProviderAliasEngines extends UrlbarProvider {
return;
}
let query = UrlbarUtils.substringAfter(queryContext.searchString, alias);
let result = new UrlbarResult(
let result = new lazy.UrlbarResult(
UrlbarUtils.RESULT_TYPE.SEARCH,
UrlbarUtils.RESULT_SOURCE.SEARCH,
...UrlbarResult.payloadAndSimpleHighlights(queryContext.tokens, {
...lazy.UrlbarResult.payloadAndSimpleHighlights(queryContext.tokens, {
engine: engine.name,
keyword: alias,
query: query.trimStart(),

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

@ -18,7 +18,9 @@ const { UrlbarProvider, UrlbarUtils } = ChromeUtils.import(
"resource:///modules/UrlbarUtils.jsm"
);
XPCOMUtils.defineLazyModuleGetters(this, {
const lazy = {};
XPCOMUtils.defineLazyModuleGetters(lazy, {
AboutPagesUtils: "resource://gre/modules/AboutPagesUtils.jsm",
PlacesUtils: "resource://gre/modules/PlacesUtils.jsm",
UrlbarPrefs: "resource:///modules/UrlbarPrefs.jsm",
@ -302,7 +304,7 @@ class ProviderAutofill extends UrlbarProvider {
this._autofillData = null;
// First of all, check for the autoFill pref.
if (!UrlbarPrefs.get("autoFill")) {
if (!lazy.UrlbarPrefs.get("autoFill")) {
return false;
}
@ -332,8 +334,8 @@ class ProviderAutofill extends UrlbarProvider {
if (
queryContext.tokens.some(
t =>
t.type == UrlbarTokenizer.TYPE.RESTRICT_TAG ||
t.type == UrlbarTokenizer.TYPE.RESTRICT_TITLE
t.type == lazy.UrlbarTokenizer.TYPE.RESTRICT_TAG ||
t.type == lazy.UrlbarTokenizer.TYPE.RESTRICT_TITLE
)
) {
return false;
@ -348,7 +350,7 @@ class ProviderAutofill extends UrlbarProvider {
// This may confuse completeDefaultIndex cause the AUTOCOMPLETE_MATCH
// tokenizer ends up trimming the search string and returning a value
// that doesn't match it, or is even shorter.
if (UrlbarTokenizer.REGEXP_SPACES.test(queryContext.searchString)) {
if (lazy.UrlbarTokenizer.REGEXP_SPACES.test(queryContext.searchString)) {
return false;
}
@ -425,10 +427,10 @@ class ProviderAutofill extends UrlbarProvider {
* @resolves {string} The top matching host, or null if not found.
*/
async getTopHostOverThreshold(queryContext, hosts) {
let db = await PlacesUtils.promiseLargeCacheDBConnection();
let db = await lazy.PlacesUtils.promiseLargeCacheDBConnection();
let conditions = [];
// Pay attention to the order of params, since they are not named.
let params = [UrlbarPrefs.get("autoFill.stddevMultiplier"), ...hosts];
let params = [lazy.UrlbarPrefs.get("autoFill.stddevMultiplier"), ...hosts];
let sources = queryContext.sources;
if (
sources.includes(UrlbarUtils.RESULT_SOURCE.HISTORY) &&
@ -497,7 +499,7 @@ class ProviderAutofill extends UrlbarProvider {
let opts = {
query_type: QUERYTYPE.AUTOFILL_ORIGIN,
searchString: searchStr.toLowerCase(),
stddevMultiplier: UrlbarPrefs.get("autoFill.stddevMultiplier"),
stddevMultiplier: lazy.UrlbarPrefs.get("autoFill.stddevMultiplier"),
};
if (this._strippedPrefix) {
opts.prefix = this._strippedPrefix;
@ -649,7 +651,7 @@ class ProviderAutofill extends UrlbarProvider {
const params = {
queryType: QUERYTYPE.AUTOFILL_ADAPTIVE,
searchString: queryContext.searchString.toLowerCase(),
useCountThreshold: UrlbarPrefs.get(
useCountThreshold: lazy.UrlbarPrefs.get(
"autoFillAdaptiveHistoryUseCountThreshold"
),
};
@ -806,10 +808,10 @@ class ProviderAutofill extends UrlbarProvider {
title = [autofilled, UrlbarUtils.HIGHLIGHT.TYPED];
}
let result = new UrlbarResult(
let result = new lazy.UrlbarResult(
UrlbarUtils.RESULT_TYPE.URL,
UrlbarUtils.RESULT_SOURCE.HISTORY,
...UrlbarResult.payloadAndSimpleHighlights(queryContext.tokens, {
...lazy.UrlbarResult.payloadAndSimpleHighlights(queryContext.tokens, {
title,
url: [finalCompleteValue, UrlbarUtils.HIGHLIGHT.TYPED],
icon: UrlbarUtils.getIconForUrl(finalCompleteValue),
@ -855,17 +857,17 @@ class ProviderAutofill extends UrlbarProvider {
return null;
}
for (const aboutUrl of AboutPagesUtils.visibleAboutUrls) {
for (const aboutUrl of lazy.AboutPagesUtils.visibleAboutUrls) {
if (aboutUrl.startsWith(`about:${this._searchString.toLowerCase()}`)) {
let [trimmedUrl] = UrlbarUtils.stripPrefixAndTrim(aboutUrl, {
stripHttp: true,
trimEmptyQuery: true,
trimSlash: !this._searchString.includes("/"),
});
let result = new UrlbarResult(
let result = new lazy.UrlbarResult(
UrlbarUtils.RESULT_TYPE.URL,
UrlbarUtils.RESULT_SOURCE.HISTORY,
...UrlbarResult.payloadAndSimpleHighlights(queryContext.tokens, {
...lazy.UrlbarResult.payloadAndSimpleHighlights(queryContext.tokens, {
title: [trimmedUrl, UrlbarUtils.HIGHLIGHT.TYPED],
url: [aboutUrl, UrlbarUtils.HIGHLIGHT.TYPED],
icon: UrlbarUtils.getIconForUrl(aboutUrl),
@ -887,15 +889,15 @@ class ProviderAutofill extends UrlbarProvider {
}
async _matchKnownUrl(queryContext) {
let conn = await PlacesUtils.promiseLargeCacheDBConnection();
let conn = await lazy.PlacesUtils.promiseLargeCacheDBConnection();
if (!conn) {
return null;
}
// We try to autofill with adaptive history first.
if (
UrlbarPrefs.get("autoFillAdaptiveHistoryEnabled") &&
UrlbarPrefs.get("autoFillAdaptiveHistoryMinCharsThreshold") <=
lazy.UrlbarPrefs.get("autoFillAdaptiveHistoryEnabled") &&
lazy.UrlbarPrefs.get("autoFillAdaptiveHistoryMinCharsThreshold") <=
queryContext.searchString.length
) {
const [query, params] = this._getAdaptiveHistoryQuery(queryContext);
@ -921,7 +923,7 @@ class ProviderAutofill extends UrlbarProvider {
// at the end, we still treat it as an URL.
let query, params;
if (
UrlbarTokenizer.looksLikeOrigin(this._searchString, {
lazy.UrlbarTokenizer.looksLikeOrigin(this._searchString, {
ignoreKnownDomains: true,
})
) {
@ -942,7 +944,7 @@ class ProviderAutofill extends UrlbarProvider {
async _matchSearchEngineDomain(queryContext) {
if (
!UrlbarPrefs.get("autoFill.searchEngines") ||
!lazy.UrlbarPrefs.get("autoFill.searchEngines") ||
!this._searchString.length
) {
return null;
@ -959,14 +961,18 @@ class ProviderAutofill extends UrlbarProvider {
}
// If the search string looks more like a url than a domain, bail out.
if (
!UrlbarTokenizer.looksLikeOrigin(searchStr, { ignoreKnownDomains: true })
!lazy.UrlbarTokenizer.looksLikeOrigin(searchStr, {
ignoreKnownDomains: true,
})
) {
return null;
}
// Since we are autofilling, we can only pick one matching engine. Use the
// first.
let engine = (await UrlbarSearchUtils.enginesForDomainPrefix(searchStr))[0];
let engine = (
await lazy.UrlbarSearchUtils.enginesForDomainPrefix(searchStr)
)[0];
if (!engine) {
return null;
}
@ -987,10 +993,10 @@ class ProviderAutofill extends UrlbarProvider {
let value =
this._strippedPrefix + domain.substr(domain.indexOf(searchStr)) + "/";
let result = new UrlbarResult(
let result = new lazy.UrlbarResult(
UrlbarUtils.RESULT_TYPE.SEARCH,
UrlbarUtils.RESULT_SOURCE.SEARCH,
...UrlbarResult.payloadAndSimpleHighlights(queryContext.tokens, {
...lazy.UrlbarResult.payloadAndSimpleHighlights(queryContext.tokens, {
engine: [engine.name, UrlbarUtils.HIGHLIGHT.TYPED],
icon: engine.iconURI?.spec,
})

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

@ -18,7 +18,9 @@ const { UrlbarProvider, UrlbarUtils } = ChromeUtils.import(
"resource:///modules/UrlbarUtils.jsm"
);
XPCOMUtils.defineLazyModuleGetters(this, {
const lazy = {};
XPCOMUtils.defineLazyModuleGetters(lazy, {
KeywordUtils: "resource://gre/modules/KeywordUtils.jsm",
UrlbarResult: "resource:///modules/UrlbarResult.jsm",
UrlbarTokenizer: "resource:///modules/UrlbarTokenizer.jsm",
@ -54,7 +56,8 @@ class ProviderBookmarkKeywords extends UrlbarProvider {
isActive(queryContext) {
return (
(!queryContext.restrictSource ||
queryContext.restrictSource == UrlbarTokenizer.RESTRICT.BOOKMARK) &&
queryContext.restrictSource ==
lazy.UrlbarTokenizer.RESTRICT.BOOKMARK) &&
!queryContext.searchMode &&
queryContext.tokens.length
);
@ -73,7 +76,7 @@ class ProviderBookmarkKeywords extends UrlbarProvider {
queryContext.searchString,
keyword
).trim();
let { entry, url, postData } = await KeywordUtils.getBindableKeyword(
let { entry, url, postData } = await lazy.KeywordUtils.getBindableKeyword(
keyword,
searchString
);
@ -99,10 +102,10 @@ class ProviderBookmarkKeywords extends UrlbarProvider {
title = UrlbarUtils.unEscapeURIForUI(url);
}
let result = new UrlbarResult(
let result = new lazy.UrlbarResult(
UrlbarUtils.RESULT_TYPE.KEYWORD,
UrlbarUtils.RESULT_SOURCE.BOOKMARKS,
...UrlbarResult.payloadAndSimpleHighlights(queryContext.tokens, {
...lazy.UrlbarResult.payloadAndSimpleHighlights(queryContext.tokens, {
title: [title, UrlbarUtils.HIGHLIGHT.TYPED],
url: [url, UrlbarUtils.HIGHLIGHT.TYPED],
keyword: [keyword, UrlbarUtils.HIGHLIGHT.TYPED],

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

@ -14,14 +14,16 @@ const { UrlbarProvider, UrlbarUtils } = ChromeUtils.import(
"resource:///modules/UrlbarUtils.jsm"
);
XPCOMUtils.defineLazyModuleGetters(this, {
const lazy = {};
XPCOMUtils.defineLazyModuleGetters(lazy, {
UrlbarPrefs: "resource:///modules/UrlbarPrefs.jsm",
UrlbarResult: "resource:///modules/UrlbarResult.jsm",
UrlbarView: "resource:///modules/UrlbarView.jsm",
});
XPCOMUtils.defineLazyServiceGetter(
this,
lazy,
"ClipboardHelper",
"@mozilla.org/widget/clipboardhelper;1",
"nsIClipboardHelper"
@ -70,8 +72,8 @@ const MIN_EXPRESSION_LENGTH = 3;
class ProviderCalculator extends UrlbarProvider {
constructor() {
super();
UrlbarResult.addDynamicResultType(DYNAMIC_RESULT_TYPE);
UrlbarView.addDynamicViewTemplate(DYNAMIC_RESULT_TYPE, VIEW_TEMPLATE);
lazy.UrlbarResult.addDynamicResultType(DYNAMIC_RESULT_TYPE);
lazy.UrlbarView.addDynamicViewTemplate(DYNAMIC_RESULT_TYPE, VIEW_TEMPLATE);
}
/**
@ -100,7 +102,7 @@ class ProviderCalculator extends UrlbarProvider {
return (
queryContext.trimmedSearchString &&
!queryContext.searchMode &&
UrlbarPrefs.get(ENABLED_PREF)
lazy.UrlbarPrefs.get(ENABLED_PREF)
);
}
@ -121,7 +123,7 @@ class ProviderCalculator extends UrlbarProvider {
return;
}
let value = Calculator.evaluatePostfix(postfix);
const result = new UrlbarResult(
const result = new lazy.UrlbarResult(
UrlbarUtils.RESULT_TYPE.DYNAMIC,
UrlbarUtils.RESULT_SOURCE.OTHER_LOCAL,
{
@ -157,7 +159,7 @@ class ProviderCalculator extends UrlbarProvider {
}
async pickResult({ payload }) {
ClipboardHelper.copyString(payload.value);
lazy.ClipboardHelper.copyString(payload.value);
}
}

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

@ -20,7 +20,9 @@ const { SkippableTimer, UrlbarProvider, UrlbarUtils } = ChromeUtils.import(
"resource:///modules/UrlbarUtils.jsm"
);
XPCOMUtils.defineLazyModuleGetters(this, {
const lazy = {};
XPCOMUtils.defineLazyModuleGetters(lazy, {
UrlbarPrefs: "resource:///modules/UrlbarPrefs.jsm",
UrlbarProvidersManager: "resource:///modules/UrlbarProvidersManager.jsm",
UrlbarResult: "resource:///modules/UrlbarResult.jsm",
@ -54,10 +56,10 @@ class UrlbarProviderExtension extends UrlbarProvider {
* The provider.
*/
static getOrCreate(name) {
let provider = UrlbarProvidersManager.getProvider(name);
let provider = lazy.UrlbarProvidersManager.getProvider(name);
if (!provider) {
provider = new UrlbarProviderExtension(name);
UrlbarProvidersManager.registerProvider(provider);
lazy.UrlbarProvidersManager.registerProvider(provider);
}
return provider;
}
@ -157,7 +159,7 @@ class UrlbarProviderExtension extends UrlbarProvider {
} else {
this._eventListeners.delete(eventName);
if (!this._eventListeners.size) {
UrlbarProvidersManager.unregisterProvider(this);
lazy.UrlbarProvidersManager.unregisterProvider(this);
}
}
}
@ -293,7 +295,7 @@ class UrlbarProviderExtension extends UrlbarProvider {
// so that we're not stuck waiting forever.
let timer = new SkippableTimer({
name: "UrlbarProviderExtension notification timer",
time: UrlbarPrefs.get("extension.timeout"),
time: lazy.UrlbarPrefs.get("extension.timeout"),
reportErrorOnTimeout: true,
logger: this.logger,
});
@ -330,7 +332,7 @@ class UrlbarProviderExtension extends UrlbarProvider {
engine = Services.search.getEngineByName(extResult.payload.engine);
} else if (extResult.payload.keyword) {
// Look up the engine by its alias.
engine = await UrlbarSearchUtils.engineForAlias(
engine = await lazy.UrlbarSearchUtils.engineForAlias(
extResult.payload.keyword
);
} else if (extResult.payload.url) {
@ -340,7 +342,9 @@ class UrlbarProviderExtension extends UrlbarProvider {
host = new URL(extResult.payload.url).hostname;
} catch (err) {}
if (host) {
engine = (await UrlbarSearchUtils.enginesForDomainPrefix(host))[0];
engine = (
await lazy.UrlbarSearchUtils.enginesForDomainPrefix(host)
)[0];
}
}
if (!engine) {
@ -355,10 +359,10 @@ class UrlbarProviderExtension extends UrlbarProvider {
extResult.payload.type = extResult.payload.type || "extension";
}
let result = new UrlbarResult(
let result = new lazy.UrlbarResult(
UrlbarProviderExtension.RESULT_TYPES[extResult.type],
UrlbarProviderExtension.SOURCE_TYPES[extResult.source],
...UrlbarResult.payloadAndSimpleHighlights(
...lazy.UrlbarResult.payloadAndSimpleHighlights(
context.tokens,
extResult.payload || {}
)

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

@ -21,7 +21,9 @@ const { UrlbarProvider, UrlbarUtils } = ChromeUtils.import(
"resource:///modules/UrlbarUtils.jsm"
);
XPCOMUtils.defineLazyModuleGetters(this, {
const lazy = {};
XPCOMUtils.defineLazyModuleGetters(lazy, {
UrlbarPrefs: "resource:///modules/UrlbarPrefs.jsm",
UrlbarResult: "resource:///modules/UrlbarResult.jsm",
UrlbarSearchUtils: "resource:///modules/UrlbarSearchUtils.jsm",
@ -93,12 +95,12 @@ class ProviderHeuristicFallback extends UrlbarProvider {
new URL(str);
} catch (ex) {
if (
UrlbarPrefs.get("keyword.enabled") &&
(UrlbarTokenizer.looksLikeOrigin(str, {
lazy.UrlbarPrefs.get("keyword.enabled") &&
(lazy.UrlbarTokenizer.looksLikeOrigin(str, {
noIp: true,
noPort: true,
}) ||
UrlbarTokenizer.REGEXP_COMMON_EMAIL.test(str))
lazy.UrlbarTokenizer.REGEXP_COMMON_EMAIL.test(str))
) {
let searchResult = this._engineSearchResult(queryContext);
if (instance != this.queryInstance) {
@ -135,7 +137,7 @@ class ProviderHeuristicFallback extends UrlbarProvider {
// restriction token was typed.
if (
queryContext.restrictSource == UrlbarUtils.RESULT_SOURCE.SEARCH ||
UrlbarTokenizer.SEARCH_MODE_RESTRICT.has(
lazy.UrlbarTokenizer.SEARCH_MODE_RESTRICT.has(
queryContext.restrictToken?.value
) ||
queryContext.searchMode
@ -158,12 +160,12 @@ class ProviderHeuristicFallback extends UrlbarProvider {
if (queryContext.fixupError) {
if (
queryContext.fixupError == Cr.NS_ERROR_MALFORMED_URI &&
!UrlbarPrefs.get("keyword.enabled")
!lazy.UrlbarPrefs.get("keyword.enabled")
) {
let result = new UrlbarResult(
let result = new lazy.UrlbarResult(
UrlbarUtils.RESULT_TYPE.URL,
UrlbarUtils.RESULT_SOURCE.OTHER_LOCAL,
...UrlbarResult.payloadAndSimpleHighlights(queryContext.tokens, {
...lazy.UrlbarResult.payloadAndSimpleHighlights(queryContext.tokens, {
title: [searchUrl, UrlbarUtils.HIGHLIGHT.NONE],
url: [searchUrl, UrlbarUtils.HIGHLIGHT.NONE],
})
@ -218,10 +220,10 @@ class ProviderHeuristicFallback extends UrlbarProvider {
iconUri = `page-icon:${prePath}/`;
}
let result = new UrlbarResult(
let result = new lazy.UrlbarResult(
UrlbarUtils.RESULT_TYPE.URL,
UrlbarUtils.RESULT_SOURCE.OTHER_LOCAL,
...UrlbarResult.payloadAndSimpleHighlights(queryContext.tokens, {
...lazy.UrlbarResult.payloadAndSimpleHighlights(queryContext.tokens, {
title: [displayURL, UrlbarUtils.HIGHLIGHT.NONE],
url: [escapedURL, UrlbarUtils.HIGHLIGHT.NONE],
icon: iconUri,
@ -237,7 +239,7 @@ class ProviderHeuristicFallback extends UrlbarProvider {
}
let firstToken = queryContext.tokens[0].value;
if (!UrlbarTokenizer.SEARCH_MODE_RESTRICT.has(firstToken)) {
if (!lazy.UrlbarTokenizer.SEARCH_MODE_RESTRICT.has(firstToken)) {
return null;
}
@ -263,7 +265,7 @@ class ProviderHeuristicFallback extends UrlbarProvider {
queryContext.searchString,
firstToken
);
if (!UrlbarTokenizer.REGEXP_SPACES_START.test(query)) {
if (!lazy.UrlbarTokenizer.REGEXP_SPACES_START.test(query)) {
return null;
}
@ -271,10 +273,10 @@ class ProviderHeuristicFallback extends UrlbarProvider {
if (queryContext.restrictSource == UrlbarUtils.RESULT_SOURCE.SEARCH) {
result = this._engineSearchResult(queryContext, firstToken);
} else {
result = new UrlbarResult(
result = new lazy.UrlbarResult(
UrlbarUtils.RESULT_TYPE.SEARCH,
UrlbarUtils.RESULT_SOURCE.OTHER_LOCAL,
...UrlbarResult.payloadAndSimpleHighlights(queryContext.tokens, {
...lazy.UrlbarResult.payloadAndSimpleHighlights(queryContext.tokens, {
query: [query.trimStart(), UrlbarUtils.HIGHLIGHT.NONE],
keyword: [firstToken, UrlbarUtils.HIGHLIGHT.NONE],
})
@ -291,7 +293,7 @@ class ProviderHeuristicFallback extends UrlbarProvider {
queryContext.searchMode.engineName
);
} else {
engine = UrlbarSearchUtils.getDefaultEngine(queryContext.isPrivate);
engine = lazy.UrlbarSearchUtils.getDefaultEngine(queryContext.isPrivate);
}
if (!engine) {
@ -305,7 +307,7 @@ class ProviderHeuristicFallback extends UrlbarProvider {
let query = queryContext.searchString;
if (
queryContext.tokens[0] &&
queryContext.tokens[0].value === UrlbarTokenizer.RESTRICT.SEARCH
queryContext.tokens[0].value === lazy.UrlbarTokenizer.RESTRICT.SEARCH
) {
query = UrlbarUtils.substringAfter(
query,
@ -313,10 +315,10 @@ class ProviderHeuristicFallback extends UrlbarProvider {
).trim();
}
return new UrlbarResult(
return new lazy.UrlbarResult(
UrlbarUtils.RESULT_TYPE.SEARCH,
UrlbarUtils.RESULT_SOURCE.SEARCH,
...UrlbarResult.payloadAndSimpleHighlights(queryContext.tokens, {
...lazy.UrlbarResult.payloadAndSimpleHighlights(queryContext.tokens, {
engine: [engine.name, UrlbarUtils.HIGHLIGHT.TYPED],
icon: engine.iconURI?.spec,
query: [query, UrlbarUtils.HIGHLIGHT.NONE],

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

@ -21,7 +21,9 @@ const { UrlbarProvider, UrlbarUtils } = ChromeUtils.import(
"resource:///modules/UrlbarUtils.jsm"
);
XPCOMUtils.defineLazyModuleGetters(this, {
const lazy = {};
XPCOMUtils.defineLazyModuleGetters(lazy, {
PlacesUtils: "resource://gre/modules/PlacesUtils.jsm",
UrlbarPrefs: "resource:///modules/UrlbarPrefs.jsm",
UrlbarProviderOpenTabs: "resource:///modules/UrlbarProviderOpenTabs.jsm",
@ -102,9 +104,9 @@ class ProviderInputHistory extends UrlbarProvider {
*/
isActive(queryContext) {
return (
(UrlbarPrefs.get("suggest.history") ||
UrlbarPrefs.get("suggest.bookmark") ||
UrlbarPrefs.get("suggest.openpage")) &&
(lazy.UrlbarPrefs.get("suggest.history") ||
lazy.UrlbarPrefs.get("suggest.bookmark") ||
lazy.UrlbarPrefs.get("suggest.openpage")) &&
!queryContext.searchMode
);
}
@ -120,7 +122,7 @@ class ProviderInputHistory extends UrlbarProvider {
async startQuery(queryContext, addCallback) {
let instance = this.queryInstance;
let conn = await PlacesUtils.promiseLargeCacheDBConnection();
let conn = await lazy.PlacesUtils.promiseLargeCacheDBConnection();
if (instance != this.queryInstance) {
return;
}
@ -142,15 +144,15 @@ class ProviderInputHistory extends UrlbarProvider {
const tags = row.getResultByIndex(QUERYINDEX.TAGS) || "";
let resultTitle = historyTitle;
if (openPageCount > 0 && UrlbarPrefs.get("suggest.openpage")) {
if (openPageCount > 0 && lazy.UrlbarPrefs.get("suggest.openpage")) {
if (url == queryContext.currentPage) {
// Don't suggest switching to the current page.
continue;
}
let result = new UrlbarResult(
let result = new lazy.UrlbarResult(
UrlbarUtils.RESULT_TYPE.TAB_SWITCH,
UrlbarUtils.RESULT_SOURCE.TABS,
...UrlbarResult.payloadAndSimpleHighlights(queryContext.tokens, {
...lazy.UrlbarResult.payloadAndSimpleHighlights(queryContext.tokens, {
url: [url, UrlbarUtils.HIGHLIGHT.TYPED],
title: [resultTitle, UrlbarUtils.HIGHLIGHT.TYPED],
icon: UrlbarUtils.getIconForUrl(url),
@ -161,10 +163,10 @@ class ProviderInputHistory extends UrlbarProvider {
}
let resultSource;
if (bookmarked && UrlbarPrefs.get("suggest.bookmark")) {
if (bookmarked && lazy.UrlbarPrefs.get("suggest.bookmark")) {
resultSource = UrlbarUtils.RESULT_SOURCE.BOOKMARKS;
resultTitle = bookmarkTitle || historyTitle;
} else if (UrlbarPrefs.get("suggest.history")) {
} else if (lazy.UrlbarPrefs.get("suggest.history")) {
resultSource = UrlbarUtils.RESULT_SOURCE.HISTORY;
} else {
continue;
@ -181,10 +183,10 @@ class ProviderInputHistory extends UrlbarProvider {
})
.sort();
let result = new UrlbarResult(
let result = new lazy.UrlbarResult(
UrlbarUtils.RESULT_TYPE.URL,
resultSource,
...UrlbarResult.payloadAndSimpleHighlights(queryContext.tokens, {
...lazy.UrlbarResult.payloadAndSimpleHighlights(queryContext.tokens, {
url: [url, UrlbarUtils.HIGHLIGHT.TYPED],
title: [resultTitle, UrlbarUtils.HIGHLIGHT.TYPED],
tags: [resultTags, UrlbarUtils.HIGHLIGHT.TYPED],
@ -207,11 +209,11 @@ class ProviderInputHistory extends UrlbarProvider {
return [
SQL_ADAPTIVE_QUERY,
{
parent: PlacesUtils.tagsFolderId,
parent: lazy.PlacesUtils.tagsFolderId,
search_string: queryContext.searchString.toLowerCase(),
matchBehavior: Ci.mozIPlacesAutoComplete.MATCH_ANYWHERE,
searchBehavior: UrlbarPrefs.get("defaultBehavior"),
userContextId: UrlbarProviderOpenTabs.getUserContextIdForOpenPagesTable(
searchBehavior: lazy.UrlbarPrefs.get("defaultBehavior"),
userContextId: lazy.UrlbarProviderOpenTabs.getUserContextIdForOpenPagesTable(
queryContext.userContextId,
queryContext.isPrivate
),

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

@ -5,7 +5,6 @@
"use strict";
var EXPORTED_SYMBOLS = ["UrlbarProviderInterventions", "QueryScorer"];
var gGlobalScope = this;
const { XPCOMUtils } = ChromeUtils.import(
"resource://gre/modules/XPCOMUtils.jsm"
@ -16,7 +15,9 @@ const { UrlbarProvider, UrlbarUtils } = ChromeUtils.import(
"resource:///modules/UrlbarUtils.jsm"
);
XPCOMUtils.defineLazyModuleGetters(this, {
const lazy = {};
XPCOMUtils.defineLazyModuleGetters(lazy, {
AppUpdater: "resource:///modules/AppUpdater.jsm",
BrowserWindowTracker: "resource:///modules/BrowserWindowTracker.jsm",
NLP: "resource://gre/modules/NLP.jsm",
@ -27,7 +28,7 @@ XPCOMUtils.defineLazyModuleGetters(this, {
UrlbarTokenizer: "resource:///modules/UrlbarTokenizer.jsm",
});
XPCOMUtils.defineLazyGetter(this, "appUpdater", () => new AppUpdater());
XPCOMUtils.defineLazyGetter(lazy, "appUpdater", () => new lazy.AppUpdater());
// The possible tips to show. These names (except NONE) are used in the names
// of keys in the `urlbar.tips` keyed scalar telemetry (see telemetry.rst).
@ -360,7 +361,7 @@ class QueryScorer {
// Compare each word in the node to the current query word.
let queryWord = queryWords[queryWordsIndex];
for (let [childWord, child] of node.childrenByWord) {
let distance = NLP.levenshtein(queryWord, childWord);
let distance = lazy.NLP.levenshtein(queryWord, childWord);
if (distance <= this._distanceThreshold) {
// The word represented by this child node matches the current query
// word. Recurse into the child node.
@ -492,7 +493,9 @@ class ProviderInterventions extends UrlbarProvider {
if (
!queryContext.searchString ||
queryContext.searchString.length > UrlbarUtils.MAX_TEXT_LENGTH ||
UrlbarTokenizer.REGEXP_LIKE_PROTOCOL.test(queryContext.searchString) ||
lazy.UrlbarTokenizer.REGEXP_LIKE_PROTOCOL.test(
queryContext.searchString
) ||
!EN_LOCALE_MATCH.test(Services.locale.appLocaleAsBCP47) ||
!Services.policies.isAllowed("urlbarinterventions")
) {
@ -521,8 +524,8 @@ class ProviderInterventions extends UrlbarProvider {
if (topDocIDs.has("update")) {
this._setCurrentTipFromAppUpdaterStatus();
} else if (topDocIDs.has("clear")) {
let window = BrowserWindowTracker.getTopWindow();
if (!PrivateBrowsingUtils.isWindowPrivate(window)) {
let window = lazy.BrowserWindowTracker.getTopWindow();
if (!lazy.PrivateBrowsingUtils.isWindowPrivate(window)) {
this.currentTip = TIPS.CLEAR;
}
} else if (topDocIDs.has("refresh")) {
@ -553,27 +556,27 @@ class ProviderInterventions extends UrlbarProvider {
}
// There are several update tips. Figure out which one to show.
switch (appUpdater.status) {
case AppUpdater.STATUS.READY_FOR_RESTART:
switch (lazy.appUpdater.status) {
case lazy.AppUpdater.STATUS.READY_FOR_RESTART:
// Prompt the user to restart.
this.currentTip = TIPS.UPDATE_RESTART;
break;
case AppUpdater.STATUS.DOWNLOAD_AND_INSTALL:
case lazy.AppUpdater.STATUS.DOWNLOAD_AND_INSTALL:
// There's an update available, but the user's pref says we should ask
// them to download and apply it.
this.currentTip = TIPS.UPDATE_ASK;
break;
case AppUpdater.STATUS.NO_UPDATES_FOUND:
case lazy.AppUpdater.STATUS.NO_UPDATES_FOUND:
// We show a special refresh tip when the browser is up to date.
this.currentTip = TIPS.UPDATE_REFRESH;
break;
case AppUpdater.STATUS.CHECKING:
case lazy.AppUpdater.STATUS.CHECKING:
// This will be the case the first time we check. See startQuery for
// how this special tip is handled.
this.currentTip = TIPS.UPDATE_CHECKING;
break;
case AppUpdater.STATUS.NO_UPDATER:
case AppUpdater.STATUS.UPDATE_DISABLED_BY_POLICY:
case lazy.AppUpdater.STATUS.NO_UPDATER:
case lazy.AppUpdater.STATUS.UPDATE_DISABLED_BY_POLICY:
// If the updater is disabled at build time or at runtime, either by
// policy or because we're in a package, do not select any update tips.
this.currentTip = TIPS.NONE;
@ -618,11 +621,11 @@ class ProviderInterventions extends UrlbarProvider {
// The updater is still checking, so wait for it to finish.
await new Promise(resolve => {
this._appUpdaterListener = () => {
appUpdater.removeListener(this._appUpdaterListener);
lazy.appUpdater.removeListener(this._appUpdaterListener);
delete this._appUpdaterListener;
resolve();
};
appUpdater.addListener(this._appUpdaterListener);
lazy.appUpdater.addListener(this._appUpdaterListener);
});
if (instance != this.queryInstance) {
// The query was canceled before the check finished.
@ -640,7 +643,7 @@ class ProviderInterventions extends UrlbarProvider {
// At this point, this.currentTip != TIPS.UPDATE_CHECKING because we
// returned early above if it was.
let result = new UrlbarResult(
let result = new lazy.UrlbarResult(
UrlbarUtils.RESULT_TYPE.TIP,
UrlbarUtils.RESULT_SOURCE.OTHER_LOCAL,
{
@ -670,7 +673,7 @@ class ProviderInterventions extends UrlbarProvider {
// If we're waiting for appUpdater to finish its update check,
// this._appUpdaterListener will be defined. We can stop listening now.
if (this._appUpdaterListener) {
appUpdater.removeListener(this._appUpdaterListener);
lazy.appUpdater.removeListener(this._appUpdaterListener);
delete this._appUpdaterListener;
}
}
@ -700,7 +703,7 @@ class ProviderInterventions extends UrlbarProvider {
restartBrowser();
break;
case TIPS.UPDATE_WEB:
let window = BrowserWindowTracker.getTopWindow();
let window = lazy.BrowserWindowTracker.getTopWindow();
window.gBrowser.selectedTab = window.gBrowser.addWebTab(
"https://www.mozilla.org/firefox/new/"
);
@ -731,7 +734,7 @@ class ProviderInterventions extends UrlbarProvider {
Date.now() - this._lastUpdateCheckTime >= UPDATE_CHECK_PERIOD_MS
) {
this._lastUpdateCheckTime = Date.now();
appUpdater.check();
lazy.appUpdater.check();
}
}
@ -741,8 +744,8 @@ class ProviderInterventions extends UrlbarProvider {
*/
resetAppUpdater() {
// Reset only if the object has already been initialized.
if (!Object.getOwnPropertyDescriptor(gGlobalScope, "appUpdater").get) {
appUpdater = new AppUpdater();
if (!Object.getOwnPropertyDescriptor(lazy, "appUpdater").get) {
lazy.appUpdater = new lazy.AppUpdater();
}
}
}
@ -754,7 +757,7 @@ var UrlbarProviderInterventions = new ProviderInterventions();
*/
function installBrowserUpdateAndRestart() {
if (appUpdater.status != AppUpdater.STATUS.DOWNLOAD_AND_INSTALL) {
if (lazy.appUpdater.status != lazy.AppUpdater.STATUS.DOWNLOAD_AND_INSTALL) {
return Promise.resolve();
}
return new Promise(resolve => {
@ -762,30 +765,30 @@ function installBrowserUpdateAndRestart() {
// Once we call startDownload, there are two possible end
// states: DOWNLOAD_FAILED and READY_FOR_RESTART.
if (
appUpdater.status != AppUpdater.STATUS.READY_FOR_RESTART &&
appUpdater.status != AppUpdater.STATUS.DOWNLOAD_FAILED
lazy.appUpdater.status != lazy.AppUpdater.STATUS.READY_FOR_RESTART &&
lazy.appUpdater.status != lazy.AppUpdater.STATUS.DOWNLOAD_FAILED
) {
return;
}
appUpdater.removeListener(listener);
if (appUpdater.status == AppUpdater.STATUS.READY_FOR_RESTART) {
lazy.appUpdater.removeListener(listener);
if (lazy.appUpdater.status == lazy.AppUpdater.STATUS.READY_FOR_RESTART) {
restartBrowser();
}
resolve();
};
appUpdater.addListener(listener);
appUpdater.startDownload();
lazy.appUpdater.addListener(listener);
lazy.appUpdater.startDownload();
});
}
function openClearHistoryDialog() {
let window = BrowserWindowTracker.getTopWindow();
let window = lazy.BrowserWindowTracker.getTopWindow();
// The behaviour of the Clear Recent History dialog in PBM does
// not have the expected effect (bug 463607).
if (PrivateBrowsingUtils.isWindowPrivate(window)) {
if (lazy.PrivateBrowsingUtils.isWindowPrivate(window)) {
return;
}
Sanitizer.showUI(window);
lazy.Sanitizer.showUI(window);
}
function restartBrowser() {
@ -813,9 +816,9 @@ function restartBrowser() {
}
function resetBrowser() {
if (!ResetProfile.resetSupported()) {
if (!lazy.ResetProfile.resetSupported()) {
return;
}
let window = BrowserWindowTracker.getTopWindow();
ResetProfile.openConfirmationDialog(window);
let window = lazy.BrowserWindowTracker.getTopWindow();
lazy.ResetProfile.openConfirmationDialog(window);
}

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

@ -19,7 +19,9 @@ const { SkippableTimer, UrlbarProvider, UrlbarUtils } = ChromeUtils.import(
"resource:///modules/UrlbarUtils.jsm"
);
XPCOMUtils.defineLazyModuleGetters(this, {
const lazy = {};
XPCOMUtils.defineLazyModuleGetters(lazy, {
ExtensionSearchHandler: "resource://gre/modules/ExtensionSearchHandler.jsm",
UrlbarResult: "resource:///modules/UrlbarResult.jsm",
});
@ -67,7 +69,7 @@ class ProviderOmnibox extends UrlbarProvider {
if (
queryContext.tokens[0] &&
queryContext.tokens[0].value.length &&
ExtensionSearchHandler.isKeywordRegistered(
lazy.ExtensionSearchHandler.isKeywordRegistered(
queryContext.tokens[0].value
) &&
UrlbarUtils.substringAfter(
@ -82,8 +84,8 @@ class ProviderOmnibox extends UrlbarProvider {
// query but cancelQuery can be called multiple times per query.
// The frequent cancels can cause the extension's state to drift from the
// provider's state.
if (ExtensionSearchHandler.hasActiveInputSession()) {
ExtensionSearchHandler.handleInputCancelled();
if (lazy.ExtensionSearchHandler.hasActiveInputSession()) {
lazy.ExtensionSearchHandler.handleInputCancelled();
}
return false;
@ -115,11 +117,11 @@ class ProviderOmnibox extends UrlbarProvider {
// Fetch heuristic result.
let keyword = queryContext.tokens[0].value;
let description = ExtensionSearchHandler.getDescription(keyword);
let heuristicResult = new UrlbarResult(
let description = lazy.ExtensionSearchHandler.getDescription(keyword);
let heuristicResult = new lazy.UrlbarResult(
UrlbarUtils.RESULT_TYPE.OMNIBOX,
UrlbarUtils.RESULT_SOURCE.OTHER_NETWORK,
...UrlbarResult.payloadAndSimpleHighlights(queryContext.tokens, {
...lazy.UrlbarResult.payloadAndSimpleHighlights(queryContext.tokens, {
title: [description, UrlbarUtils.HIGHLIGHT.TYPED],
content: [queryContext.searchString, UrlbarUtils.HIGHLIGHT.TYPED],
keyword: [queryContext.tokens[0].value, UrlbarUtils.HIGHLIGHT.TYPED],
@ -135,7 +137,7 @@ class ProviderOmnibox extends UrlbarProvider {
text: queryContext.searchString,
inPrivateWindow: queryContext.isPrivate,
};
this._resultsPromise = ExtensionSearchHandler.handleSearch(
this._resultsPromise = lazy.ExtensionSearchHandler.handleSearch(
data,
suggestions => {
if (instance != this.queryInstance) {
@ -146,18 +148,21 @@ class ProviderOmnibox extends UrlbarProvider {
if (content == heuristicResult.payload.content) {
continue;
}
let result = new UrlbarResult(
let result = new lazy.UrlbarResult(
UrlbarUtils.RESULT_TYPE.OMNIBOX,
UrlbarUtils.RESULT_SOURCE.OTHER_NETWORK,
...UrlbarResult.payloadAndSimpleHighlights(queryContext.tokens, {
title: [suggestion.description, UrlbarUtils.HIGHLIGHT.TYPED],
content: [content, UrlbarUtils.HIGHLIGHT.TYPED],
keyword: [
queryContext.tokens[0].value,
UrlbarUtils.HIGHLIGHT.TYPED,
],
icon: UrlbarUtils.ICON.EXTENSION,
})
...lazy.UrlbarResult.payloadAndSimpleHighlights(
queryContext.tokens,
{
title: [suggestion.description, UrlbarUtils.HIGHLIGHT.TYPED],
content: [content, UrlbarUtils.HIGHLIGHT.TYPED],
keyword: [
queryContext.tokens[0].value,
UrlbarUtils.HIGHLIGHT.TYPED,
],
icon: UrlbarUtils.ICON.EXTENSION,
}
)
);
addCallback(this, result);
}

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

@ -19,7 +19,9 @@ const { UrlbarProvider, UrlbarUtils } = ChromeUtils.import(
"resource:///modules/UrlbarUtils.jsm"
);
XPCOMUtils.defineLazyModuleGetters(this, {
const lazy = {};
XPCOMUtils.defineLazyModuleGetters(lazy, {
PlacesUtils: "resource://gre/modules/PlacesUtils.jsm",
UrlbarProvidersManager: "resource:///modules/UrlbarProvidersManager.jsm",
UrlbarResult: "resource:///modules/UrlbarResult.jsm",
@ -104,7 +106,7 @@ class UrlbarProviderOpenTabs extends UrlbarProvider {
* Copy over cached open tabs to the memory table once the Urlbar
* connection has been initialized.
*/
static promiseDBPopulated = PlacesUtils.largeCacheDBConnDeferred.promise.then(
static promiseDBPopulated = lazy.PlacesUtils.largeCacheDBConnDeferred.promise.then(
async () => {
// Must be set before populating.
UrlbarProviderOpenTabs.memoryTableInitialized = true;
@ -172,7 +174,7 @@ class UrlbarProviderOpenTabs extends UrlbarProvider {
// TODO:
// * properly search and handle tokens, this is just a mock for now.
let instance = this.queryInstance;
let conn = await PlacesUtils.promiseLargeCacheDBConnection();
let conn = await lazy.PlacesUtils.promiseLargeCacheDBConnection();
await UrlbarProviderOpenTabs.promiseDBPopulated;
await conn.executeCached(
`
@ -187,7 +189,7 @@ class UrlbarProviderOpenTabs extends UrlbarProvider {
}
addCallback(
this,
new UrlbarResult(
new lazy.UrlbarResult(
UrlbarUtils.RESULT_TYPE.TAB_SWITCH,
UrlbarUtils.RESULT_SOURCE.TABS,
{
@ -211,8 +213,8 @@ async function addToMemoryTable(url, userContextId) {
if (!UrlbarProviderOpenTabs.memoryTableInitialized) {
return;
}
await UrlbarProvidersManager.runInCriticalSection(async () => {
let conn = await PlacesUtils.promiseLargeCacheDBConnection();
await lazy.UrlbarProvidersManager.runInCriticalSection(async () => {
let conn = await lazy.PlacesUtils.promiseLargeCacheDBConnection();
await conn.executeCached(
`
INSERT OR REPLACE INTO moz_openpages_temp (url, userContextId, open_count)
@ -241,8 +243,8 @@ async function removeFromMemoryTable(url, userContextId) {
if (!UrlbarProviderOpenTabs.memoryTableInitialized) {
return;
}
await UrlbarProvidersManager.runInCriticalSection(async () => {
let conn = await PlacesUtils.promiseLargeCacheDBConnection();
await lazy.UrlbarProvidersManager.runInCriticalSection(async () => {
let conn = await lazy.PlacesUtils.promiseLargeCacheDBConnection();
await conn.executeCached(
`
UPDATE moz_openpages_temp

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

@ -107,7 +107,9 @@ const { UrlbarProvider, UrlbarUtils } = ChromeUtils.import(
"resource:///modules/UrlbarUtils.jsm"
);
XPCOMUtils.defineLazyModuleGetters(this, {
const lazy = {};
XPCOMUtils.defineLazyModuleGetters(lazy, {
KeywordUtils: "resource://gre/modules/KeywordUtils.jsm",
ObjectUtils: "resource://gre/modules/ObjectUtils.jsm",
PlacesUtils: "resource://gre/modules/PlacesUtils.jsm",
@ -128,19 +130,19 @@ function setTimeout(callback, ms) {
}
// Maps restriction character types to textual behaviors.
XPCOMUtils.defineLazyGetter(this, "typeToBehaviorMap", () => {
XPCOMUtils.defineLazyGetter(lazy, "typeToBehaviorMap", () => {
return new Map([
[UrlbarTokenizer.TYPE.RESTRICT_HISTORY, "history"],
[UrlbarTokenizer.TYPE.RESTRICT_BOOKMARK, "bookmark"],
[UrlbarTokenizer.TYPE.RESTRICT_TAG, "tag"],
[UrlbarTokenizer.TYPE.RESTRICT_OPENPAGE, "openpage"],
[UrlbarTokenizer.TYPE.RESTRICT_SEARCH, "search"],
[UrlbarTokenizer.TYPE.RESTRICT_TITLE, "title"],
[UrlbarTokenizer.TYPE.RESTRICT_URL, "url"],
[lazy.UrlbarTokenizer.TYPE.RESTRICT_HISTORY, "history"],
[lazy.UrlbarTokenizer.TYPE.RESTRICT_BOOKMARK, "bookmark"],
[lazy.UrlbarTokenizer.TYPE.RESTRICT_TAG, "tag"],
[lazy.UrlbarTokenizer.TYPE.RESTRICT_OPENPAGE, "openpage"],
[lazy.UrlbarTokenizer.TYPE.RESTRICT_SEARCH, "search"],
[lazy.UrlbarTokenizer.TYPE.RESTRICT_TITLE, "title"],
[lazy.UrlbarTokenizer.TYPE.RESTRICT_URL, "url"],
]);
});
XPCOMUtils.defineLazyGetter(this, "sourceToBehaviorMap", () => {
XPCOMUtils.defineLazyGetter(lazy, "sourceToBehaviorMap", () => {
return new Map([
[UrlbarUtils.RESULT_SOURCE.HISTORY, "history"],
[UrlbarUtils.RESULT_SOURCE.BOOKMARKS, "bookmark"],
@ -165,7 +167,7 @@ XPCOMUtils.defineLazyGetter(this, "sourceToBehaviorMap", () => {
*/
function makeKeyForMatch(match) {
let key, prefix;
let action = PlacesUtils.parseActionUrl(match.value);
let action = lazy.PlacesUtils.parseActionUrl(match.value);
if (!action) {
[key, prefix] = UrlbarUtils.stripPrefixAndTrim(match.value, {
stripHttp: true,
@ -281,16 +283,16 @@ function convertLegacyMatches(context, matches, urls) {
* @returns {object} an UrlbarResult
*/
function makeUrlbarResult(tokens, info) {
let action = PlacesUtils.parseActionUrl(info.url);
let action = lazy.PlacesUtils.parseActionUrl(info.url);
if (action) {
switch (action.type) {
case "searchengine": {
if (action.params.isSearchHistory) {
// Return a form history result.
return new UrlbarResult(
return new lazy.UrlbarResult(
UrlbarUtils.RESULT_TYPE.SEARCH,
UrlbarUtils.RESULT_SOURCE.HISTORY,
...UrlbarResult.payloadAndSimpleHighlights(tokens, {
...lazy.UrlbarResult.payloadAndSimpleHighlights(tokens, {
engine: action.params.engineName,
suggestion: [
action.params.searchSuggestion,
@ -301,10 +303,10 @@ function makeUrlbarResult(tokens, info) {
);
}
return new UrlbarResult(
return new lazy.UrlbarResult(
UrlbarUtils.RESULT_TYPE.SEARCH,
UrlbarUtils.RESULT_SOURCE.SEARCH,
...UrlbarResult.payloadAndSimpleHighlights(tokens, {
...lazy.UrlbarResult.payloadAndSimpleHighlights(tokens, {
engine: [action.params.engineName, UrlbarUtils.HIGHLIGHT.TYPED],
suggestion: [
action.params.searchSuggestion,
@ -321,20 +323,20 @@ function makeUrlbarResult(tokens, info) {
);
}
case "switchtab":
return new UrlbarResult(
return new lazy.UrlbarResult(
UrlbarUtils.RESULT_TYPE.TAB_SWITCH,
UrlbarUtils.RESULT_SOURCE.TABS,
...UrlbarResult.payloadAndSimpleHighlights(tokens, {
...lazy.UrlbarResult.payloadAndSimpleHighlights(tokens, {
url: [action.params.url, UrlbarUtils.HIGHLIGHT.TYPED],
title: [info.comment, UrlbarUtils.HIGHLIGHT.TYPED],
icon: info.icon,
})
);
case "visiturl":
return new UrlbarResult(
return new lazy.UrlbarResult(
UrlbarUtils.RESULT_TYPE.URL,
UrlbarUtils.RESULT_SOURCE.OTHER_LOCAL,
...UrlbarResult.payloadAndSimpleHighlights(tokens, {
...lazy.UrlbarResult.payloadAndSimpleHighlights(tokens, {
title: [info.comment, UrlbarUtils.HIGHLIGHT.TYPED],
url: [action.params.url, UrlbarUtils.HIGHLIGHT.TYPED],
icon: info.icon,
@ -386,10 +388,10 @@ function makeUrlbarResult(tokens, info) {
.sort();
}
return new UrlbarResult(
return new lazy.UrlbarResult(
UrlbarUtils.RESULT_TYPE.URL,
source,
...UrlbarResult.payloadAndSimpleHighlights(tokens, {
...lazy.UrlbarResult.payloadAndSimpleHighlights(tokens, {
url: [info.url, UrlbarUtils.HIGHLIGHT.TYPED],
icon: info.icon,
title: [comment, UrlbarUtils.HIGHLIGHT.TYPED],
@ -426,7 +428,7 @@ function Search(queryContext, listener, provider) {
this._matchBehavior = Ci.mozIPlacesAutoComplete.MATCH_BOUNDARY;
// Set the default behavior for this search.
this._behavior = this._searchString
? UrlbarPrefs.get("defaultBehavior")
? lazy.UrlbarPrefs.get("defaultBehavior")
: this._emptySearchDefaultBehavior;
this._inPrivateWindow = queryContext.isPrivate;
@ -442,14 +444,14 @@ function Search(queryContext, listener, provider) {
this._filterOnHost = engine.getResultDomain();
}
this._userContextId = UrlbarProviderOpenTabs.getUserContextIdForOpenPagesTable(
this._userContextId = lazy.UrlbarProviderOpenTabs.getUserContextIdForOpenPagesTable(
this._userContextId,
this._inPrivateWindow
);
// Use the original string here, not the stripped one, so the tokenizer can
// properly recognize token types.
let { tokens } = UrlbarTokenizer.tokenize({
let { tokens } = lazy.UrlbarTokenizer.tokenize({
searchString: unescapedSearchString,
trimmedSearchString: unescapedSearchString.trim(),
});
@ -458,9 +460,9 @@ function Search(queryContext, listener, provider) {
this._leadingRestrictionToken = null;
if (tokens.length) {
if (
UrlbarTokenizer.isRestrictionToken(tokens[0]) &&
lazy.UrlbarTokenizer.isRestrictionToken(tokens[0]) &&
(tokens.length > 1 ||
tokens[0].type == UrlbarTokenizer.TYPE.RESTRICT_SEARCH)
tokens[0].type == lazy.UrlbarTokenizer.TYPE.RESTRICT_SEARCH)
) {
this._leadingRestrictionToken = tokens[0].value;
}
@ -486,11 +488,11 @@ function Search(queryContext, listener, provider) {
if (
queryContext &&
queryContext.restrictSource &&
sourceToBehaviorMap.has(queryContext.restrictSource)
lazy.sourceToBehaviorMap.has(queryContext.restrictSource)
) {
this._behavior = 0;
this.setBehavior("restrict");
let behavior = sourceToBehaviorMap.get(queryContext.restrictSource);
let behavior = lazy.sourceToBehaviorMap.get(queryContext.restrictSource);
this.setBehavior(behavior);
// When we are in restrict mode, all the tokens are valid for searching, so
@ -511,7 +513,7 @@ function Search(queryContext, listener, provider) {
// Set the right JavaScript behavior based on our preference. Note that the
// preference is whether or not we should filter JavaScript, and the
// behavior is if we should search it or not.
if (!UrlbarPrefs.get("filter.javascript")) {
if (!lazy.UrlbarPrefs.get("filter.javascript")) {
this.setBehavior("javascript");
}
@ -567,11 +569,11 @@ Search.prototype = {
// Set the proper behavior while filtering tokens.
let filtered = [];
for (let token of tokens) {
if (!UrlbarTokenizer.isRestrictionToken(token)) {
if (!lazy.UrlbarTokenizer.isRestrictionToken(token)) {
filtered.push(token);
continue;
}
let behavior = typeToBehaviorMap.get(token.type);
let behavior = lazy.typeToBehaviorMap.get(token.type);
if (!behavior) {
throw new Error(`Unknown token type ${token.type}`);
}
@ -632,7 +634,7 @@ Search.prototype = {
// Used by stop() to interrupt an eventual running statement.
this.interrupt = () => {
// Interrupt any ongoing statement to run the search sooner.
if (!UrlbarProvidersManager.interruptLevel) {
if (!lazy.UrlbarProvidersManager.interruptLevel) {
conn.interrupt();
}
};
@ -643,7 +645,7 @@ Search.prototype = {
// If the query is simply "@" and we have tokenAliasEngines then return
// early. UrlbarProviderTokenAliasEngines will add engine results.
let tokenAliasEngines = await UrlbarSearchUtils.tokenAliasEngines();
let tokenAliasEngines = await lazy.UrlbarSearchUtils.tokenAliasEngines();
if (this._trimmedOriginalSearchString == "@" && tokenAliasEngines.length) {
this._provider.finishSearch(true);
return;
@ -663,7 +665,7 @@ Search.prototype = {
// UrlbarProviderSearchSuggestions will handle suggestions, if any.
let emptySearchRestriction =
this._trimmedOriginalSearchString.length <= 3 &&
this._leadingRestrictionToken == UrlbarTokenizer.RESTRICT.SEARCH &&
this._leadingRestrictionToken == lazy.UrlbarTokenizer.RESTRICT.SEARCH &&
/\s*\S?$/.test(this._trimmedOriginalSearchString);
if (
emptySearchRestriction ||
@ -714,7 +716,7 @@ Search.prototype = {
return false;
}
let aliasEngine = await UrlbarSearchUtils.engineForAlias(
let aliasEngine = await lazy.UrlbarSearchUtils.engineForAlias(
this._heuristicToken,
this._originalSearchString
);
@ -723,7 +725,7 @@ Search.prototype = {
return true;
}
let { entry } = await KeywordUtils.getBindableKeyword(
let { entry } = await lazy.KeywordUtils.getBindableKeyword(
this._heuristicToken,
this._originalSearchString
);
@ -846,7 +848,7 @@ Search.prototype = {
// already checked that the typed query is a subset of the search history
// query above with this._searchTokens.every(...).
if (
!UrlbarSearchUtils.serpsAreEquivalent(
!lazy.UrlbarSearchUtils.serpsAreEquivalent(
historyUrl,
generatedSuggestionUrl,
[parseResult.termsParameterName]
@ -889,10 +891,13 @@ Search.prototype = {
// Restyle past searches, unless they are bookmarks or special results.
if (
match.style == "favicon" &&
(UrlbarPrefs.get("restyleSearches") || this._searchModeEngine)
(lazy.UrlbarPrefs.get("restyleSearches") || this._searchModeEngine)
) {
let restyled = this._maybeRestyleSearchMatch(match);
if (restyled && UrlbarPrefs.get("maxHistoricalSearchSuggestions") == 0) {
if (
restyled &&
lazy.UrlbarPrefs.get("maxHistoricalSearchSuggestions") == 0
) {
// The user doesn't want search history.
return;
}
@ -935,7 +940,7 @@ Search.prototype = {
let [urlMapKey, prefix, action] = makeKeyForMatch(match);
if (
(match.placeId && this._usedPlaceIds.has(match.placeId)) ||
this._usedURLs.some(e => ObjectUtils.deepEqual(e.key, urlMapKey))
this._usedURLs.some(e => lazy.ObjectUtils.deepEqual(e.key, urlMapKey))
) {
let isDupe = true;
if (action && ["switchtab", "remotetab"].includes(action.type)) {
@ -943,7 +948,7 @@ Search.prototype = {
// among current matches.
for (let i = 0; i < this._usedURLs.length; ++i) {
let { key: matchKey, action: matchAction } = this._usedURLs[i];
if (ObjectUtils.deepEqual(matchKey, urlMapKey)) {
if (lazy.ObjectUtils.deepEqual(matchKey, urlMapKey)) {
isDupe = true;
if (!matchAction || action.type == "switchtab") {
this._usedURLs[i] = {
@ -974,7 +979,7 @@ Search.prototype = {
let { key: existingKey, prefix: existingPrefix } = this._usedURLs[i];
let existingPrefixRank = UrlbarUtils.getPrefixRank(existingPrefix);
if (ObjectUtils.deepEqual(existingKey, urlMapKey)) {
if (lazy.ObjectUtils.deepEqual(existingKey, urlMapKey)) {
isDupe = true;
if (prefix == existingPrefix) {
@ -1027,7 +1032,7 @@ Search.prototype = {
let index = 0;
if (!this._groups) {
this._groups = [];
this._makeGroups(UrlbarPrefs.get("resultGroups"), this._maxResults);
this._makeGroups(lazy.UrlbarPrefs.get("resultGroups"), this._maxResults);
}
let replace = 0;
@ -1180,7 +1185,7 @@ Search.prototype = {
// This means removing less interesting urls, like redirects or
// non-bookmarked title-less pages.
if (UrlbarPrefs.get("restyleSearches") || this._searchModeEngine) {
if (lazy.UrlbarPrefs.get("restyleSearches") || this._searchModeEngine) {
// If restyle is enabled, we want to filter out redirect targets,
// because sources are urls built using search engines definitions that
// we can reverse-parse.
@ -1249,9 +1254,9 @@ Search.prototype = {
// Otherwise, it is bookmarks, if they are enabled. If both history and
// bookmarks are disabled, it defaults to open pages.
let val = Ci.mozIPlacesAutoComplete.BEHAVIOR_RESTRICT;
if (UrlbarPrefs.get("suggest.history")) {
if (lazy.UrlbarPrefs.get("suggest.history")) {
val |= Ci.mozIPlacesAutoComplete.BEHAVIOR_HISTORY;
} else if (UrlbarPrefs.get("suggest.bookmark")) {
} else if (lazy.UrlbarPrefs.get("suggest.bookmark")) {
val |= Ci.mozIPlacesAutoComplete.BEHAVIOR_BOOKMARK;
} else {
val |= Ci.mozIPlacesAutoComplete.BEHAVIOR_OPENPAGE;
@ -1282,7 +1287,7 @@ Search.prototype = {
*/
get _searchQuery() {
let params = {
parent: PlacesUtils.tagsFolderId,
parent: lazy.PlacesUtils.tagsFolderId,
query_type: QUERYTYPE_FILTERED,
matchBehavior: this._matchBehavior,
searchBehavior: this._behavior,
@ -1397,10 +1402,10 @@ class ProviderPlaces extends UrlbarProvider {
getDatabaseHandle() {
if (!this._promiseDatabase) {
this._promiseDatabase = (async () => {
let conn = await PlacesUtils.promiseLargeCacheDBConnection();
let conn = await lazy.PlacesUtils.promiseLargeCacheDBConnection();
// We don't catch exceptions here as it is too late to block shutdown.
Sqlite.shutdown.addBlocker("UrlbarProviderPlaces closing", () => {
lazy.Sqlite.shutdown.addBlocker("UrlbarProviderPlaces closing", () => {
// Break a possible cycle through the
// previous result, the controller and
// ourselves.
@ -1427,7 +1432,7 @@ class ProviderPlaces extends UrlbarProvider {
if (
!queryContext.trimmedSearchString &&
queryContext.searchMode?.engineName &&
UrlbarPrefs.get("update2.emptySearchBehavior") < 2
lazy.UrlbarPrefs.get("update2.emptySearchBehavior") < 2
) {
return false;
}
@ -1505,7 +1510,7 @@ class ProviderPlaces extends UrlbarProvider {
}
_startLegacyQuery(queryContext, callback) {
let deferred = PromiseUtils.defer();
let deferred = lazy.PromiseUtils.defer();
let listener = (matches, searchOngoing) => {
callback(matches);
if (!searchOngoing) {

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

@ -21,7 +21,9 @@ const { UrlbarProvider, UrlbarUtils } = ChromeUtils.import(
"resource:///modules/UrlbarUtils.jsm"
);
XPCOMUtils.defineLazyModuleGetters(this, {
const lazy = {};
XPCOMUtils.defineLazyModuleGetters(lazy, {
ProfileAge: "resource://gre/modules/ProfileAge.jsm",
UrlbarPrefs: "resource:///modules/UrlbarPrefs.jsm",
UrlbarResult: "resource:///modules/UrlbarResult.jsm",
@ -44,7 +46,7 @@ function PreloadedSite(url, title) {
* populate(sites) : populates the storage with array of [url,title]
* sites[]: resulting array of sites (PreloadedSite objects)
*/
XPCOMUtils.defineLazyGetter(this, "PreloadedSiteStorage", () =>
XPCOMUtils.defineLazyGetter(lazy, "PreloadedSiteStorage", () =>
Object.seal({
sites: [],
@ -62,8 +64,8 @@ XPCOMUtils.defineLazyGetter(this, "PreloadedSiteStorage", () =>
})
);
XPCOMUtils.defineLazyGetter(this, "ProfileAgeCreatedPromise", async () => {
let times = await ProfileAge();
XPCOMUtils.defineLazyGetter(lazy, "ProfileAgeCreatedPromise", async () => {
let times = await lazy.ProfileAge();
return times.created;
});
@ -74,10 +76,10 @@ class ProviderPreloadedSites extends UrlbarProvider {
constructor() {
super();
if (UrlbarPrefs.get("usepreloadedtopurls.enabled")) {
if (lazy.UrlbarPrefs.get("usepreloadedtopurls.enabled")) {
fetch("chrome://browser/content/urlbar/preloaded-top-urls.json")
.then(response => response.json())
.then(sites => PreloadedSiteStorage.populate(sites))
.then(sites => lazy.PreloadedSiteStorage.populate(sites))
.catch(ex => this.logger.error(ex));
}
}
@ -119,12 +121,12 @@ class ProviderPreloadedSites extends UrlbarProvider {
return false;
}
if (!UrlbarPrefs.get("usepreloadedtopurls.enabled")) {
if (!lazy.UrlbarPrefs.get("usepreloadedtopurls.enabled")) {
return false;
}
if (
!UrlbarPrefs.get("autoFill") ||
!lazy.UrlbarPrefs.get("autoFill") ||
!queryContext.allowAutofill ||
queryContext.tokens.length != 1
) {
@ -148,7 +150,7 @@ class ProviderPreloadedSites extends UrlbarProvider {
// As an optimization, don't try to autofill if the search term includes any
// whitespace.
if (UrlbarTokenizer.REGEXP_SPACES.test(queryContext.searchString)) {
if (lazy.UrlbarTokenizer.REGEXP_SPACES.test(queryContext.searchString)) {
return false;
}
@ -185,17 +187,17 @@ class ProviderPreloadedSites extends UrlbarProvider {
}
// Now, add non-autofill preloaded sites.
for (let site of PreloadedSiteStorage.sites) {
for (let site of lazy.PreloadedSiteStorage.sites) {
let url = site.uri.spec;
if (
(!this._strippedPrefix || url.startsWith(this._strippedPrefix)) &&
(site.uri.host.includes(this._lowerCaseSearchString) ||
site._matchTitle.includes(this._lowerCaseSearchString))
) {
let result = new UrlbarResult(
let result = new lazy.UrlbarResult(
UrlbarUtils.RESULT_TYPE.URL,
UrlbarUtils.RESULT_SOURCE.OTHER_LOCAL,
...UrlbarResult.payloadAndSimpleHighlights(queryContext.tokens, {
...lazy.UrlbarResult.payloadAndSimpleHighlights(queryContext.tokens, {
title: [site.title, UrlbarUtils.HIGHLIGHT.TYPED],
url: [url, UrlbarUtils.HIGHLIGHT.TYPED],
icon: UrlbarUtils.getIconForUrl(url),
@ -224,11 +226,11 @@ class ProviderPreloadedSites extends UrlbarProvider {
* the format.
*/
populatePreloadedSiteStorage(list) {
PreloadedSiteStorage.populate(list);
lazy.PreloadedSiteStorage.populate(list);
}
async _getAutofillResult(queryContext) {
let matchedSite = PreloadedSiteStorage.sites.find(site => {
let matchedSite = lazy.PreloadedSiteStorage.sites.find(site => {
return (
(!this._strippedPrefix ||
site.uri.spec.startsWith(this._strippedPrefix)) &&
@ -248,10 +250,10 @@ class ProviderPreloadedSites extends UrlbarProvider {
trimSlash: !this._searchString.includes("/"),
});
let result = new UrlbarResult(
let result = new lazy.UrlbarResult(
UrlbarUtils.RESULT_TYPE.URL,
UrlbarUtils.RESULT_SOURCE.OTHER_LOCAL,
...UrlbarResult.payloadAndSimpleHighlights(queryContext.tokens, {
...lazy.UrlbarResult.payloadAndSimpleHighlights(queryContext.tokens, {
title: [title, UrlbarUtils.HIGHLIGHT.TYPED],
url: [url, UrlbarUtils.HIGHLIGHT.TYPED],
icon: UrlbarUtils.getIconForUrl(url),
@ -274,15 +276,15 @@ class ProviderPreloadedSites extends UrlbarProvider {
}
async _checkPreloadedSitesExpiry() {
if (!UrlbarPrefs.get("usepreloadedtopurls.enabled")) {
if (!lazy.UrlbarPrefs.get("usepreloadedtopurls.enabled")) {
return;
}
let profileCreationDate = await ProfileAgeCreatedPromise;
let profileCreationDate = await lazy.ProfileAgeCreatedPromise;
let daysSinceProfileCreation =
(Date.now() - profileCreationDate) / MS_PER_DAY;
if (
daysSinceProfileCreation >
UrlbarPrefs.get("usepreloadedtopurls.expire_days")
lazy.UrlbarPrefs.get("usepreloadedtopurls.expire_days")
) {
Services.prefs.setBoolPref(
"browser.urlbar.usepreloadedtopurls.enabled",

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

@ -19,7 +19,9 @@ const { SkippableTimer, UrlbarProvider, UrlbarUtils } = ChromeUtils.import(
"resource:///modules/UrlbarUtils.jsm"
);
XPCOMUtils.defineLazyModuleGetters(this, {
const lazy = {};
XPCOMUtils.defineLazyModuleGetters(lazy, {
UrlbarResult: "resource:///modules/UrlbarResult.jsm",
UrlbarSearchUtils: "resource:///modules/UrlbarSearchUtils.jsm",
UrlbarTokenizer: "resource:///modules/UrlbarTokenizer.jsm",
@ -60,7 +62,7 @@ class ProviderPrivateSearch extends UrlbarProvider {
*/
isActive(queryContext) {
return (
UrlbarSearchUtils.separatePrivateDefaultUIEnabled &&
lazy.UrlbarSearchUtils.separatePrivateDefaultUIEnabled &&
!queryContext.isPrivate &&
queryContext.tokens.length
);
@ -77,7 +79,7 @@ class ProviderPrivateSearch extends UrlbarProvider {
let searchString = queryContext.trimmedSearchString;
if (
queryContext.tokens.some(
t => t.type == UrlbarTokenizer.TYPE.RESTRICT_SEARCH
t => t.type == lazy.UrlbarTokenizer.TYPE.RESTRICT_SEARCH
)
) {
if (queryContext.tokens.length == 1) {
@ -86,7 +88,7 @@ class ProviderPrivateSearch extends UrlbarProvider {
}
// Remove the restriction char from the search string.
searchString = queryContext.tokens
.filter(t => t.type != UrlbarTokenizer.TYPE.RESTRICT_SEARCH)
.filter(t => t.type != lazy.UrlbarTokenizer.TYPE.RESTRICT_SEARCH)
.map(t => t.value)
.join(" ");
}
@ -97,7 +99,7 @@ class ProviderPrivateSearch extends UrlbarProvider {
? Services.search.getEngineByName(queryContext.searchMode.engineName)
: await Services.search.getDefaultPrivate();
let isPrivateEngine =
UrlbarSearchUtils.separatePrivateDefault &&
lazy.UrlbarSearchUtils.separatePrivateDefault &&
engine != (await Services.search.getDefault());
this.logger.info(`isPrivateEngine: ${isPrivateEngine}`);
@ -115,10 +117,10 @@ class ProviderPrivateSearch extends UrlbarProvider {
return;
}
let result = new UrlbarResult(
let result = new lazy.UrlbarResult(
UrlbarUtils.RESULT_TYPE.SEARCH,
UrlbarUtils.RESULT_SOURCE.SEARCH,
...UrlbarResult.payloadAndSimpleHighlights(queryContext.tokens, {
...lazy.UrlbarResult.payloadAndSimpleHighlights(queryContext.tokens, {
engine: [engine.name, UrlbarUtils.HIGHLIGHT.TYPED],
query: [searchString, UrlbarUtils.HIGHLIGHT.NONE],
icon: engine.iconURI?.spec,

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

@ -14,7 +14,8 @@ const { UrlbarProvider, UrlbarUtils } = ChromeUtils.import(
"resource:///modules/UrlbarUtils.jsm"
);
XPCOMUtils.defineLazyModuleGetters(this, {
const lazy = {};
XPCOMUtils.defineLazyModuleGetters(lazy, {
QuickActionsLoaderDefault:
"resource:///modules/QuickActionsLoaderDefault.jsm",
UrlbarPrefs: "resource:///modules/UrlbarPrefs.jsm",
@ -43,9 +44,9 @@ const SUGGESTED_INDEX = 1;
class ProviderQuickActions extends UrlbarProvider {
constructor() {
super();
UrlbarResult.addDynamicResultType(DYNAMIC_TYPE_NAME);
lazy.UrlbarResult.addDynamicResultType(DYNAMIC_TYPE_NAME);
Services.tm.idleDispatchToMainThread(() =>
QuickActionsLoaderDefault.load()
lazy.QuickActionsLoaderDefault.load()
);
}
@ -80,9 +81,9 @@ class ProviderQuickActions extends UrlbarProvider {
*/
isActive(queryContext) {
return (
UrlbarPrefs.get(ENABLED_PREF) &&
lazy.UrlbarPrefs.get(ENABLED_PREF) &&
(!queryContext.restrictSource ||
queryContext.restrictSource == UrlbarTokenizer.RESTRICT.ACTIONS) &&
queryContext.restrictSource == lazy.UrlbarTokenizer.RESTRICT.ACTIONS) &&
!queryContext.searchMode
);
}
@ -117,7 +118,7 @@ class ProviderQuickActions extends UrlbarProvider {
results.length = ACTIONS_SHOWN_FOCUS;
}
const result = new UrlbarResult(
const result = new lazy.UrlbarResult(
UrlbarUtils.RESULT_TYPE.DYNAMIC,
UrlbarUtils.RESULT_SOURCE.ACTIONS,
{

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

@ -18,7 +18,9 @@ const {
UrlbarUtils,
} = ChromeUtils.import("resource:///modules/UrlbarUtils.jsm");
XPCOMUtils.defineLazyModuleGetters(this, {
const lazy = {};
XPCOMUtils.defineLazyModuleGetters(lazy, {
AsyncShutdown: "resource://gre/modules/AsyncShutdown.jsm",
clearInterval: "resource://gre/modules/Timer.jsm",
CONTEXTUAL_SERVICES_PING_TYPES:
@ -108,19 +110,21 @@ class ProviderQuickSuggest extends UrlbarProvider {
constructor(...args) {
super(...args);
UrlbarQuickSuggest.init();
UrlbarQuickSuggest.on("config-set", () => this._validateImpressionStats());
lazy.UrlbarQuickSuggest.init();
lazy.UrlbarQuickSuggest.on("config-set", () =>
this._validateImpressionStats()
);
this._updateFeatureState();
NimbusFeatures.urlbar.onUpdate(() => this._updateFeatureState());
lazy.NimbusFeatures.urlbar.onUpdate(() => this._updateFeatureState());
UrlbarPrefs.addObserver(this);
lazy.UrlbarPrefs.addObserver(this);
// Periodically record impression counters reset telemetry.
this._setImpressionCountersResetInterval();
// On shutdown, record any final impression counters reset telemetry.
AsyncShutdown.profileChangeTeardown.addBlocker(
lazy.AsyncShutdown.profileChangeTeardown.addBlocker(
"UrlbarProviderQuickSuggest: Record impression counters reset telemetry",
() => this._resetElapsedImpressionCounters()
);
@ -209,10 +213,10 @@ class ProviderQuickSuggest extends UrlbarProvider {
queryContext.trimmedSearchString &&
!queryContext.searchMode &&
!queryContext.isPrivate &&
UrlbarPrefs.get("quickSuggestEnabled") &&
(UrlbarPrefs.get("suggest.quicksuggest.nonsponsored") ||
UrlbarPrefs.get("suggest.quicksuggest.sponsored") ||
UrlbarPrefs.get("quicksuggest.dataCollection.enabled"))
lazy.UrlbarPrefs.get("quickSuggestEnabled") &&
(lazy.UrlbarPrefs.get("suggest.quicksuggest.nonsponsored") ||
lazy.UrlbarPrefs.get("suggest.quicksuggest.sponsored") ||
lazy.UrlbarPrefs.get("quicksuggest.dataCollection.enabled"))
);
}
@ -234,14 +238,14 @@ class ProviderQuickSuggest extends UrlbarProvider {
// There are two sources for quick suggest: remote settings (from
// `UrlbarQuickSuggest`) and Merino.
let promises = [];
if (UrlbarPrefs.get("quickSuggestRemoteSettingsEnabled")) {
if (lazy.UrlbarPrefs.get("quickSuggestRemoteSettingsEnabled")) {
promises.push(
this._fetchRemoteSettingsSuggestions(queryContext, searchString)
);
}
if (
UrlbarPrefs.get("merinoEnabled") &&
UrlbarPrefs.get("quicksuggest.dataCollection.enabled") &&
lazy.UrlbarPrefs.get("merinoEnabled") &&
lazy.UrlbarPrefs.get("quicksuggest.dataCollection.enabled") &&
queryContext.allowRemoteResults()
) {
promises.push(this._fetchMerinoSuggestions(queryContext, searchString));
@ -298,8 +302,8 @@ class ProviderQuickSuggest extends UrlbarProvider {
let isSuggestionBestMatch = false;
if (typeof suggestion._test_is_best_match == "boolean") {
isSuggestionBestMatch = suggestion._test_is_best_match;
} else if (UrlbarQuickSuggest.config.best_match) {
let { best_match } = UrlbarQuickSuggest.config;
} else if (lazy.UrlbarQuickSuggest.config.best_match) {
let { best_match } = lazy.UrlbarQuickSuggest.config;
isSuggestionBestMatch =
best_match.min_search_string_length <= searchString.length &&
!best_match.blocked_suggestion_ids.includes(suggestion.block_id);
@ -308,8 +312,8 @@ class ProviderQuickSuggest extends UrlbarProvider {
// Determine if the urlbar result should be a best match.
let isResultBestMatch =
isSuggestionBestMatch &&
UrlbarPrefs.get("bestMatchEnabled") &&
UrlbarPrefs.get("suggest.bestmatch");
lazy.UrlbarPrefs.get("bestMatchEnabled") &&
lazy.UrlbarPrefs.get("suggest.bestmatch");
if (isResultBestMatch) {
// Show the result as a best match. Best match titles don't include the
// `full_keyword`, and the user's search string is highlighted.
@ -324,10 +328,13 @@ class ProviderQuickSuggest extends UrlbarProvider {
];
}
let result = new UrlbarResult(
let result = new lazy.UrlbarResult(
UrlbarUtils.RESULT_TYPE.URL,
UrlbarUtils.RESULT_SOURCE.SEARCH,
...UrlbarResult.payloadAndSimpleHighlights(queryContext.tokens, payload)
...lazy.UrlbarResult.payloadAndSimpleHighlights(
queryContext.tokens,
payload
)
);
if (isResultBestMatch) {
@ -335,12 +342,12 @@ class ProviderQuickSuggest extends UrlbarProvider {
result.suggestedIndex = 1;
} else if (
!isNaN(suggestion.position) &&
UrlbarPrefs.get("quickSuggestAllowPositionInSuggestions")
lazy.UrlbarPrefs.get("quickSuggestAllowPositionInSuggestions")
) {
result.suggestedIndex = suggestion.position;
} else {
result.isSuggestedIndexRelativeToGroup = true;
result.suggestedIndex = UrlbarPrefs.get(
result.suggestedIndex = lazy.UrlbarPrefs.get(
suggestion.is_sponsored
? "quickSuggestSponsoredIndex"
: "quickSuggestNonSponsoredIndex"
@ -364,18 +371,18 @@ class ProviderQuickSuggest extends UrlbarProvider {
// Else if the user is not in a modal experiment:
// Record the event
if (
UrlbarPrefs.get("isBestMatchExperiment") ||
UrlbarPrefs.get("experimentType") === "best-match"
lazy.UrlbarPrefs.get("isBestMatchExperiment") ||
lazy.UrlbarPrefs.get("experimentType") === "best-match"
) {
if (
isSuggestionBestMatch &&
(!UrlbarPrefs.get("bestMatchEnabled") ||
UrlbarPrefs.get("suggest.bestmatch"))
(!lazy.UrlbarPrefs.get("bestMatchEnabled") ||
lazy.UrlbarPrefs.get("suggest.bestmatch"))
) {
UrlbarQuickSuggest.ensureExposureEventRecorded();
lazy.UrlbarQuickSuggest.ensureExposureEventRecorded();
}
} else if (UrlbarPrefs.get("experimentType") !== "modal") {
UrlbarQuickSuggest.ensureExposureEventRecorded();
} else if (lazy.UrlbarPrefs.get("experimentType") !== "modal") {
lazy.UrlbarQuickSuggest.ensureExposureEventRecorded();
}
}
@ -394,8 +401,8 @@ class ProviderQuickSuggest extends UrlbarProvider {
blockResult(queryContext, result) {
if (
(!result.isBestMatch &&
!UrlbarPrefs.get("quickSuggestBlockingEnabled")) ||
(result.isBestMatch && !UrlbarPrefs.get("bestMatchBlockingEnabled"))
!lazy.UrlbarPrefs.get("quickSuggestBlockingEnabled")) ||
(result.isBestMatch && !lazy.UrlbarPrefs.get("bestMatchBlockingEnabled"))
) {
this.logger.info("Blocking disabled, ignoring block");
return false;
@ -423,7 +430,7 @@ class ProviderQuickSuggest extends UrlbarProvider {
let json = JSON.stringify([...this._blockedDigests]);
this._updatingBlockedDigests = true;
try {
UrlbarPrefs.set("quicksuggest.blockedDigests", json);
lazy.UrlbarPrefs.set("quicksuggest.blockedDigests", json);
} finally {
this._updatingBlockedDigests = false;
}
@ -459,7 +466,7 @@ class ProviderQuickSuggest extends UrlbarProvider {
await this._blockTaskQueue.queue(() => {
this.logger.info(`Clearing all blocked suggestions`);
this._blockedDigests.clear();
UrlbarPrefs.clear("quicksuggest.blockedDigests");
lazy.UrlbarPrefs.clear("quicksuggest.blockedDigests");
});
}
@ -631,7 +638,7 @@ class ProviderQuickSuggest extends UrlbarProvider {
// Always use lowercase to make the reporting consistent
advertiser: result.payload.sponsoredAdvertiser.toLocaleLowerCase(),
block_id: result.payload.sponsoredBlockId,
improve_suggest_experience_checked: UrlbarPrefs.get(
improve_suggest_experience_checked: lazy.UrlbarPrefs.get(
"quicksuggest.dataCollection.enabled"
),
position: telemetryResultIndex,
@ -639,34 +646,34 @@ class ProviderQuickSuggest extends UrlbarProvider {
};
// impression
PartnerLinkAttribution.sendContextualServicesPing(
lazy.PartnerLinkAttribution.sendContextualServicesPing(
{
...payload,
is_clicked,
reporting_url: result.payload.sponsoredImpressionUrl,
},
CONTEXTUAL_SERVICES_PING_TYPES.QS_IMPRESSION
lazy.CONTEXTUAL_SERVICES_PING_TYPES.QS_IMPRESSION
);
// click
if (is_clicked) {
PartnerLinkAttribution.sendContextualServicesPing(
lazy.PartnerLinkAttribution.sendContextualServicesPing(
{
...payload,
reporting_url: result.payload.sponsoredClickUrl,
},
CONTEXTUAL_SERVICES_PING_TYPES.QS_SELECTION
lazy.CONTEXTUAL_SERVICES_PING_TYPES.QS_SELECTION
);
}
// block
if (selType == "block") {
PartnerLinkAttribution.sendContextualServicesPing(
lazy.PartnerLinkAttribution.sendContextualServicesPing(
{
...payload,
iab_category: result.payload.sponsoredIabCategory,
},
CONTEXTUAL_SERVICES_PING_TYPES.QS_BLOCK
lazy.CONTEXTUAL_SERVICES_PING_TYPES.QS_BLOCK
);
}
}
@ -697,29 +704,29 @@ class ProviderQuickSuggest extends UrlbarProvider {
}
break;
case "quicksuggest.dataCollection.enabled":
if (!UrlbarPrefs.updatingFirefoxSuggestScenario) {
if (!lazy.UrlbarPrefs.updatingFirefoxSuggestScenario) {
Services.telemetry.recordEvent(
TELEMETRY_EVENT_CATEGORY,
"data_collect_toggled",
UrlbarPrefs.get(pref) ? "enabled" : "disabled"
lazy.UrlbarPrefs.get(pref) ? "enabled" : "disabled"
);
}
break;
case "suggest.quicksuggest.nonsponsored":
if (!UrlbarPrefs.updatingFirefoxSuggestScenario) {
if (!lazy.UrlbarPrefs.updatingFirefoxSuggestScenario) {
Services.telemetry.recordEvent(
TELEMETRY_EVENT_CATEGORY,
"enable_toggled",
UrlbarPrefs.get(pref) ? "enabled" : "disabled"
lazy.UrlbarPrefs.get(pref) ? "enabled" : "disabled"
);
}
break;
case "suggest.quicksuggest.sponsored":
if (!UrlbarPrefs.updatingFirefoxSuggestScenario) {
if (!lazy.UrlbarPrefs.updatingFirefoxSuggestScenario) {
Services.telemetry.recordEvent(
TELEMETRY_EVENT_CATEGORY,
"sponsored_toggled",
UrlbarPrefs.get(pref) ? "enabled" : "disabled"
lazy.UrlbarPrefs.get(pref) ? "enabled" : "disabled"
);
}
break;
@ -815,7 +822,7 @@ class ProviderQuickSuggest extends UrlbarProvider {
let suggestions;
TelemetryStopwatch.start(TELEMETRY_REMOTE_SETTINGS_LATENCY, queryContext);
try {
suggestions = await UrlbarQuickSuggest.query(searchString);
suggestions = await lazy.UrlbarQuickSuggest.query(searchString);
TelemetryStopwatch.finish(
TELEMETRY_REMOTE_SETTINGS_LATENCY,
queryContext
@ -866,7 +873,7 @@ class ProviderQuickSuggest extends UrlbarProvider {
// Get the endpoint URL. It's empty by default when running tests so they
// don't hit the network.
let endpointString = UrlbarPrefs.get("merino.endpointURL");
let endpointString = lazy.UrlbarPrefs.get("merino.endpointURL");
if (!endpointString) {
return null;
}
@ -884,17 +891,17 @@ class ProviderQuickSuggest extends UrlbarProvider {
this._merinoSequenceNumber
);
let clientVariants = UrlbarPrefs.get("merino.clientVariants");
let clientVariants = lazy.UrlbarPrefs.get("merino.clientVariants");
if (clientVariants) {
url.searchParams.set(MERINO_PARAMS.CLIENT_VARIANTS, clientVariants);
}
let providers = UrlbarPrefs.get("merino.providers");
let providers = lazy.UrlbarPrefs.get("merino.providers");
if (providers) {
url.searchParams.set(MERINO_PARAMS.PROVIDERS, providers);
} else if (
!UrlbarPrefs.get("suggest.quicksuggest.nonsponsored") &&
!UrlbarPrefs.get("suggest.quicksuggest.sponsored")
!lazy.UrlbarPrefs.get("suggest.quicksuggest.nonsponsored") &&
!lazy.UrlbarPrefs.get("suggest.quicksuggest.sponsored")
) {
// Data collection is enabled but suggestions are not. Set the providers
// param to an empty string to tell Merino not to fetch any suggestions.
@ -910,7 +917,7 @@ class ProviderQuickSuggest extends UrlbarProvider {
};
// Set up the timeout timer.
let timeout = UrlbarPrefs.get("merinoTimeoutMs");
let timeout = lazy.UrlbarPrefs.get("merinoTimeoutMs");
let timer = (this._merinoTimeoutTimer = new SkippableTimer({
name: "Merino timeout",
time: timeout,
@ -1036,9 +1043,9 @@ class ProviderQuickSuggest extends UrlbarProvider {
// Return false if suggestions are disabled.
if (
(suggestion.is_sponsored &&
!UrlbarPrefs.get("suggest.quicksuggest.sponsored")) ||
!lazy.UrlbarPrefs.get("suggest.quicksuggest.sponsored")) ||
(!suggestion.is_sponsored &&
!UrlbarPrefs.get("suggest.quicksuggest.nonsponsored"))
!lazy.UrlbarPrefs.get("suggest.quicksuggest.nonsponsored"))
) {
this.logger.info("Suggestions disabled, not adding suggestion");
return false;
@ -1047,9 +1054,9 @@ class ProviderQuickSuggest extends UrlbarProvider {
// Return false if an impression cap has been hit.
if (
(suggestion.is_sponsored &&
UrlbarPrefs.get("quickSuggestImpressionCapsSponsoredEnabled")) ||
lazy.UrlbarPrefs.get("quickSuggestImpressionCapsSponsoredEnabled")) ||
(!suggestion.is_sponsored &&
UrlbarPrefs.get("quickSuggestImpressionCapsNonSponsoredEnabled"))
lazy.UrlbarPrefs.get("quickSuggestImpressionCapsNonSponsoredEnabled"))
) {
this._resetElapsedImpressionCounters();
let type = suggestion.is_sponsored ? "sponsored" : "nonsponsored";
@ -1130,16 +1137,16 @@ class ProviderQuickSuggest extends UrlbarProvider {
JSON.stringify({
isSponsored,
currentStats: this._impressionStats,
impression_caps: UrlbarQuickSuggest.config.impression_caps,
impression_caps: lazy.UrlbarQuickSuggest.config.impression_caps,
})
);
// Don't bother recording anything if caps are disabled.
if (
(isSponsored &&
!UrlbarPrefs.get("quickSuggestImpressionCapsSponsoredEnabled")) ||
!lazy.UrlbarPrefs.get("quickSuggestImpressionCapsSponsoredEnabled")) ||
(!isSponsored &&
!UrlbarPrefs.get("quickSuggestImpressionCapsNonSponsoredEnabled"))
!lazy.UrlbarPrefs.get("quickSuggestImpressionCapsNonSponsoredEnabled"))
) {
this.logger.info("Impression caps disabled, skipping update");
return;
@ -1175,7 +1182,7 @@ class ProviderQuickSuggest extends UrlbarProvider {
// Save the stats.
this._updatingImpressionStats = true;
try {
UrlbarPrefs.set(
lazy.UrlbarPrefs.set(
"quicksuggest.impressionCaps.stats",
JSON.stringify(this._impressionStats)
);
@ -1191,7 +1198,7 @@ class ProviderQuickSuggest extends UrlbarProvider {
* Loads and validates impression stats.
*/
_loadImpressionStats() {
let json = UrlbarPrefs.get("quicksuggest.impressionCaps.stats");
let json = lazy.UrlbarPrefs.get("quicksuggest.impressionCaps.stats");
if (!json) {
this._impressionStats = {};
} else {
@ -1218,7 +1225,7 @@ class ProviderQuickSuggest extends UrlbarProvider {
* for more info.
*/
_validateImpressionStats() {
let { impression_caps } = UrlbarQuickSuggest.config;
let { impression_caps } = lazy.UrlbarQuickSuggest.config;
this.logger.info("Validating impression stats");
this.logger.debug(
@ -1339,7 +1346,7 @@ class ProviderQuickSuggest extends UrlbarProvider {
this.logger.debug(
JSON.stringify({
currentStats: this._impressionStats,
impression_caps: UrlbarQuickSuggest.config.impression_caps,
impression_caps: lazy.UrlbarQuickSuggest.config.impression_caps,
})
);
@ -1462,9 +1469,9 @@ class ProviderQuickSuggest extends UrlbarProvider {
ms = IMPRESSION_COUNTERS_RESET_INTERVAL_MS
) {
if (this._impressionCountersResetInterval) {
clearInterval(this._impressionCountersResetInterval);
lazy.clearInterval(this._impressionCountersResetInterval);
}
this._impressionCountersResetInterval = setInterval(
this._impressionCountersResetInterval = lazy.setInterval(
() => this._resetElapsedImpressionCounters(),
ms
);
@ -1489,7 +1496,7 @@ class ProviderQuickSuggest extends UrlbarProvider {
this.logger.debug(`Queueing _loadBlockedDigests`);
await this._blockTaskQueue.queue(() => {
this.logger.info(`Loading blocked suggestion digests`);
let json = UrlbarPrefs.get("quicksuggest.blockedDigests");
let json = lazy.UrlbarPrefs.get("quicksuggest.blockedDigests");
this.logger.debug(
`browser.urlbar.quicksuggest.blockedDigests value: ${json}`
);
@ -1527,7 +1534,7 @@ class ProviderQuickSuggest extends UrlbarProvider {
* Updates state based on the `browser.urlbar.quicksuggest.enabled` pref.
*/
_updateFeatureState() {
let enabled = UrlbarPrefs.get("quickSuggestEnabled");
let enabled = lazy.UrlbarPrefs.get("quickSuggestEnabled");
if (enabled == this._quickSuggestEnabled) {
// This method is a Nimbus `onUpdate()` callback, which means it's called
// each time any pref is changed that is a fallback for a Nimbus variable.

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

@ -19,7 +19,9 @@ const { UrlbarProvider, UrlbarUtils } = ChromeUtils.import(
"resource:///modules/UrlbarUtils.jsm"
);
XPCOMUtils.defineLazyModuleGetters(this, {
const lazy = {};
XPCOMUtils.defineLazyModuleGetters(lazy, {
PlacesUtils: "resource://gre/modules/PlacesUtils.jsm",
SyncedTabs: "resource://services-sync/SyncedTabs.jsm",
UrlbarPrefs: "resource:///modules/UrlbarPrefs.jsm",
@ -34,7 +36,7 @@ let _cache = null;
// are found.
const RECENT_REMOTE_TAB_THRESHOLD_MS = 72 * 60 * 60 * 1000; // 72 hours.
XPCOMUtils.defineLazyGetter(this, "weaveXPCService", function() {
XPCOMUtils.defineLazyGetter(lazy, "weaveXPCService", function() {
try {
return Cc["@mozilla.org/weave/service;1"].getService(
Ci.nsISupports
@ -46,21 +48,21 @@ XPCOMUtils.defineLazyGetter(this, "weaveXPCService", function() {
});
XPCOMUtils.defineLazyPreferenceGetter(
this,
lazy,
"showRemoteIconsPref",
"services.sync.syncedTabs.showRemoteIcons",
true
);
XPCOMUtils.defineLazyPreferenceGetter(
this,
lazy,
"showRemoteTabsPref",
"services.sync.syncedTabs.showRemoteTabs",
true
);
XPCOMUtils.defineLazyPreferenceGetter(
this,
lazy,
"syncUsernamePref",
"services.sync.username"
);
@ -103,13 +105,13 @@ class ProviderRemoteTabs extends UrlbarProvider {
*/
isActive(queryContext) {
return (
syncUsernamePref &&
showRemoteTabsPref &&
UrlbarPrefs.get("suggest.remotetab") &&
lazy.syncUsernamePref &&
lazy.showRemoteTabsPref &&
lazy.UrlbarPrefs.get("suggest.remotetab") &&
queryContext.sources.includes(UrlbarUtils.RESULT_SOURCE.TABS) &&
weaveXPCService &&
weaveXPCService.ready &&
weaveXPCService.enabled
lazy.weaveXPCService &&
lazy.weaveXPCService.ready &&
lazy.weaveXPCService.enabled
);
}
@ -137,30 +139,30 @@ class ProviderRemoteTabs extends UrlbarProvider {
for (let { tab, client } of tabsData) {
if (
!searchString ||
searchString == UrlbarTokenizer.RESTRICT.OPENPAGE ||
searchString == lazy.UrlbarTokenizer.RESTRICT.OPENPAGE ||
re.test(tab.url) ||
(tab.title && re.test(tab.title))
) {
if (showRemoteIconsPref) {
if (lazy.showRemoteIconsPref) {
if (!tab.icon) {
// It's rare that Sync supplies the icon for the page. If it does, it is a
// string URL.
tab.icon = UrlbarUtils.getIconForUrl(tab.url);
} else {
tab.icon = PlacesUtils.favicons.getFaviconLinkForIcon(
tab.icon = lazy.PlacesUtils.favicons.getFaviconLinkForIcon(
Services.io.newURI(tab.icon)
).spec;
}
}
let result = new UrlbarResult(
let result = new lazy.UrlbarResult(
UrlbarUtils.RESULT_TYPE.REMOTE_TAB,
UrlbarUtils.RESULT_SOURCE.TABS,
...UrlbarResult.payloadAndSimpleHighlights(queryContext.tokens, {
...lazy.UrlbarResult.payloadAndSimpleHighlights(queryContext.tokens, {
url: [tab.url, UrlbarUtils.HIGHLIGHT.TYPED],
title: [tab.title, UrlbarUtils.HIGHLIGHT.TYPED],
device: client.name,
icon: showRemoteIconsPref ? tab.icon : "",
icon: lazy.showRemoteIconsPref ? tab.icon : "",
lastUsed: (tab.lastUsed || 0) * 1000,
})
);
@ -208,9 +210,9 @@ class ProviderRemoteTabs extends UrlbarProvider {
// being signed in), don't reach in to Weave.Service as that may initialize
// Sync unnecessarily - we'll get an observer notification later when it
// becomes ready and has synced a list of tabs.
if (weaveXPCService.ready) {
let clients = await SyncedTabs.getTabClients();
SyncedTabs.sortTabClientsByLastUsed(clients);
if (lazy.weaveXPCService.ready) {
let clients = await lazy.SyncedTabs.getTabClients();
lazy.SyncedTabs.sortTabClientsByLastUsed(clients);
for (let client of clients) {
for (let tab of client.tabs) {
tabsData.push({ tab, client });

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

@ -19,7 +19,9 @@ const { SkippableTimer, UrlbarProvider, UrlbarUtils } = ChromeUtils.import(
"resource:///modules/UrlbarUtils.jsm"
);
XPCOMUtils.defineLazyModuleGetters(this, {
const lazy = {};
XPCOMUtils.defineLazyModuleGetters(lazy, {
SearchSuggestionController:
"resource://gre/modules/SearchSuggestionController.jsm",
UrlbarPrefs: "resource:///modules/UrlbarPrefs.jsm",
@ -38,7 +40,7 @@ XPCOMUtils.defineLazyModuleGetters(this, {
function looksLikeUrl(str, ignoreAlphanumericHosts = false) {
// Single word including special chars.
return (
!UrlbarTokenizer.REGEXP_SPACES.test(str) &&
!lazy.UrlbarTokenizer.REGEXP_SPACES.test(str) &&
(["/", "@", ":", "["].some(c => str.includes(c)) ||
(ignoreAlphanumericHosts
? /^([\[\]A-Z0-9-]+\.){3,}[^.]+$/i.test(str)
@ -102,9 +104,9 @@ class ProviderSearchSuggestions extends UrlbarProvider {
}
let wantsLocalSuggestions =
UrlbarPrefs.get("maxHistoricalSearchSuggestions") &&
lazy.UrlbarPrefs.get("maxHistoricalSearchSuggestions") &&
(queryContext.trimmedSearchString ||
UrlbarPrefs.get("update2.emptySearchBehavior") != 0);
lazy.UrlbarPrefs.get("update2.emptySearchBehavior") != 0);
return wantsLocalSuggestions || this._allowRemoteSuggestions(queryContext);
}
@ -123,7 +125,7 @@ class ProviderSearchSuggestions extends UrlbarProvider {
(queryContext.restrictSource &&
queryContext.restrictSource == UrlbarUtils.RESULT_SOURCE.SEARCH) ||
queryContext.tokens.some(
t => t.type == UrlbarTokenizer.TYPE.RESTRICT_SEARCH
t => t.type == lazy.UrlbarTokenizer.TYPE.RESTRICT_SEARCH
) ||
(queryContext.searchMode &&
queryContext.sources.includes(UrlbarUtils.RESULT_SOURCE.SEARCH))
@ -143,11 +145,11 @@ class ProviderSearchSuggestions extends UrlbarProvider {
if (
// If the user typed a restriction token or token alias, we ignore the
// pref to disable suggestions in the Urlbar.
(!UrlbarPrefs.get("suggest.searches") &&
(!lazy.UrlbarPrefs.get("suggest.searches") &&
!this._isTokenOrRestrictionPresent(queryContext)) ||
!UrlbarPrefs.get("browser.search.suggest.enabled") ||
!lazy.UrlbarPrefs.get("browser.search.suggest.enabled") ||
(queryContext.isPrivate &&
!UrlbarPrefs.get("browser.search.suggest.enabled.private"))
!lazy.UrlbarPrefs.get("browser.search.suggest.enabled.private"))
) {
return false;
}
@ -231,9 +233,10 @@ class ProviderSearchSuggestions extends UrlbarProvider {
let leadingRestrictionToken = null;
if (
UrlbarTokenizer.isRestrictionToken(queryContext.tokens[0]) &&
lazy.UrlbarTokenizer.isRestrictionToken(queryContext.tokens[0]) &&
(queryContext.tokens.length > 1 ||
queryContext.tokens[0].type == UrlbarTokenizer.TYPE.RESTRICT_SEARCH)
queryContext.tokens[0].type ==
lazy.UrlbarTokenizer.TYPE.RESTRICT_SEARCH)
) {
leadingRestrictionToken = queryContext.tokens[0].value;
}
@ -242,7 +245,7 @@ class ProviderSearchSuggestions extends UrlbarProvider {
// when the search shortcut is used and it's not user typed. Don't strip
// other restriction chars, so that it's possible to search for things
// including one of those (e.g. "c#").
if (leadingRestrictionToken === UrlbarTokenizer.RESTRICT.SEARCH) {
if (leadingRestrictionToken === lazy.UrlbarTokenizer.RESTRICT.SEARCH) {
query = UrlbarUtils.substringAfter(query, leadingRestrictionToken).trim();
}
@ -255,7 +258,7 @@ class ProviderSearchSuggestions extends UrlbarProvider {
queryContext.searchMode.engineName
);
} else {
engine = UrlbarSearchUtils.getDefaultEngine(queryContext.isPrivate);
engine = lazy.UrlbarSearchUtils.getDefaultEngine(queryContext.isPrivate);
}
if (!engine) {
@ -304,7 +307,7 @@ class ProviderSearchSuggestions extends UrlbarProvider {
return null;
}
this._suggestionsController = new SearchSuggestionController();
this._suggestionsController = new lazy.SearchSuggestionController();
this._suggestionsController.formHistoryParam = queryContext.formHistoryName;
// If there's a form history entry that equals the search string, the search
@ -347,7 +350,7 @@ class ProviderSearchSuggestions extends UrlbarProvider {
// show form history at all. With the introduction of flexed result
// groups, we now use it only as a boolean: Zero means don't show form
// history at all (as before), non-zero means show it.
if (UrlbarPrefs.get("maxHistoricalSearchSuggestions")) {
if (lazy.UrlbarPrefs.get("maxHistoricalSearchSuggestions")) {
for (let entry of fetchData.local) {
results.push(makeFormHistoryResult(queryContext, engine, entry));
}
@ -359,7 +362,7 @@ class ProviderSearchSuggestions extends UrlbarProvider {
if (
allowRemote &&
!fetchData.remote.length &&
searchString.length > UrlbarPrefs.get("maxCharsForSearchSuggestions")
searchString.length > lazy.UrlbarPrefs.get("maxCharsForSearchSuggestions")
) {
this._lastLowResultsSearchSuggestion = searchString;
}
@ -390,7 +393,7 @@ class ProviderSearchSuggestions extends UrlbarProvider {
let tailPrefix = entry.matchPrefix;
// Skip tail suggestions if the pref is disabled.
if (tail && !UrlbarPrefs.get("richSuggestions.tail")) {
if (tail && !lazy.UrlbarPrefs.get("richSuggestions.tail")) {
continue;
}
@ -400,20 +403,26 @@ class ProviderSearchSuggestions extends UrlbarProvider {
try {
results.push(
new UrlbarResult(
new lazy.UrlbarResult(
UrlbarUtils.RESULT_TYPE.SEARCH,
UrlbarUtils.RESULT_SOURCE.SEARCH,
...UrlbarResult.payloadAndSimpleHighlights(queryContext.tokens, {
engine: [engine.name, UrlbarUtils.HIGHLIGHT.TYPED],
suggestion: [entry.value, UrlbarUtils.HIGHLIGHT.SUGGESTED],
lowerCaseSuggestion: entry.value.toLocaleLowerCase(),
tailPrefix,
tail: [tail, UrlbarUtils.HIGHLIGHT.SUGGESTED],
tailOffsetIndex: tail ? entry.tailOffsetIndex : undefined,
keyword: [alias ? alias : undefined, UrlbarUtils.HIGHLIGHT.TYPED],
query: [searchString.trim(), UrlbarUtils.HIGHLIGHT.NONE],
icon: !entry.value ? engine.iconURI?.spec : undefined,
})
...lazy.UrlbarResult.payloadAndSimpleHighlights(
queryContext.tokens,
{
engine: [engine.name, UrlbarUtils.HIGHLIGHT.TYPED],
suggestion: [entry.value, UrlbarUtils.HIGHLIGHT.SUGGESTED],
lowerCaseSuggestion: entry.value.toLocaleLowerCase(),
tailPrefix,
tail: [tail, UrlbarUtils.HIGHLIGHT.SUGGESTED],
tailOffsetIndex: tail ? entry.tailOffsetIndex : undefined,
keyword: [
alias ? alias : undefined,
UrlbarUtils.HIGHLIGHT.TYPED,
],
query: [searchString.trim(), UrlbarUtils.HIGHLIGHT.NONE],
icon: !entry.value ? engine.iconURI?.spec : undefined,
}
)
)
);
} catch (err) {
@ -457,12 +466,14 @@ class ProviderSearchSuggestions extends UrlbarProvider {
// Match an alias only when it has a space after it. If there's no trailing
// space, then continue to treat it as part of the search string.
if (!UrlbarTokenizer.REGEXP_SPACES_START.test(query)) {
if (!lazy.UrlbarTokenizer.REGEXP_SPACES_START.test(query)) {
return null;
}
// Check if the user entered an engine alias directly.
let engineMatch = await UrlbarSearchUtils.engineForAlias(possibleAlias);
let engineMatch = await lazy.UrlbarSearchUtils.engineForAlias(
possibleAlias
);
if (engineMatch) {
return {
engine: engineMatch,
@ -476,10 +487,10 @@ class ProviderSearchSuggestions extends UrlbarProvider {
}
function makeFormHistoryResult(queryContext, engine, entry) {
return new UrlbarResult(
return new lazy.UrlbarResult(
UrlbarUtils.RESULT_TYPE.SEARCH,
UrlbarUtils.RESULT_SOURCE.HISTORY,
...UrlbarResult.payloadAndSimpleHighlights(queryContext.tokens, {
...lazy.UrlbarResult.payloadAndSimpleHighlights(queryContext.tokens, {
engine: engine.name,
suggestion: [entry.value, UrlbarUtils.HIGHLIGHT.SUGGESTED],
lowerCaseSuggestion: entry.value.toLocaleLowerCase(),

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

@ -20,7 +20,9 @@ const { UrlbarProvider, UrlbarUtils } = ChromeUtils.import(
"resource:///modules/UrlbarUtils.jsm"
);
XPCOMUtils.defineLazyModuleGetters(this, {
const lazy = {};
XPCOMUtils.defineLazyModuleGetters(lazy, {
AppMenuNotifications: "resource://gre/modules/AppMenuNotifications.jsm",
DefaultBrowserCheck: "resource:///modules/BrowserGlue.jsm",
BrowserWindowTracker: "resource:///modules/BrowserWindowTracker.jsm",
@ -31,7 +33,7 @@ XPCOMUtils.defineLazyModuleGetters(this, {
UrlbarResult: "resource:///modules/UrlbarResult.jsm",
});
XPCOMUtils.defineLazyGetter(this, "updateManager", () => {
XPCOMUtils.defineLazyGetter(lazy, "updateManager", () => {
return (
Cc["@mozilla.org/updates/update-manager;1"] &&
Cc["@mozilla.org/updates/update-manager;1"].getService(Ci.nsIUpdateManager)
@ -39,7 +41,7 @@ XPCOMUtils.defineLazyGetter(this, "updateManager", () => {
});
XPCOMUtils.defineLazyPreferenceGetter(
this,
lazy,
"cfrFeaturesUserPref",
"browser.newtabpage.activity-stream.asrouter.userprefs.cfr.features",
true
@ -99,7 +101,10 @@ class ProviderSearchTips extends UrlbarProvider {
// example because a tip was already shown.
this.disableTipsForCurrentSession = true;
for (let tip of Object.values(TIPS)) {
if (tip && UrlbarPrefs.get(`tipShownCount.${tip}`) < MAX_SHOWN_COUNT) {
if (
tip &&
lazy.UrlbarPrefs.get(`tipShownCount.${tip}`) < MAX_SHOWN_COUNT
) {
this.disableTipsForCurrentSession = false;
break;
}
@ -121,7 +126,7 @@ class ProviderSearchTips extends UrlbarProvider {
get PRIORITY() {
// Search tips are prioritized over the Places and top sites providers.
return UrlbarProviderTopSites.PRIORITY + 1;
return lazy.UrlbarProviderTopSites.PRIORITY + 1;
}
/**
@ -147,7 +152,7 @@ class ProviderSearchTips extends UrlbarProvider {
* @returns {boolean} Whether this provider should be invoked for the search.
*/
isActive(queryContext) {
return this.currentTip && cfrFeaturesUserPref;
return this.currentTip && lazy.cfrFeaturesUserPref;
}
/**
@ -176,7 +181,7 @@ class ProviderSearchTips extends UrlbarProvider {
let defaultEngine = await Services.search.getDefault();
let result = new UrlbarResult(
let result = new lazy.UrlbarResult(
UrlbarUtils.RESULT_TYPE.TIP,
UrlbarUtils.RESULT_SOURCE.OTHER_LOCAL,
{
@ -222,7 +227,7 @@ class ProviderSearchTips extends UrlbarProvider {
* The result that was picked.
*/
pickResult(result) {
let window = BrowserWindowTracker.getTopWindow();
let window = lazy.BrowserWindowTracker.getTopWindow();
window.gURLBar.value = "";
window.gURLBar.setPageProxyState("invalid");
window.gURLBar.removeAttribute("suppress-focus-border");
@ -255,7 +260,7 @@ class ProviderSearchTips extends UrlbarProvider {
// engaged with the urlbar while the tip was showing. We treat both as the
// user's acknowledgment of the tip, and we don't show tips again in any
// session. Set the shown count to the max.
UrlbarPrefs.set(
lazy.UrlbarPrefs.set(
`tipShownCount.${this.showedTipTypeInCurrentEngagement}`,
MAX_SHOWN_COUNT
);
@ -318,9 +323,9 @@ class ProviderSearchTips extends UrlbarProvider {
// Check if we are supposed to show a tip for the current session.
if (
!cfrFeaturesUserPref ||
!lazy.cfrFeaturesUserPref ||
(this.disableTipsForCurrentSession &&
!UrlbarPrefs.get("searchTips.test.ignoreShowLimits"))
!lazy.UrlbarPrefs.get("searchTips.test.ignoreShowLimits"))
) {
return;
}
@ -354,11 +359,13 @@ class ProviderSearchTips extends UrlbarProvider {
return;
}
let ignoreShowLimits = UrlbarPrefs.get("searchTips.test.ignoreShowLimits");
let ignoreShowLimits = lazy.UrlbarPrefs.get(
"searchTips.test.ignoreShowLimits"
);
// If we've shown this type of tip the maximum number of times over all
// sessions, don't show it again.
let shownCount = UrlbarPrefs.get(`tipShownCount.${tip}`);
let shownCount = lazy.UrlbarPrefs.get(`tipShownCount.${tip}`);
if (shownCount >= MAX_SHOWN_COUNT && !ignoreShowLimits) {
return;
}
@ -370,12 +377,12 @@ class ProviderSearchTips extends UrlbarProvider {
}
// Start a search.
setTimeout(async () => {
lazy.setTimeout(async () => {
if (this._maybeShowTipForUrlInstance != instance) {
return;
}
let window = BrowserWindowTracker.getTopWindow();
let window = lazy.BrowserWindowTracker.getTopWindow();
// We don't want to interrupt a user's typed query with a Search Tip.
// See bugs 1613662 and 1619547.
if (
@ -398,7 +405,7 @@ class ProviderSearchTips extends UrlbarProvider {
this.disableTipsForCurrentSession = true;
// Store the new shown count.
UrlbarPrefs.set(`tipShownCount.${tip}`, shownCount + 1);
lazy.UrlbarPrefs.set(`tipShownCount.${tip}`, shownCount + 1);
this.currentTip = tip;
window.gURLBar.search("", { focus: tip == TIPS.ONBOARD });
@ -407,7 +414,7 @@ class ProviderSearchTips extends UrlbarProvider {
}
async function isBrowserShowingNotification() {
let window = BrowserWindowTracker.getTopWindow();
let window = lazy.BrowserWindowTracker.getTopWindow();
// urlbar view and notification box (info bar)
if (
@ -420,9 +427,9 @@ async function isBrowserShowingNotification() {
// app menu notification doorhanger
if (
AppMenuNotifications.activeNotification &&
!AppMenuNotifications.activeNotification.dismissed &&
!AppMenuNotifications.activeNotification.options.badgeOnly
lazy.AppMenuNotifications.activeNotification &&
!lazy.AppMenuNotifications.activeNotification.dismissed &&
!lazy.AppMenuNotifications.activeNotification.options.badgeOnly
) {
return true;
}
@ -467,7 +474,7 @@ async function isBrowserShowingNotification() {
// On startup, the default browser check normally opens after the Search Tip.
// As a result, we can't check for the prompt's presence, but we can check if
// it plans on opening.
const willPrompt = await DefaultBrowserCheck.willCheckDefaultBrowser(
const willPrompt = await lazy.DefaultBrowserCheck.willCheckDefaultBrowser(
/* isStartupCheck */ false
);
if (willPrompt) {
@ -518,12 +525,12 @@ async function lastBrowserUpdateDate() {
// Get the newest update in the update history. This isn't perfect
// because these dates are when updates are applied, not when the
// user restarts with the update. See bug 1595328.
if (updateManager && updateManager.getUpdateCount()) {
let update = updateManager.getUpdateAt(0);
if (lazy.updateManager && lazy.updateManager.getUpdateCount()) {
let update = lazy.updateManager.getUpdateAt(0);
return update.installDate;
}
// Fall back to the profile age.
let age = await ProfileAge();
let age = await lazy.ProfileAge();
return (await age.firstUse) || age.created;
}

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

@ -20,7 +20,9 @@ const { UrlbarProvider, UrlbarUtils } = ChromeUtils.import(
"resource:///modules/UrlbarUtils.jsm"
);
XPCOMUtils.defineLazyModuleGetters(this, {
const lazy = {};
XPCOMUtils.defineLazyModuleGetters(lazy, {
UrlbarView: "resource:///modules/UrlbarView.jsm",
UrlbarPrefs: "resource:///modules/UrlbarPrefs.jsm",
UrlbarProviderAutofill: "resource:///modules/UrlbarProviderAutofill.jsm",
@ -96,8 +98,8 @@ const VIEW_TEMPLATE = {
* of the provider singleton.
*/
function initializeDynamicResult() {
UrlbarResult.addDynamicResultType(DYNAMIC_RESULT_TYPE);
UrlbarView.addDynamicViewTemplate(DYNAMIC_RESULT_TYPE, VIEW_TEMPLATE);
lazy.UrlbarResult.addDynamicResultType(DYNAMIC_RESULT_TYPE);
lazy.UrlbarView.addDynamicViewTemplate(DYNAMIC_RESULT_TYPE, VIEW_TEMPLATE);
}
/**
@ -140,7 +142,7 @@ class ProviderTabToSearch extends UrlbarProvider {
queryContext.searchString &&
queryContext.tokens.length == 1 &&
!queryContext.searchMode &&
UrlbarPrefs.get("suggest.engines")
lazy.UrlbarPrefs.get("suggest.engines")
);
}
@ -235,12 +237,12 @@ class ProviderTabToSearch extends UrlbarProvider {
(!this.onboardingInteractionAtTime ||
this.onboardingInteractionAtTime < Date.now() - 1000 * 60 * 5)
) {
let interactionsLeft = UrlbarPrefs.get(
let interactionsLeft = lazy.UrlbarPrefs.get(
"tabToSearch.onboard.interactionsLeft"
);
if (interactionsLeft > 0) {
UrlbarPrefs.set(
lazy.UrlbarPrefs.set(
"tabToSearch.onboard.interactionsLeft",
--interactionsLeft
);
@ -275,7 +277,7 @@ class ProviderTabToSearch extends UrlbarProvider {
try {
// urlbar.tabtosearch.* is prerelease-only/opt-in for now. See bug 1686330.
for (let engine of this.enginesShown.regular) {
let scalarKey = UrlbarSearchUtils.getSearchModeScalarKey({
let scalarKey = lazy.UrlbarSearchUtils.getSearchModeScalarKey({
engineName: engine,
});
Services.telemetry.keyedScalarAdd(
@ -285,7 +287,7 @@ class ProviderTabToSearch extends UrlbarProvider {
);
}
for (let engine of this.enginesShown.onboarding) {
let scalarKey = UrlbarSearchUtils.getSearchModeScalarKey({
let scalarKey = lazy.UrlbarSearchUtils.getSearchModeScalarKey({
engineName: engine,
});
Services.telemetry.keyedScalarAdd(
@ -355,7 +357,7 @@ class ProviderTabToSearch extends UrlbarProvider {
);
// Skip any string that cannot be an origin.
if (
!UrlbarTokenizer.looksLikeOrigin(searchStr, {
!lazy.UrlbarTokenizer.looksLikeOrigin(searchStr, {
ignoreKnownDomains: true,
noIp: true,
})
@ -369,15 +371,18 @@ class ProviderTabToSearch extends UrlbarProvider {
}
// Add all matching engines.
let engines = await UrlbarSearchUtils.enginesForDomainPrefix(searchStr, {
matchAllDomainLevels: true,
onlyEnabled: true,
});
let engines = await lazy.UrlbarSearchUtils.enginesForDomainPrefix(
searchStr,
{
matchAllDomainLevels: true,
onlyEnabled: true,
}
);
if (!engines.length) {
return;
}
const onboardingInteractionsLeft = UrlbarPrefs.get(
const onboardingInteractionsLeft = lazy.UrlbarPrefs.get(
"tabToSearch.onboard.interactionsLeft"
);
@ -427,7 +432,7 @@ class ProviderTabToSearch extends UrlbarProvider {
}
}
if (partialMatchEnginesByHost.size) {
let host = await UrlbarProviderAutofill.getTopHostOverThreshold(
let host = await lazy.UrlbarProviderAutofill.getTopHostOverThreshold(
queryContext,
Array.from(partialMatchEnginesByHost.keys())
);
@ -448,7 +453,7 @@ function makeOnboardingResult(engine, satisfiesAutofillThreshold = false) {
stripWww: true,
});
url = url.substr(0, url.length - engine.searchUrlPublicSuffix.length);
let result = new UrlbarResult(
let result = new lazy.UrlbarResult(
UrlbarUtils.RESULT_TYPE.DYNAMIC,
UrlbarUtils.RESULT_SOURCE.SEARCH,
{
@ -470,10 +475,10 @@ function makeResult(context, engine, satisfiesAutofillThreshold = false) {
stripWww: true,
});
url = url.substr(0, url.length - engine.searchUrlPublicSuffix.length);
let result = new UrlbarResult(
let result = new lazy.UrlbarResult(
UrlbarUtils.RESULT_TYPE.SEARCH,
UrlbarUtils.RESULT_SOURCE.SEARCH,
...UrlbarResult.payloadAndSimpleHighlights(context.tokens, {
...lazy.UrlbarResult.payloadAndSimpleHighlights(context.tokens, {
engine: engine.name,
isGeneralPurposeEngine: engine.isGeneralPurposeEngine,
url,

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

@ -18,7 +18,9 @@ const { UrlbarProvider, UrlbarUtils } = ChromeUtils.import(
"resource:///modules/UrlbarUtils.jsm"
);
XPCOMUtils.defineLazyModuleGetters(this, {
const lazy = {};
XPCOMUtils.defineLazyModuleGetters(lazy, {
UrlbarPrefs: "resource:///modules/UrlbarPrefs.jsm",
UrlbarResult: "resource:///modules/UrlbarResult.jsm",
UrlbarSearchUtils: "resource:///modules/UrlbarSearchUtils.jsm",
@ -84,7 +86,7 @@ class ProviderTokenAliasEngines extends UrlbarProvider {
return false;
}
this._engines = await UrlbarSearchUtils.tokenAliasEngines();
this._engines = await lazy.UrlbarSearchUtils.tokenAliasEngines();
if (!this._engines.length) {
return false;
}
@ -99,7 +101,7 @@ class ProviderTokenAliasEngines extends UrlbarProvider {
}
// If the user is typing a potential engine name, autofill it.
if (UrlbarPrefs.get("autoFill") && queryContext.allowAutofill) {
if (lazy.UrlbarPrefs.get("autoFill") && queryContext.allowAutofill) {
let result = this._getAutofillResult(queryContext);
if (result) {
this._autofillData = { result, instance };
@ -133,10 +135,10 @@ class ProviderTokenAliasEngines extends UrlbarProvider {
tokenAliases[0].startsWith(queryContext.trimmedSearchString) &&
engine.name != this._autofillData?.result.payload.engine
) {
let result = new UrlbarResult(
let result = new lazy.UrlbarResult(
UrlbarUtils.RESULT_TYPE.SEARCH,
UrlbarUtils.RESULT_SOURCE.SEARCH,
...UrlbarResult.payloadAndSimpleHighlights(queryContext.tokens, {
...lazy.UrlbarResult.payloadAndSimpleHighlights(queryContext.tokens, {
engine: [engine.name, UrlbarUtils.HIGHLIGHT.TYPED],
keyword: [tokenAliases[0], UrlbarUtils.HIGHLIGHT.TYPED],
query: ["", UrlbarUtils.HIGHLIGHT.TYPED],
@ -183,7 +185,7 @@ class ProviderTokenAliasEngines extends UrlbarProvider {
// alias followed by a space. We enter search mode at that point.
if (
lowerCaseSearchString.startsWith(alias) &&
UrlbarTokenizer.REGEXP_SPACES_START.test(
lazy.UrlbarTokenizer.REGEXP_SPACES_START.test(
lowerCaseSearchString.substring(alias.length)
)
) {
@ -196,16 +198,19 @@ class ProviderTokenAliasEngines extends UrlbarProvider {
queryContext.searchString +
alias.substr(queryContext.searchString.length);
let value = aliasPreservingUserCase + " ";
let result = new UrlbarResult(
let result = new lazy.UrlbarResult(
UrlbarUtils.RESULT_TYPE.SEARCH,
UrlbarUtils.RESULT_SOURCE.SEARCH,
...UrlbarResult.payloadAndSimpleHighlights(queryContext.tokens, {
engine: [engine.name, UrlbarUtils.HIGHLIGHT.TYPED],
keyword: [aliasPreservingUserCase, UrlbarUtils.HIGHLIGHT.TYPED],
query: ["", UrlbarUtils.HIGHLIGHT.TYPED],
icon: engine.iconURI?.spec,
providesSearchMode: true,
})
...lazy.UrlbarResult.payloadAndSimpleHighlights(
queryContext.tokens,
{
engine: [engine.name, UrlbarUtils.HIGHLIGHT.TYPED],
keyword: [aliasPreservingUserCase, UrlbarUtils.HIGHLIGHT.TYPED],
query: ["", UrlbarUtils.HIGHLIGHT.TYPED],
icon: engine.iconURI?.spec,
providesSearchMode: true,
}
)
);
// We set suggestedIndex = 0 instead of the heuristic because we

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

@ -19,7 +19,9 @@ const { UrlbarProvider, UrlbarUtils } = ChromeUtils.import(
"resource:///modules/UrlbarUtils.jsm"
);
XPCOMUtils.defineLazyModuleGetters(this, {
const lazy = {};
XPCOMUtils.defineLazyModuleGetters(lazy, {
AboutNewTab: "resource:///modules/AboutNewTab.jsm",
CONTEXTUAL_SERVICES_PING_TYPES:
"resource:///modules/PartnerLinkAttribution.jsm",
@ -126,7 +128,7 @@ class ProviderTopSites extends UrlbarProvider {
return;
}
let sites = AboutNewTab.getTopSites();
let sites = lazy.AboutNewTab.getTopSites();
let instance = this.queryInstance;
@ -134,7 +136,7 @@ class ProviderTopSites extends UrlbarProvider {
// on about:newtab.
sites = sites.filter(site => site);
if (!UrlbarPrefs.get("sponsoredTopSites")) {
if (!lazy.UrlbarPrefs.get("sponsoredTopSites")) {
sites = sites.filter(site => !site.sponsored_position);
}
@ -146,7 +148,7 @@ class ProviderTopSites extends UrlbarProvider {
this,
"topSitesRows",
"browser.newtabpage.activity-stream.topSitesRows",
TOP_SITES_DEFAULT_ROWS
lazy.TOP_SITES_DEFAULT_ROWS
);
}
@ -154,8 +156,8 @@ class ProviderTopSites extends UrlbarProvider {
// Sites greater than what is visible in the New Tab Page, because the
// additional ones couldn't be managed from the page.
let numTopSites = Math.min(
UrlbarPrefs.get("maxRichResults"),
TOP_SITES_MAX_SITES_PER_ROW * this.topSitesRows
lazy.UrlbarPrefs.get("maxRichResults"),
lazy.TOP_SITES_MAX_SITES_PER_ROW * this.topSitesRows
);
sites = sites.slice(0, numTopSites);
@ -216,18 +218,18 @@ class ProviderTopSites extends UrlbarProvider {
sponsoredClickUrl: site.sponsoredClickUrl,
};
}
let result = new UrlbarResult(
let result = new lazy.UrlbarResult(
UrlbarUtils.RESULT_TYPE.URL,
UrlbarUtils.RESULT_SOURCE.OTHER_LOCAL,
...UrlbarResult.payloadAndSimpleHighlights(
...lazy.UrlbarResult.payloadAndSimpleHighlights(
queryContext.tokens,
payload
)
);
let tabs;
if (UrlbarPrefs.get("suggest.openpage")) {
tabs = UrlbarProviderOpenTabs.getOpenTabs(
if (lazy.UrlbarPrefs.get("suggest.openpage")) {
tabs = lazy.UrlbarProviderOpenTabs.getOpenTabs(
queryContext.userContextId || 0,
queryContext.isPrivate
);
@ -236,8 +238,8 @@ class ProviderTopSites extends UrlbarProvider {
if (tabs && tabs.includes(site.url.replace(/#.*$/, ""))) {
result.type = UrlbarUtils.RESULT_TYPE.TAB_SWITCH;
result.source = UrlbarUtils.RESULT_SOURCE.TABS;
} else if (UrlbarPrefs.get("suggest.bookmark")) {
let bookmark = await PlacesUtils.bookmarks.fetch({
} else if (lazy.UrlbarPrefs.get("suggest.bookmark")) {
let bookmark = await lazy.PlacesUtils.bookmarks.fetch({
url: new URL(result.payload.url),
});
if (bookmark) {
@ -254,7 +256,7 @@ class ProviderTopSites extends UrlbarProvider {
break;
}
case "search": {
let engine = await UrlbarSearchUtils.engineForAlias(site.title);
let engine = await lazy.UrlbarSearchUtils.engineForAlias(site.title);
if (!engine && site.url) {
// Look up the engine by its domain.
@ -264,7 +266,7 @@ class ProviderTopSites extends UrlbarProvider {
} catch (err) {}
if (host) {
engine = (
await UrlbarSearchUtils.enginesForDomainPrefix(host)
await lazy.UrlbarSearchUtils.enginesForDomainPrefix(host)
)[0];
}
}
@ -278,18 +280,21 @@ class ProviderTopSites extends UrlbarProvider {
break;
}
let result = new UrlbarResult(
let result = new lazy.UrlbarResult(
UrlbarUtils.RESULT_TYPE.SEARCH,
UrlbarUtils.RESULT_SOURCE.SEARCH,
...UrlbarResult.payloadAndSimpleHighlights(queryContext.tokens, {
title: site.title,
keyword: site.title,
providesSearchMode: true,
engine: engine.name,
query: "",
icon: site.favicon,
isPinned: site.isPinned,
})
...lazy.UrlbarResult.payloadAndSimpleHighlights(
queryContext.tokens,
{
title: site.title,
keyword: site.title,
providesSearchMode: true,
engine: engine.name,
query: "",
icon: site.favicon,
isPinned: site.isPinned,
}
)
);
addCallback(this, result);
break;
@ -327,7 +332,7 @@ class ProviderTopSites extends UrlbarProvider {
`urlbar_${site.position}`,
1
);
PartnerLinkAttribution.sendContextualServicesPing(
lazy.PartnerLinkAttribution.sendContextualServicesPing(
{
source: "urlbar",
tile_id: site.sponsoredTileId || -1,
@ -335,7 +340,7 @@ class ProviderTopSites extends UrlbarProvider {
reporting_url: site.sponsoredImpressionUrl,
advertiser: site.title.toLocaleLowerCase(),
},
CONTEXTUAL_SERVICES_PING_TYPES.TOPSITES_IMPRESSION
lazy.CONTEXTUAL_SERVICES_PING_TYPES.TOPSITES_IMPRESSION
);
}
}

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

@ -27,14 +27,16 @@ const { UrlbarProvider, UrlbarUtils } = ChromeUtils.import(
"resource:///modules/UrlbarUtils.jsm"
);
XPCOMUtils.defineLazyModuleGetters(this, {
const lazy = {};
XPCOMUtils.defineLazyModuleGetters(lazy, {
UrlbarPrefs: "resource:///modules/UrlbarPrefs.jsm",
UrlbarResult: "resource:///modules/UrlbarResult.jsm",
UrlbarView: "resource:///modules/UrlbarView.jsm",
});
XPCOMUtils.defineLazyServiceGetter(
this,
lazy,
"ClipboardHelper",
"@mozilla.org/widget/clipboardhelper;1",
"nsIClipboardHelper"
@ -84,8 +86,8 @@ const VIEW_TEMPLATE = {
class ProviderUnitConversion extends UrlbarProvider {
constructor() {
super();
UrlbarResult.addDynamicResultType(DYNAMIC_RESULT_TYPE);
UrlbarView.addDynamicViewTemplate(DYNAMIC_RESULT_TYPE, VIEW_TEMPLATE);
lazy.UrlbarResult.addDynamicResultType(DYNAMIC_RESULT_TYPE);
lazy.UrlbarView.addDynamicViewTemplate(DYNAMIC_RESULT_TYPE, VIEW_TEMPLATE);
}
/**
@ -115,7 +117,7 @@ class ProviderUnitConversion extends UrlbarProvider {
* Whether this provider should be invoked for the search.
*/
isActive({ searchString }) {
if (!UrlbarPrefs.get("unitConversion.enabled")) {
if (!lazy.UrlbarPrefs.get("unitConversion.enabled")) {
return false;
}
@ -163,7 +165,7 @@ class ProviderUnitConversion extends UrlbarProvider {
* The callback invoked by this method to add each result.
*/
startQuery(queryContext, addCallback) {
const result = new UrlbarResult(
const result = new lazy.UrlbarResult(
UrlbarUtils.RESULT_TYPE.DYNAMIC,
UrlbarUtils.RESULT_SOURCE.OTHER_LOCAL,
{
@ -172,7 +174,9 @@ class ProviderUnitConversion extends UrlbarProvider {
input: queryContext.searchString,
}
);
result.suggestedIndex = UrlbarPrefs.get("unitConversion.suggestedIndex");
result.suggestedIndex = lazy.UrlbarPrefs.get(
"unitConversion.suggestedIndex"
);
addCallback(this, result);
}
@ -181,7 +185,7 @@ class ProviderUnitConversion extends UrlbarProvider {
const { textContent } = element.querySelector(
".urlbarView-dynamic-unitConversion-output"
);
ClipboardHelper.copyString(textContent);
lazy.ClipboardHelper.copyString(textContent);
}
}

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

@ -14,7 +14,8 @@ var EXPORTED_SYMBOLS = ["UrlbarProvidersManager"];
const { XPCOMUtils } = ChromeUtils.import(
"resource://gre/modules/XPCOMUtils.jsm"
);
XPCOMUtils.defineLazyModuleGetters(this, {
const lazy = {};
XPCOMUtils.defineLazyModuleGetters(lazy, {
ObjectUtils: "resource://gre/modules/ObjectUtils.jsm",
PlacesUtils: "resource://gre/modules/PlacesUtils.jsm",
SkippableTimer: "resource:///modules/UrlbarUtils.jsm",
@ -26,8 +27,8 @@ XPCOMUtils.defineLazyModuleGetters(this, {
UrlbarUtils: "resource:///modules/UrlbarUtils.jsm",
});
XPCOMUtils.defineLazyGetter(this, "logger", () =>
UrlbarUtils.getLogger({ prefix: "ProvidersManager" })
XPCOMUtils.defineLazyGetter(lazy, "logger", () =>
lazy.UrlbarUtils.getLogger({ prefix: "ProvidersManager" })
);
// List of available local providers, each is implemented in its own jsm module
@ -117,19 +118,21 @@ class ProvidersManager {
* @param {object} provider
*/
registerProvider(provider) {
if (!provider || !(provider instanceof UrlbarProvider)) {
if (!provider || !(provider instanceof lazy.UrlbarProvider)) {
throw new Error(`Trying to register an invalid provider`);
}
if (!Object.values(UrlbarUtils.PROVIDER_TYPE).includes(provider.type)) {
if (
!Object.values(lazy.UrlbarUtils.PROVIDER_TYPE).includes(provider.type)
) {
throw new Error(`Unknown provider type ${provider.type}`);
}
logger.info(`Registering provider ${provider.name}`);
lazy.logger.info(`Registering provider ${provider.name}`);
let index = -1;
if (provider.type == UrlbarUtils.PROVIDER_TYPE.HEURISTIC) {
if (provider.type == lazy.UrlbarUtils.PROVIDER_TYPE.HEURISTIC) {
// Keep heuristic providers in order at the front of the array. Find the
// first non-heuristic provider and insert the new provider there.
index = this.providers.findIndex(
p => p.type != UrlbarUtils.PROVIDER_TYPE.HEURISTIC
p => p.type != lazy.UrlbarUtils.PROVIDER_TYPE.HEURISTIC
);
}
if (index < 0) {
@ -143,7 +146,7 @@ class ProvidersManager {
* @param {object} provider
*/
unregisterProvider(provider) {
logger.info(`Unregistering provider ${provider.name}`);
lazy.logger.info(`Unregistering provider ${provider.name}`);
let index = this.providers.findIndex(p => p.name == provider.name);
if (index != -1) {
this.providers.splice(index, 1);
@ -164,10 +167,10 @@ class ProvidersManager {
* @param {object} muxer a UrlbarMuxer object
*/
registerMuxer(muxer) {
if (!muxer || !(muxer instanceof UrlbarMuxer)) {
if (!muxer || !(muxer instanceof lazy.UrlbarMuxer)) {
throw new Error(`Trying to register an invalid muxer`);
}
logger.info(`Registering muxer ${muxer.name}`);
lazy.logger.info(`Registering muxer ${muxer.name}`);
this.muxers.set(muxer.name, muxer);
}
@ -177,7 +180,7 @@ class ProvidersManager {
*/
unregisterMuxer(muxer) {
let muxerName = typeof muxer == "string" ? muxer : muxer.name;
logger.info(`Unregistering muxer ${muxerName}`);
lazy.logger.info(`Unregistering muxer ${muxerName}`);
this.muxers.delete(muxerName);
}
@ -187,11 +190,11 @@ class ProvidersManager {
* @param {object} [controller] a UrlbarController instance
*/
async startQuery(queryContext, controller = null) {
logger.info(`Query start ${queryContext.searchString}`);
lazy.logger.info(`Query start ${queryContext.searchString}`);
// Define the muxer to use.
let muxerName = queryContext.muxer || DEFAULT_MUXER;
logger.info(`Using muxer ${muxerName}`);
lazy.logger.info(`Using muxer ${muxerName}`);
let muxer = this.muxers.get(muxerName);
if (!muxer) {
throw new Error(`Muxer with name ${muxerName} not found`);
@ -204,7 +207,7 @@ class ProvidersManager {
: this.providers;
// Apply tokenization.
UrlbarTokenizer.tokenize(queryContext);
lazy.UrlbarTokenizer.tokenize(queryContext);
// If there's a single source, we are in restriction mode.
if (queryContext.sources && queryContext.sources.length == 1) {
@ -221,11 +224,11 @@ class ProvidersManager {
queryContext.restrictToken = restrictToken;
// If the restriction token has an equivalent source, then set it as
// restrictSource.
if (UrlbarTokenizer.SEARCH_MODE_RESTRICT.has(restrictToken.value)) {
if (lazy.UrlbarTokenizer.SEARCH_MODE_RESTRICT.has(restrictToken.value)) {
queryContext.restrictSource = queryContext.sources[0];
}
}
logger.debug(`Context sources ${queryContext.sources}`);
lazy.logger.debug(`Context sources ${queryContext.sources}`);
let query = new Query(queryContext, controller, muxer, providers);
this.queries.set(queryContext, query);
@ -233,7 +236,7 @@ class ProvidersManager {
// The muxer and many providers depend on the search service and our search
// utils. Make sure they're initialized now (via UrlbarSearchUtils) so that
// all query-related urlbar modules don't need to do it.
await UrlbarSearchUtils.init();
await lazy.UrlbarSearchUtils.init();
if (query.canceled) {
return;
}
@ -242,7 +245,7 @@ class ProvidersManager {
let updateBehaviorPromises = [];
for (let provider of this.providers) {
if (
provider.type == UrlbarUtils.PROVIDER_TYPE.EXTENSION &&
provider.type == lazy.UrlbarUtils.PROVIDER_TYPE.EXTENSION &&
provider.name != "Omnibox"
) {
updateBehaviorPromises.push(
@ -265,7 +268,7 @@ class ProvidersManager {
* @param {object} queryContext
*/
cancelQuery(queryContext) {
logger.info(`Query cancel "${queryContext.searchString}"`);
lazy.logger.info(`Query cancel "${queryContext.searchString}"`);
let query = this.queries.get(queryContext);
if (!query) {
throw new Error("Couldn't find a matching query for the given context");
@ -273,7 +276,7 @@ class ProvidersManager {
query.cancel();
if (!this.interruptLevel) {
try {
let db = PlacesUtils.promiseLargeCacheDBConnection();
let db = lazy.PlacesUtils.promiseLargeCacheDBConnection();
db.interrupt();
} catch (ex) {}
}
@ -407,7 +410,7 @@ class Query {
}
}
})
.catch(ex => logger.error(ex))
.catch(ex => lazy.logger.error(ex))
);
}
@ -436,7 +439,7 @@ class Query {
let queryPromises = [];
for (let provider of activeProviders) {
if (provider.type == UrlbarUtils.PROVIDER_TYPE.HEURISTIC) {
if (provider.type == lazy.UrlbarUtils.PROVIDER_TYPE.HEURISTIC) {
this.context.pendingHeuristicProviders.add(provider.name);
queryPromises.push(startQuery(provider));
continue;
@ -445,9 +448,9 @@ class Query {
// Tracks the delay timer. We will fire (in this specific case, cancel
// would do the same, since the callback is empty) the timer when the
// search is canceled, unblocking start().
this._sleepTimer = new SkippableTimer({
this._sleepTimer = new lazy.SkippableTimer({
name: "Query provider timer",
time: UrlbarPrefs.get("delay"),
time: lazy.UrlbarPrefs.get("delay"),
logger: provider.logger,
});
}
@ -458,7 +461,7 @@ class Query {
);
}
logger.info(`Queried ${queryPromises.length} providers`);
lazy.logger.info(`Queried ${queryPromises.length} providers`);
await Promise.all(queryPromises);
// All the providers are done returning results, so we can stop chunking.
@ -494,13 +497,13 @@ class Query {
provider.tryMethod("cancelQuery", this.context);
}
if (this._heuristicProviderTimer) {
this._heuristicProviderTimer.cancel().catch(ex => logger.error(ex));
this._heuristicProviderTimer.cancel().catch(ex => lazy.logger.error(ex));
}
if (this._chunkTimer) {
this._chunkTimer.cancel().catch(ex => logger.error(ex));
this._chunkTimer.cancel().catch(ex => lazy.logger.error(ex));
}
if (this._sleepTimer) {
this._sleepTimer.fire().catch(ex => logger.error(ex));
this._sleepTimer.fire().catch(ex => lazy.logger.error(ex));
}
}
@ -510,7 +513,7 @@ class Query {
* @param {object} result
*/
add(provider, result) {
if (!(provider instanceof UrlbarProvider)) {
if (!(provider instanceof lazy.UrlbarProvider)) {
throw new Error("Invalid provider passed to the add callback");
}
@ -545,9 +548,9 @@ class Query {
!this.acceptableSources.includes(result.source) &&
!result.heuristic &&
// Treat form history as searches for the purpose of acceptableSources.
(result.type != UrlbarUtils.RESULT_TYPE.SEARCH ||
result.source != UrlbarUtils.RESULT_SOURCE.HISTORY ||
!this.acceptableSources.includes(UrlbarUtils.RESULT_SOURCE.SEARCH))
(result.type != lazy.UrlbarUtils.RESULT_TYPE.SEARCH ||
result.source != lazy.UrlbarUtils.RESULT_SOURCE.HISTORY ||
!this.acceptableSources.includes(lazy.UrlbarUtils.RESULT_SOURCE.SEARCH))
) {
return;
}
@ -555,11 +558,11 @@ class Query {
// Filter out javascript results for safety. The provider is supposed to do
// it, but we don't want to risk leaking these out.
if (
result.type != UrlbarUtils.RESULT_TYPE.KEYWORD &&
result.type != lazy.UrlbarUtils.RESULT_TYPE.KEYWORD &&
result.payload.url &&
result.payload.url.startsWith("javascript:") &&
!this.context.searchString.startsWith("javascript:") &&
UrlbarPrefs.get("filter.javascript")
lazy.UrlbarPrefs.get("filter.javascript")
) {
return;
}
@ -579,9 +582,9 @@ class Query {
// If the timer fires first, we stop waiting on the remaining heuristic
// providers.
// Both timers are used to reduce UI flicker.
if (provider.type == UrlbarUtils.PROVIDER_TYPE.HEURISTIC) {
if (provider.type == lazy.UrlbarUtils.PROVIDER_TYPE.HEURISTIC) {
if (!this._heuristicProviderTimer) {
this._heuristicProviderTimer = new SkippableTimer({
this._heuristicProviderTimer = new lazy.SkippableTimer({
name: "Heuristic provider timer",
callback: () => this._notifyResults(),
time: CHUNK_RESULTS_DELAY_MS,
@ -589,7 +592,7 @@ class Query {
});
}
} else if (!this._chunkTimer) {
this._chunkTimer = new SkippableTimer({
this._chunkTimer = new lazy.SkippableTimer({
name: "Query chunk timer",
callback: () => this._notifyResults(),
time: CHUNK_RESULTS_DELAY_MS,
@ -602,7 +605,7 @@ class Query {
this._heuristicProviderTimer &&
!this.context.pendingHeuristicProviders.size
) {
this._heuristicProviderTimer.fire().catch(ex => logger.error(ex));
this._heuristicProviderTimer.fire().catch(ex => lazy.logger.error(ex));
}
}
@ -610,12 +613,12 @@ class Query {
this.muxer.sort(this.context);
if (this._heuristicProviderTimer) {
this._heuristicProviderTimer.cancel().catch(ex => logger.error(ex));
this._heuristicProviderTimer.cancel().catch(ex => lazy.logger.error(ex));
this._heuristicProviderTimer = null;
}
if (this._chunkTimer) {
this._chunkTimer.cancel().catch(ex => logger.error(ex));
this._chunkTimer.cancel().catch(ex => lazy.logger.error(ex));
this._chunkTimer = null;
}
@ -631,7 +634,7 @@ class Query {
return;
}
this.context.firstResultChanged = !ObjectUtils.deepEqual(
this.context.firstResultChanged = !lazy.ObjectUtils.deepEqual(
this.context.firstResult,
this.context.results[0]
);
@ -657,52 +660,52 @@ function updateSourcesIfEmpty(context) {
// There can be only one restrict token per query.
let restrictToken = context.tokens.find(t =>
[
UrlbarTokenizer.TYPE.RESTRICT_HISTORY,
UrlbarTokenizer.TYPE.RESTRICT_BOOKMARK,
UrlbarTokenizer.TYPE.RESTRICT_TAG,
UrlbarTokenizer.TYPE.RESTRICT_OPENPAGE,
UrlbarTokenizer.TYPE.RESTRICT_SEARCH,
UrlbarTokenizer.TYPE.RESTRICT_TITLE,
UrlbarTokenizer.TYPE.RESTRICT_URL,
UrlbarTokenizer.TYPE.RESTRICT_ACTION,
lazy.UrlbarTokenizer.TYPE.RESTRICT_HISTORY,
lazy.UrlbarTokenizer.TYPE.RESTRICT_BOOKMARK,
lazy.UrlbarTokenizer.TYPE.RESTRICT_TAG,
lazy.UrlbarTokenizer.TYPE.RESTRICT_OPENPAGE,
lazy.UrlbarTokenizer.TYPE.RESTRICT_SEARCH,
lazy.UrlbarTokenizer.TYPE.RESTRICT_TITLE,
lazy.UrlbarTokenizer.TYPE.RESTRICT_URL,
lazy.UrlbarTokenizer.TYPE.RESTRICT_ACTION,
].includes(t.type)
);
// RESTRICT_TITLE and RESTRICT_URL do not affect query sources.
let restrictTokenType =
restrictToken &&
restrictToken.type != UrlbarTokenizer.TYPE.RESTRICT_TITLE &&
restrictToken.type != UrlbarTokenizer.TYPE.RESTRICT_URL
restrictToken.type != lazy.UrlbarTokenizer.TYPE.RESTRICT_TITLE &&
restrictToken.type != lazy.UrlbarTokenizer.TYPE.RESTRICT_URL
? restrictToken.type
: undefined;
for (let source of Object.values(UrlbarUtils.RESULT_SOURCE)) {
for (let source of Object.values(lazy.UrlbarUtils.RESULT_SOURCE)) {
// Skip sources that the context doesn't care about.
if (context.sources && !context.sources.includes(source)) {
continue;
}
// Check prefs and restriction tokens.
switch (source) {
case UrlbarUtils.RESULT_SOURCE.BOOKMARKS:
case lazy.UrlbarUtils.RESULT_SOURCE.BOOKMARKS:
if (
restrictTokenType === UrlbarTokenizer.TYPE.RESTRICT_BOOKMARK ||
restrictTokenType === UrlbarTokenizer.TYPE.RESTRICT_TAG ||
(!restrictTokenType && UrlbarPrefs.get("suggest.bookmark"))
restrictTokenType === lazy.UrlbarTokenizer.TYPE.RESTRICT_BOOKMARK ||
restrictTokenType === lazy.UrlbarTokenizer.TYPE.RESTRICT_TAG ||
(!restrictTokenType && lazy.UrlbarPrefs.get("suggest.bookmark"))
) {
acceptedSources.push(source);
}
break;
case UrlbarUtils.RESULT_SOURCE.HISTORY:
case lazy.UrlbarUtils.RESULT_SOURCE.HISTORY:
if (
restrictTokenType === UrlbarTokenizer.TYPE.RESTRICT_HISTORY ||
(!restrictTokenType && UrlbarPrefs.get("suggest.history"))
restrictTokenType === lazy.UrlbarTokenizer.TYPE.RESTRICT_HISTORY ||
(!restrictTokenType && lazy.UrlbarPrefs.get("suggest.history"))
) {
acceptedSources.push(source);
}
break;
case UrlbarUtils.RESULT_SOURCE.SEARCH:
case lazy.UrlbarUtils.RESULT_SOURCE.SEARCH:
if (
restrictTokenType === UrlbarTokenizer.TYPE.RESTRICT_SEARCH ||
restrictTokenType === lazy.UrlbarTokenizer.TYPE.RESTRICT_SEARCH ||
!restrictTokenType
) {
// We didn't check browser.urlbar.suggest.searches here, because it
@ -713,20 +716,20 @@ function updateSourcesIfEmpty(context) {
acceptedSources.push(source);
}
break;
case UrlbarUtils.RESULT_SOURCE.TABS:
case lazy.UrlbarUtils.RESULT_SOURCE.TABS:
if (
restrictTokenType === UrlbarTokenizer.TYPE.RESTRICT_OPENPAGE ||
(!restrictTokenType && UrlbarPrefs.get("suggest.openpage"))
restrictTokenType === lazy.UrlbarTokenizer.TYPE.RESTRICT_OPENPAGE ||
(!restrictTokenType && lazy.UrlbarPrefs.get("suggest.openpage"))
) {
acceptedSources.push(source);
}
break;
case UrlbarUtils.RESULT_SOURCE.OTHER_NETWORK:
case lazy.UrlbarUtils.RESULT_SOURCE.OTHER_NETWORK:
if (!context.isPrivate && !restrictTokenType) {
acceptedSources.push(source);
}
break;
case UrlbarUtils.RESULT_SOURCE.OTHER_LOCAL:
case lazy.UrlbarUtils.RESULT_SOURCE.OTHER_LOCAL:
default:
if (!restrictTokenType) {
acceptedSources.push(source);

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

@ -15,7 +15,9 @@ const { EventEmitter } = ChromeUtils.import(
"resource://gre/modules/EventEmitter.jsm"
);
XPCOMUtils.defineLazyModuleGetters(this, {
const lazy = {};
XPCOMUtils.defineLazyModuleGetters(lazy, {
BrowserWindowTracker: "resource:///modules/BrowserWindowTracker.jsm",
NimbusFeatures: "resource://nimbus/ExperimentAPI.jsm",
QUICK_SUGGEST_SOURCE: "resource:///modules/UrlbarProviderQuickSuggest.jsm",
@ -28,7 +30,7 @@ XPCOMUtils.defineLazyModuleGetters(this, {
const log = console.createInstance({
prefix: "QuickSuggest",
maxLogLevel: UrlbarPrefs.get("quicksuggest.log") ? "All" : "Warn",
maxLogLevel: lazy.UrlbarPrefs.get("quicksuggest.log") ? "All" : "Warn",
});
const RS_COLLECTION = "quicksuggest";
@ -74,8 +76,8 @@ const ADD_RESULTS_CHUNK_SIZE = 1000;
*/
class QuickSuggest extends EventEmitter {
init() {
UrlbarPrefs.addObserver(this);
NimbusFeatures.urlbar.onUpdate(() => this._queueSettingsSetup());
lazy.UrlbarPrefs.addObserver(this);
lazy.NimbusFeatures.urlbar.onUpdate(() => this._queueSettingsSetup());
this._settingsTaskQueue.queue(() => {
return new Promise(resolve => {
@ -174,7 +176,7 @@ class QuickSuggest extends EventEmitter {
typeof result.score == "number"
? result.score
: DEFAULT_SUGGESTION_SCORE,
source: QUICK_SUGGEST_SOURCE.REMOTE_SETTINGS,
source: lazy.QUICK_SUGGEST_SOURCE.REMOTE_SETTINGS,
icon: icons.shift(),
position: result.position,
_test_is_best_match: result._test_is_best_match,
@ -193,7 +195,7 @@ class QuickSuggest extends EventEmitter {
if (!this._recordedExposureEvent) {
this._recordedExposureEvent = true;
Services.tm.idleDispatchToMainThread(() =>
NimbusFeatures.urlbar.recordExposureEvent({ once: true })
lazy.NimbusFeatures.urlbar.recordExposureEvent({ once: true })
);
}
}
@ -268,54 +270,54 @@ class QuickSuggest extends EventEmitter {
// The call to this method races scenario initialization on startup, and the
// Nimbus variables we rely on below depend on the scenario, so wait for it
// to be initialized.
await UrlbarPrefs.firefoxSuggestScenarioStartupPromise;
await lazy.UrlbarPrefs.firefoxSuggestScenarioStartupPromise;
// If the feature is disabled, the user has already seen the dialog, or the
// user has already opted in, don't show the onboarding.
if (
!UrlbarPrefs.get(FEATURE_AVAILABLE) ||
UrlbarPrefs.get(SEEN_DIALOG_PREF) ||
UrlbarPrefs.get("quicksuggest.dataCollection.enabled")
!lazy.UrlbarPrefs.get(FEATURE_AVAILABLE) ||
lazy.UrlbarPrefs.get(SEEN_DIALOG_PREF) ||
lazy.UrlbarPrefs.get("quicksuggest.dataCollection.enabled")
) {
return false;
}
// Wait a number of restarts before showing the dialog.
let restartsSeen = UrlbarPrefs.get(RESTARTS_PREF);
let restartsSeen = lazy.UrlbarPrefs.get(RESTARTS_PREF);
if (
restartsSeen <
UrlbarPrefs.get("quickSuggestShowOnboardingDialogAfterNRestarts")
lazy.UrlbarPrefs.get("quickSuggestShowOnboardingDialogAfterNRestarts")
) {
UrlbarPrefs.set(RESTARTS_PREF, restartsSeen + 1);
lazy.UrlbarPrefs.set(RESTARTS_PREF, restartsSeen + 1);
return false;
}
let win = BrowserWindowTracker.getTopWindow();
let win = lazy.BrowserWindowTracker.getTopWindow();
// Don't show the dialog on top of about:welcome for new users.
if (win.gBrowser?.currentURI?.spec == "about:welcome") {
return false;
}
if (UrlbarPrefs.get("experimentType") === "modal") {
if (lazy.UrlbarPrefs.get("experimentType") === "modal") {
this.ensureExposureEventRecorded();
}
if (!UrlbarPrefs.get("quickSuggestShouldShowOnboardingDialog")) {
if (!lazy.UrlbarPrefs.get("quickSuggestShouldShowOnboardingDialog")) {
return false;
}
let variationType;
try {
// An error happens if the pref is not in user prefs.
variationType = UrlbarPrefs.get(DIALOG_VARIATION_PREF).toLowerCase();
variationType = lazy.UrlbarPrefs.get(DIALOG_VARIATION_PREF).toLowerCase();
} catch (e) {}
let params = { choice: undefined, variationType, visitedMain: false };
await win.gDialogBox.open(ONBOARDING_URI, params);
UrlbarPrefs.set(SEEN_DIALOG_PREF, true);
UrlbarPrefs.set(
lazy.UrlbarPrefs.set(SEEN_DIALOG_PREF, true);
lazy.UrlbarPrefs.set(
DIALOG_VERSION_PREF,
JSON.stringify({ version: 1, variation: variationType })
);
@ -324,12 +326,12 @@ class QuickSuggest extends EventEmitter {
// so it will retain its user-branch value regardless of what the particular
// default was at the time.
let optedIn = params.choice == ONBOARDING_CHOICE.ACCEPT_2;
UrlbarPrefs.set("quicksuggest.dataCollection.enabled", optedIn);
lazy.UrlbarPrefs.set("quicksuggest.dataCollection.enabled", optedIn);
switch (params.choice) {
case ONBOARDING_CHOICE.LEARN_MORE_1:
case ONBOARDING_CHOICE.LEARN_MORE_2:
win.openTrustedLinkIn(UrlbarProviderQuickSuggest.helpUrl, "tab", {
win.openTrustedLinkIn(lazy.UrlbarProviderQuickSuggest.helpUrl, "tab", {
fromChrome: true,
});
break;
@ -346,7 +348,7 @@ class QuickSuggest extends EventEmitter {
break;
}
UrlbarPrefs.set("quicksuggest.onboardingDialogChoice", params.choice);
lazy.UrlbarPrefs.set("quicksuggest.onboardingDialogChoice", params.choice);
Services.telemetry.recordEvent(
"contextservices.quicksuggest",
@ -383,7 +385,7 @@ class QuickSuggest extends EventEmitter {
// overlap, and happen only one at a time. It also lets clients, especially
// tests, use this class without having to worry about whether a settings sync
// or initialization is ongoing; see `readyPromise`.
_settingsTaskQueue = new TaskQueue();
_settingsTaskQueue = new lazy.TaskQueue();
// Configuration data synced from remote settings. See the `config` getter.
_config = {};
@ -407,12 +409,12 @@ class QuickSuggest extends EventEmitter {
_queueSettingsSetup() {
this._settingsTaskQueue.queue(() => {
let enabled =
UrlbarPrefs.get(FEATURE_AVAILABLE) &&
(UrlbarPrefs.get("suggest.quicksuggest.nonsponsored") ||
UrlbarPrefs.get("suggest.quicksuggest.sponsored"));
lazy.UrlbarPrefs.get(FEATURE_AVAILABLE) &&
(lazy.UrlbarPrefs.get("suggest.quicksuggest.nonsponsored") ||
lazy.UrlbarPrefs.get("suggest.quicksuggest.sponsored"));
if (enabled && !this._rs) {
this._onSettingsSync = (...args) => this._queueSettingsSync(...args);
this._rs = RemoteSettings(RS_COLLECTION);
this._rs = lazy.RemoteSettings(RS_COLLECTION);
this._rs.on("sync", this._onSettingsSync);
} else if (!enabled && this._rs) {
this._rs.off("sync", this._onSettingsSync);
@ -446,7 +448,7 @@ class QuickSuggest extends EventEmitter {
);
}
let dataType = UrlbarPrefs.get("quickSuggestRemoteSettingsDataType");
let dataType = lazy.UrlbarPrefs.get("quickSuggestRemoteSettingsDataType");
log.debug("Loading data with type:", dataType);
let [configArray, data] = await Promise.all([

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

@ -17,7 +17,8 @@ var EXPORTED_SYMBOLS = ["UrlbarResult"];
const { XPCOMUtils } = ChromeUtils.import(
"resource://gre/modules/XPCOMUtils.jsm"
);
XPCOMUtils.defineLazyModuleGetters(this, {
const lazy = {};
XPCOMUtils.defineLazyModuleGetters(lazy, {
BrowserUIUtils: "resource:///modules/BrowserUIUtils.jsm",
JsonSchemaValidator:
"resource://gre/modules/components-utils/JsonSchemaValidator.jsm",
@ -45,14 +46,14 @@ class UrlbarResult {
constructor(resultType, resultSource, payload, payloadHighlights = {}) {
// Type describes the payload and visualization that should be used for
// this result.
if (!Object.values(UrlbarUtils.RESULT_TYPE).includes(resultType)) {
if (!Object.values(lazy.UrlbarUtils.RESULT_TYPE).includes(resultType)) {
throw new Error("Invalid result type");
}
this.type = resultType;
// Source describes which data has been used to derive this result. In case
// multiple sources are involved, use the more privacy restricted.
if (!Object.values(UrlbarUtils.RESULT_SOURCE).includes(resultSource)) {
if (!Object.values(lazy.UrlbarUtils.RESULT_SOURCE).includes(resultSource)) {
throw new Error("Invalid result source");
}
this.source = resultSource;
@ -108,11 +109,11 @@ class UrlbarResult {
*/
get _titleAndHighlights() {
switch (this.type) {
case UrlbarUtils.RESULT_TYPE.KEYWORD:
case UrlbarUtils.RESULT_TYPE.TAB_SWITCH:
case UrlbarUtils.RESULT_TYPE.URL:
case UrlbarUtils.RESULT_TYPE.OMNIBOX:
case UrlbarUtils.RESULT_TYPE.REMOTE_TAB:
case lazy.UrlbarUtils.RESULT_TYPE.KEYWORD:
case lazy.UrlbarUtils.RESULT_TYPE.TAB_SWITCH:
case lazy.UrlbarUtils.RESULT_TYPE.URL:
case lazy.UrlbarUtils.RESULT_TYPE.OMNIBOX:
case lazy.UrlbarUtils.RESULT_TYPE.REMOTE_TAB:
if (this.payload.qsSuggestion) {
return [
// We will initially only be targetting en-US users with this experiment
@ -124,7 +125,7 @@ class UrlbarResult {
return this.payload.title
? [this.payload.title, this.payloadHighlights.title]
: [this.payload.url || "", this.payloadHighlights.url || []];
case UrlbarUtils.RESULT_TYPE.SEARCH:
case lazy.UrlbarUtils.RESULT_TYPE.SEARCH:
if (this.payload.providesSearchMode) {
return ["", []];
}
@ -165,14 +166,14 @@ class UrlbarResult {
* @returns {object} `payload` if it's valid.
*/
validatePayload(payload) {
let schema = UrlbarUtils.getPayloadSchema(this.type);
let schema = lazy.UrlbarUtils.getPayloadSchema(this.type);
if (!schema) {
throw new Error(`Unrecognized result type: ${this.type}`);
}
let result = JsonSchemaValidator.validate(payload, schema, {
let result = lazy.JsonSchemaValidator.validate(payload, schema, {
allowExplicitUndefinedProperties: true,
allowNullAsUndefinedProperties: true,
allowExtraProperties: this.type == UrlbarUtils.RESULT_TYPE.DYNAMIC,
allowExtraProperties: this.type == lazy.UrlbarUtils.RESULT_TYPE.DYNAMIC,
});
if (!result.valid) {
throw result.error;
@ -227,7 +228,7 @@ class UrlbarResult {
// have a domain.
payloadInfo.title = payloadInfo.title || [
"",
UrlbarUtils.HIGHLIGHT.TYPED,
lazy.UrlbarUtils.HIGHLIGHT.TYPED,
];
try {
payloadInfo.title[0] = new URL(payloadInfo.url[0]).host;
@ -238,8 +239,8 @@ class UrlbarResult {
// For display purposes we need to unescape the url.
payloadInfo.displayUrl = [...payloadInfo.url];
let url = payloadInfo.displayUrl[0];
if (url && UrlbarPrefs.get("trimURLs")) {
url = BrowserUIUtils.removeSingleTrailingSlashFromURL(url);
if (url && lazy.UrlbarPrefs.get("trimURLs")) {
url = lazy.BrowserUIUtils.removeSingleTrailingSlashFromURL(url);
if (url.startsWith("https://")) {
url = url.substring(8);
if (url.startsWith("www.")) {
@ -247,7 +248,7 @@ class UrlbarResult {
}
}
}
payloadInfo.displayUrl[0] = UrlbarUtils.unEscapeURIForUI(url);
payloadInfo.displayUrl[0] = lazy.UrlbarUtils.unEscapeURIForUI(url);
}
// For performance reasons limit excessive string lengths, to reduce the
@ -256,7 +257,10 @@ class UrlbarResult {
for (let prop of ["displayUrl", "title", "suggestion"]) {
let val = payloadInfo[prop]?.[0];
if (typeof val == "string") {
payloadInfo[prop][0] = val.substring(0, UrlbarUtils.MAX_TEXT_LENGTH);
payloadInfo[prop][0] = val.substring(
0,
lazy.UrlbarUtils.MAX_TEXT_LENGTH
);
}
}
@ -269,9 +273,9 @@ class UrlbarResult {
entries.reduce((highlights, [name, [val, highlightType]]) => {
if (highlightType) {
highlights[name] = !Array.isArray(val)
? UrlbarUtils.getTokenMatches(tokens, val || "", highlightType)
? lazy.UrlbarUtils.getTokenMatches(tokens, val || "", highlightType)
: val.map(subval =>
UrlbarUtils.getTokenMatches(tokens, subval, highlightType)
lazy.UrlbarUtils.getTokenMatches(tokens, subval, highlightType)
);
}
return highlights;

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

@ -15,7 +15,9 @@ const { SearchOneOffs } = ChromeUtils.import(
"resource:///modules/SearchOneOffs.jsm"
);
XPCOMUtils.defineLazyModuleGetters(this, {
const lazy = {};
XPCOMUtils.defineLazyModuleGetters(lazy, {
UrlbarPrefs: "resource:///modules/UrlbarPrefs.jsm",
UrlbarUtils: "resource:///modules/UrlbarUtils.jsm",
});
@ -34,7 +36,7 @@ class UrlbarSearchOneOffs extends SearchOneOffs {
super(view.panel.querySelector(".search-one-offs"));
this.view = view;
this.input = view.input;
UrlbarPrefs.addObserver(this);
lazy.UrlbarPrefs.addObserver(this);
// Override the SearchOneOffs.jsm value for the Address Bar.
this.disableOneOffsHorizontalKeyNavigation = true;
this._webEngines = [];
@ -199,7 +201,7 @@ class UrlbarSearchOneOffs extends SearchOneOffs {
let startQueryParams = {
allowAutofill:
!searchMode.engineName &&
searchMode.source != UrlbarUtils.RESULT_SOURCE.SEARCH,
searchMode.source != lazy.UrlbarUtils.RESULT_SOURCE.SEARCH,
event,
};
@ -298,7 +300,11 @@ class UrlbarSearchOneOffs extends SearchOneOffs {
// We need to call super.willHide() even when we return false below because
// it has the necessary side effect of creating this._engineInfo.
let superWillHide = await super.willHide();
if (UrlbarUtils.LOCAL_SEARCH_MODES.some(m => UrlbarPrefs.get(m.pref))) {
if (
lazy.UrlbarUtils.LOCAL_SEARCH_MODES.some(m =>
lazy.UrlbarPrefs.get(m.pref)
)
) {
return false;
}
return superWillHide;
@ -315,7 +321,9 @@ class UrlbarSearchOneOffs extends SearchOneOffs {
// Invalidate the engine cache when the local-one-offs-related prefs change
// so that the one-offs rebuild themselves the next time the view opens.
if (
[...UrlbarUtils.LOCAL_SEARCH_MODES.map(m => m.pref)].includes(changedPref)
[...lazy.UrlbarUtils.LOCAL_SEARCH_MODES.map(m => m.pref)].includes(
changedPref
)
) {
this.invalidateCache();
}
@ -341,11 +349,12 @@ class UrlbarSearchOneOffs extends SearchOneOffs {
_rebuildEngineList(engines, addEngines) {
super._rebuildEngineList(engines, addEngines);
for (let { source, pref, restrict } of UrlbarUtils.LOCAL_SEARCH_MODES) {
if (!UrlbarPrefs.get(pref)) {
for (let { source, pref, restrict } of lazy.UrlbarUtils
.LOCAL_SEARCH_MODES) {
if (!lazy.UrlbarPrefs.get(pref)) {
continue;
}
let name = UrlbarUtils.getResultSourceName(source);
let name = lazy.UrlbarUtils.getResultSourceName(source);
let button = this.document.createXULElement("button");
button.id = `urlbar-engine-one-off-item-${name}`;
button.setAttribute("class", "searchbar-engine-one-off-item");

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

@ -18,7 +18,9 @@ const { XPCOMUtils } = ChromeUtils.import(
);
const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm");
XPCOMUtils.defineLazyModuleGetters(this, {
const lazy = {};
XPCOMUtils.defineLazyModuleGetters(lazy, {
UrlbarTokenizer: "resource:///modules/UrlbarTokenizer.jsm",
UrlbarUtils: "resource:///modules/UrlbarUtils.jsm",
});
@ -161,10 +163,10 @@ class SearchUtils {
await Promise.all([this.init(), this._refreshEnginesByAliasPromise]);
let engine = this._enginesByAlias.get(alias.toLocaleLowerCase());
if (engine && searchString) {
let query = UrlbarUtils.substringAfter(searchString, alias);
let query = lazy.UrlbarUtils.substringAfter(searchString, alias);
// Match an alias only when it has a space after it. If there's no trailing
// space, then continue to treat it as part of the search string.
if (!UrlbarTokenizer.REGEXP_SPACES_START.test(query)) {
if (!lazy.UrlbarTokenizer.REGEXP_SPACES_START.test(query)) {
return null;
}
}
@ -254,7 +256,8 @@ class SearchUtils {
scalarKey = searchMode.engineName;
}
} else if (searchMode.source) {
scalarKey = UrlbarUtils.getResultSourceName(searchMode.source) || "other";
scalarKey =
lazy.UrlbarUtils.getResultSourceName(searchMode.source) || "other";
}
return scalarKey;

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

@ -16,12 +16,13 @@ const { XPCOMUtils } = ChromeUtils.import(
"resource://gre/modules/XPCOMUtils.jsm"
);
const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm");
XPCOMUtils.defineLazyModuleGetters(this, {
const lazy = {};
XPCOMUtils.defineLazyModuleGetters(lazy, {
UrlbarUtils: "resource:///modules/UrlbarUtils.jsm",
});
XPCOMUtils.defineLazyGetter(this, "logger", () =>
UrlbarUtils.getLogger({ prefix: "Tokenizer" })
XPCOMUtils.defineLazyGetter(lazy, "logger", () =>
lazy.UrlbarUtils.getLogger({ prefix: "Tokenizer" })
);
var UrlbarTokenizer = {
@ -127,7 +128,7 @@ var UrlbarTokenizer = {
}
let path = slashIndex != -1 ? token.slice(slashIndex) : "";
logger.debug("path", path);
lazy.logger.debug("path", path);
if (requirePath && !path) {
return false;
}
@ -196,8 +197,8 @@ var UrlbarTokenizer = {
let userinfo = atIndex != -1 ? token.slice(0, atIndex) : "";
let hostPort = atIndex != -1 ? token.slice(atIndex + 1) : token;
let hasPort = this.REGEXP_HAS_PORT.test(hostPort);
logger.debug("userinfo", userinfo);
logger.debug("hostPort", hostPort);
lazy.logger.debug("userinfo", userinfo);
lazy.logger.debug("hostPort", hostPort);
if (noPort && hasPort) {
return false;
}
@ -241,7 +242,7 @@ var UrlbarTokenizer = {
* tokens property.
*/
tokenize(queryContext) {
logger.info("Tokenizing", queryContext);
lazy.logger.info("Tokenizing", queryContext);
if (!queryContext.trimmedSearchString) {
queryContext.tokens = [];
return queryContext;
@ -407,6 +408,6 @@ function filterTokens(tokens) {
}
}
logger.info("Filtered Tokens", tokens);
lazy.logger.info("Filtered Tokens", tokens);
return filtered;
}

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

@ -23,7 +23,8 @@ const { XPCOMUtils } = ChromeUtils.import(
"resource://gre/modules/XPCOMUtils.jsm"
);
const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm");
XPCOMUtils.defineLazyModuleGetters(this, {
const lazy = {};
XPCOMUtils.defineLazyModuleGetters(lazy, {
BrowserWindowTracker: "resource:///modules/BrowserWindowTracker.jsm",
FormHistory: "resource://gre/modules/FormHistory.jsm",
KeywordUtils: "resource://gre/modules/KeywordUtils.jsm",
@ -219,25 +220,25 @@ var UrlbarUtils = {
return [
{
source: UrlbarUtils.RESULT_SOURCE.BOOKMARKS,
restrict: UrlbarTokenizer.RESTRICT.BOOKMARK,
restrict: lazy.UrlbarTokenizer.RESTRICT.BOOKMARK,
icon: "chrome://browser/skin/bookmark.svg",
pref: "shortcuts.bookmarks",
},
{
source: UrlbarUtils.RESULT_SOURCE.TABS,
restrict: UrlbarTokenizer.RESTRICT.OPENPAGE,
restrict: lazy.UrlbarTokenizer.RESTRICT.OPENPAGE,
icon: "chrome://browser/skin/tab.svg",
pref: "shortcuts.tabs",
},
{
source: UrlbarUtils.RESULT_SOURCE.HISTORY,
restrict: UrlbarTokenizer.RESTRICT.HISTORY,
restrict: lazy.UrlbarTokenizer.RESTRICT.HISTORY,
icon: "chrome://browser/skin/history.svg",
pref: "shortcuts.history",
},
{
source: UrlbarUtils.RESULT_SOURCE.ACTIONS,
restrict: UrlbarTokenizer.RESTRICT.ACTION,
restrict: lazy.UrlbarTokenizer.RESTRICT.ACTION,
icon: "chrome://devtools/skin/images/command-console.svg",
pref: "shortcuts.quickactions",
},
@ -263,13 +264,13 @@ var UrlbarUtils = {
*/
addToUrlbarHistory(url, window) {
if (
!PrivateBrowsingUtils.isWindowPrivate(window) &&
!lazy.PrivateBrowsingUtils.isWindowPrivate(window) &&
url &&
!url.includes(" ") &&
// eslint-disable-next-line no-control-regex
!/[\x00-\x1F]/.test(url)
) {
PlacesUIUtils.markPageAsTyped(url);
lazy.PlacesUIUtils.markPageAsTyped(url);
}
},
@ -308,7 +309,7 @@ var UrlbarUtils = {
// from the location bar.
let entry = null;
try {
entry = await PlacesUtils.keywords.fetch(keyword);
entry = await lazy.PlacesUtils.keywords.fetch(keyword);
} catch (ex) {
Cu.reportError(`Unable to fetch Places keyword "${keyword}": ${ex}`);
}
@ -318,7 +319,7 @@ var UrlbarUtils = {
}
try {
[url, postData] = await KeywordUtils.parseUrlAndPostData(
[url, postData] = await lazy.KeywordUtils.parseUrlAndPostData(
entry.url.href,
entry.postData,
param
@ -698,9 +699,10 @@ var UrlbarUtils = {
* setSearchMode documentation for details.
*/
searchModeForToken(token) {
if (token == UrlbarTokenizer.RESTRICT.SEARCH) {
if (token == lazy.UrlbarTokenizer.RESTRICT.SEARCH) {
return {
engineName: UrlbarSearchUtils.getDefaultEngine(this.isPrivate).name,
engineName: lazy.UrlbarSearchUtils.getDefaultEngine(this.isPrivate)
.name,
};
}
@ -722,7 +724,7 @@ var UrlbarUtils = {
* initialized, it will be a no-op.
*/
setupSpeculativeConnection(urlOrEngine, window) {
if (!UrlbarPrefs.get("speculativeConnect.enabled")) {
if (!lazy.UrlbarPrefs.get("speculativeConnect.enabled")) {
return;
}
if (urlOrEngine instanceof Ci.nsISearchEngine) {
@ -860,7 +862,7 @@ var UrlbarUtils = {
},
async addToInputHistory(url, input) {
await PlacesUtils.withConnectionWrapper("addToInputHistory", db => {
await lazy.PlacesUtils.withConnectionWrapper("addToInputHistory", db => {
// use_count will asymptotically approach the max of 10.
return db.executeCached(
`
@ -944,7 +946,7 @@ var UrlbarUtils = {
* then [prefix, remainder]. Otherwise, ["", str].
*/
stripURLPrefix(str) {
let match = UrlbarTokenizer.REGEXP_PREFIX.exec(str);
let match = lazy.UrlbarTokenizer.REGEXP_PREFIX.exec(str);
if (!match) {
return ["", str];
}
@ -973,7 +975,7 @@ var UrlbarUtils = {
*/
async getHeuristicResultFor(
searchString,
window = BrowserWindowTracker.getTopWindow()
window = lazy.BrowserWindowTracker.getTopWindow()
) {
if (!searchString) {
throw new Error("Must pass a non-null search string");
@ -981,7 +983,7 @@ var UrlbarUtils = {
let options = {
allowAutofill: false,
isPrivate: PrivateBrowsingUtils.isWindowPrivate(window),
isPrivate: lazy.PrivateBrowsingUtils.isWindowPrivate(window),
maxResults: 1,
searchString,
userContextId: window.gBrowser.selectedBrowser.getAttribute(
@ -998,7 +1000,7 @@ var UrlbarUtils = {
}
}
let context = new UrlbarQueryContext(options);
await UrlbarProvidersManager.startQuery(context);
await lazy.UrlbarProvidersManager.startQuery(context);
if (!context.heuristicResult) {
throw new Error("There should always be an heuristic result");
}
@ -1014,17 +1016,17 @@ var UrlbarUtils = {
*/
getLogger({ prefix = "" } = {}) {
if (!this._logger) {
this._logger = Log.repository.getLogger("urlbar");
this._logger = lazy.Log.repository.getLogger("urlbar");
this._logger.manageLevelFromPref("browser.urlbar.loglevel");
this._logger.addAppender(
new Log.ConsoleAppender(new Log.BasicFormatter())
new lazy.Log.ConsoleAppender(new lazy.Log.BasicFormatter())
);
}
if (prefix) {
// This is not an early return because it is necessary to invoke getLogger
// at least once before getLoggerWithMessagePrefix; it replaces a
// method of the original logger, rather than using an actual Proxy.
return Log.repository.getLoggerWithMessagePrefix(
return lazy.Log.repository.getLoggerWithMessagePrefix(
"urlbar",
prefix + " :: "
);
@ -1068,12 +1070,13 @@ var UrlbarUtils = {
if (
!value ||
input.isPrivate ||
value.length > SearchSuggestionController.SEARCH_HISTORY_MAX_VALUE_LENGTH
value.length >
lazy.SearchSuggestionController.SEARCH_HISTORY_MAX_VALUE_LENGTH
) {
return Promise.resolve();
}
return new Promise((resolve, reject) => {
FormHistory.update(
lazy.FormHistory.update(
{
op: "bump",
fieldname: input.formHistoryName,
@ -1113,10 +1116,10 @@ var UrlbarUtils = {
// Create `URL` objects to make the logic below easier. The strings must
// include schemes for this to work.
if (!UrlbarTokenizer.REGEXP_PREFIX.test(url)) {
if (!lazy.UrlbarTokenizer.REGEXP_PREFIX.test(url)) {
url = "http://" + url;
}
if (!UrlbarTokenizer.REGEXP_PREFIX.test(candidate)) {
if (!lazy.UrlbarTokenizer.REGEXP_PREFIX.test(candidate)) {
candidate = "http://" + candidate;
}
try {
@ -1236,7 +1239,7 @@ var UrlbarUtils = {
};
XPCOMUtils.defineLazyGetter(UrlbarUtils.ICON, "DEFAULT", () => {
return PlacesUtils.favicons.defaultFavicon.spec;
return lazy.PlacesUtils.favicons.defaultFavicon.spec;
});
XPCOMUtils.defineLazyGetter(UrlbarUtils, "strings", () => {
@ -1726,7 +1729,7 @@ class UrlbarQueryContext {
// mozilla.o, because the fixup check below can't validate them.
if (
this.tokens.length == 1 &&
this.tokens[0].type == UrlbarTokenizer.TYPE.POSSIBLE_ORIGIN
this.tokens[0].type == lazy.UrlbarTokenizer.TYPE.POSSIBLE_ORIGIN
) {
return false;
}

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

@ -11,7 +11,9 @@ const { XPCOMUtils } = ChromeUtils.import(
);
const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm");
XPCOMUtils.defineLazyModuleGetters(this, {
const lazy = {};
XPCOMUtils.defineLazyModuleGetters(lazy, {
PrivateBrowsingUtils: "resource://gre/modules/PrivateBrowsingUtils.jsm",
UrlbarPrefs: "resource:///modules/UrlbarPrefs.jsm",
UrlbarUtils: "resource:///modules/UrlbarUtils.jsm",
@ -148,7 +150,7 @@ class UrlbarValueFormatter {
let flags =
Services.uriFixup.FIXUP_FLAG_FIX_SCHEME_TYPOS |
Services.uriFixup.FIXUP_FLAG_ALLOW_KEYWORD_LOOKUP;
if (PrivateBrowsingUtils.isWindowPrivate(this.window)) {
if (lazy.PrivateBrowsingUtils.isWindowPrivate(this.window)) {
flags |= Services.uriFixup.FIXUP_FLAG_PRIVATE_CONTEXT;
}
let uriInfo;
@ -262,7 +264,7 @@ class UrlbarValueFormatter {
url,
} = urlMetaData;
// We strip http, so we should not show the scheme box for it.
if (!UrlbarPrefs.get("trimURLs") || schemeWSlashes != "http://") {
if (!lazy.UrlbarPrefs.get("trimURLs") || schemeWSlashes != "http://") {
this.scheme.value = schemeWSlashes;
this.inputField.style.setProperty(
"--urlbar-scheme-size",
@ -272,7 +274,7 @@ class UrlbarValueFormatter {
this._ensureFormattedHostVisible(urlMetaData);
if (!UrlbarPrefs.get("formatting.enabled")) {
if (!lazy.UrlbarPrefs.get("formatting.enabled")) {
return false;
}
@ -369,7 +371,7 @@ class UrlbarValueFormatter {
* True if formatting was applied and false if not.
*/
_formatSearchAlias() {
if (!UrlbarPrefs.get("formatting.enabled")) {
if (!lazy.UrlbarPrefs.get("formatting.enabled")) {
return false;
}
@ -459,7 +461,7 @@ class UrlbarValueFormatter {
if (
this._selectedResult &&
this._selectedResult.type == UrlbarUtils.RESULT_TYPE.SEARCH
this._selectedResult.type == lazy.UrlbarUtils.RESULT_TYPE.SEARCH
) {
return this._selectedResult.payload.keyword || null;
}

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

@ -10,7 +10,8 @@ const { XPCOMUtils } = ChromeUtils.import(
"resource://gre/modules/XPCOMUtils.jsm"
);
const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm");
XPCOMUtils.defineLazyModuleGetters(this, {
const lazy = {};
XPCOMUtils.defineLazyModuleGetters(lazy, {
BrowserWindowTracker: "resource:///modules/BrowserWindowTracker.jsm",
L10nCache: "resource:///modules/UrlbarUtils.jsm",
ObjectUtils: "resource://gre/modules/ObjectUtils.jsm",
@ -23,7 +24,7 @@ XPCOMUtils.defineLazyModuleGetters(this, {
});
XPCOMUtils.defineLazyServiceGetter(
this,
lazy,
"styleSheetService",
"@mozilla.org/content/style-sheet-service;1",
"nsIStyleSheetService"
@ -83,7 +84,7 @@ class UrlbarView {
this._queryContextCache = new QueryContextCache(5);
// We cache l10n strings to avoid Fluent's async lookup.
this._l10nCache = new L10nCache(this.document.l10n);
this._l10nCache = new lazy.L10nCache(this.document.l10n);
for (let viewTemplate of UrlbarView.dynamicViewTemplatesByName.values()) {
if (viewTemplate.stylesheet) {
@ -94,7 +95,7 @@ class UrlbarView {
get oneOffSearchButtons() {
if (!this._oneOffSearchButtons) {
this._oneOffSearchButtons = new UrlbarSearchOneOffs(this);
this._oneOffSearchButtons = new lazy.UrlbarSearchOneOffs(this);
this._oneOffSearchButtons.addEventListener(
"SelectedOneOffButtonChanged",
this
@ -355,7 +356,7 @@ class UrlbarView {
selectedElt?.result?.providerName == "TabToSearch" &&
!this._announceTabToSearchOnSelection &&
userPressedTab &&
UrlbarPrefs.get("accessibility.tabToSearch.announceResults");
lazy.UrlbarPrefs.get("accessibility.tabToSearch.announceResults");
if (skipAnnouncement) {
// Once we skip setting aria-activedescendant once, we should not skip
// it again if the user returns to that result.
@ -655,7 +656,7 @@ class UrlbarView {
queryContext.trimmedSearchString) &&
queryContext.trimmedSearchString[0] != "@" &&
(queryContext.trimmedSearchString[0] !=
UrlbarTokenizer.RESTRICT.SEARCH ||
lazy.UrlbarTokenizer.RESTRICT.SEARCH ||
queryContext.trimmedSearchString.length != 1)
);
}
@ -692,7 +693,7 @@ class UrlbarView {
let secondResult = queryContext.results[1];
if (
secondResult?.providerName == "TabToSearch" &&
UrlbarPrefs.get("accessibility.tabToSearch.announceResults") &&
lazy.UrlbarPrefs.get("accessibility.tabToSearch.announceResults") &&
this._previousTabToSearchEngine != secondResult.payload.engine
) {
let engine = secondResult.payload.engine;
@ -847,7 +848,7 @@ class UrlbarView {
static addDynamicViewTemplate(name, viewTemplate) {
this.dynamicViewTemplatesByName.set(name, viewTemplate);
if (viewTemplate.stylesheet) {
for (let window of BrowserWindowTracker.orderedWindows) {
for (let window of lazy.BrowserWindowTracker.orderedWindows) {
addDynamicStylesheet(window, viewTemplate.stylesheet);
}
}
@ -867,7 +868,7 @@ class UrlbarView {
}
this.dynamicViewTemplatesByName.delete(name);
if (viewTemplate.stylesheet) {
for (let window of BrowserWindowTracker.orderedWindows) {
for (let window of lazy.BrowserWindowTracker.orderedWindows) {
removeDynamicStylesheet(window, viewTemplate.stylesheet);
}
}
@ -906,8 +907,8 @@ class UrlbarView {
throw new Error("A heuristic result must be given");
}
return (
!UrlbarPrefs.get("experimental.hideHeuristic") ||
result.type == UrlbarUtils.RESULT_TYPE.TIP
!lazy.UrlbarPrefs.get("experimental.hideHeuristic") ||
result.type == lazy.UrlbarUtils.RESULT_TYPE.TIP
);
}
@ -919,7 +920,7 @@ class UrlbarView {
_resultIsSearchSuggestion(result) {
return Boolean(
result &&
result.type == UrlbarUtils.RESULT_TYPE.SEARCH &&
result.type == lazy.UrlbarUtils.RESULT_TYPE.SEARCH &&
result.payload.suggestion
);
}
@ -994,7 +995,7 @@ class UrlbarView {
) {
let row = this._rows.children[rowIndex];
if (this._isElementVisible(row)) {
visibleSpanCount += UrlbarUtils.getSpanForResult(row.result);
visibleSpanCount += lazy.UrlbarUtils.getSpanForResult(row.result);
}
// Continue updating rows as long as we haven't encountered a new
// suggestedIndex result that couldn't replace a current result.
@ -1026,7 +1027,7 @@ class UrlbarView {
let row = this._rows.children[rowIndex];
row.setAttribute("stale", "true");
if (this._isElementVisible(row)) {
visibleSpanCount += UrlbarUtils.getSpanForResult(row.result);
visibleSpanCount += lazy.UrlbarUtils.getSpanForResult(row.result);
}
}
@ -1061,7 +1062,7 @@ class UrlbarView {
}
}
let newVisibleSpanCount =
visibleSpanCount + UrlbarUtils.getSpanForResult(result);
visibleSpanCount + lazy.UrlbarUtils.getSpanForResult(result);
if (
newVisibleSpanCount <= queryContext.maxResults &&
!seenMisplacedResult
@ -1155,7 +1156,7 @@ class UrlbarView {
// only when necessary.
if (
result.providerName == "UrlbarProviderQuickSuggest" &&
UrlbarPrefs.get("quickSuggestBlockingEnabled")
lazy.UrlbarPrefs.get("quickSuggestBlockingEnabled")
) {
this._addRowButton(item, "block", "firefox-suggest-urlbar-block");
}
@ -1209,7 +1210,7 @@ class UrlbarView {
_createRowContentForDynamicType(item, result) {
let { dynamicType } = result.payload;
let provider = UrlbarProvidersManager.getProvider(result.providerName);
let provider = lazy.UrlbarProvidersManager.getProvider(result.providerName);
let viewTemplate =
provider.getViewTemplate?.(result) ||
UrlbarView.dynamicViewTemplatesByName.get(dynamicType);
@ -1297,7 +1298,7 @@ class UrlbarView {
body.appendChild(bottom);
item._elements.set("bottom", bottom);
if (UrlbarPrefs.get("bestMatchBlockingEnabled")) {
if (lazy.UrlbarPrefs.get("bestMatchBlockingEnabled")) {
this._addRowButton(item, "block", "firefox-suggest-urlbar-block");
}
if (result.payload.helpUrl) {
@ -1335,19 +1336,19 @@ class UrlbarView {
_updateRow(item, result) {
let oldResult = item.result;
let oldResultType = item.result && item.result.type;
let provider = UrlbarProvidersManager.getProvider(result.providerName);
let provider = lazy.UrlbarProvidersManager.getProvider(result.providerName);
item.result = result;
item.removeAttribute("stale");
item.id = getUniqueId("urlbarView-row-");
let needsNewContent =
oldResultType === undefined ||
(oldResultType == UrlbarUtils.RESULT_TYPE.TIP) !=
(result.type == UrlbarUtils.RESULT_TYPE.TIP) ||
(oldResultType == UrlbarUtils.RESULT_TYPE.DYNAMIC) !=
(result.type == UrlbarUtils.RESULT_TYPE.DYNAMIC) ||
(oldResultType == UrlbarUtils.RESULT_TYPE.DYNAMIC &&
result.type == UrlbarUtils.RESULT_TYPE.DYNAMIC &&
(oldResultType == lazy.UrlbarUtils.RESULT_TYPE.TIP) !=
(result.type == lazy.UrlbarUtils.RESULT_TYPE.TIP) ||
(oldResultType == lazy.UrlbarUtils.RESULT_TYPE.DYNAMIC) !=
(result.type == lazy.UrlbarUtils.RESULT_TYPE.DYNAMIC) ||
(oldResultType == lazy.UrlbarUtils.RESULT_TYPE.DYNAMIC &&
result.type == lazy.UrlbarUtils.RESULT_TYPE.DYNAMIC &&
oldResult.payload.dynamicType != result.payload.dynamicType) ||
// Dynamic results that implement getViewTemplate will
// always need updating.
@ -1355,11 +1356,11 @@ class UrlbarView {
oldResult.isBestMatch != result.isBestMatch ||
!!result.payload.helpUrl != item._buttons.has("help") ||
(result.isBestMatch &&
UrlbarPrefs.get("bestMatchBlockingEnabled") !=
lazy.UrlbarPrefs.get("bestMatchBlockingEnabled") !=
item._buttons.has("block")) ||
(!result.isBestMatch &&
result.providerName == "UrlbarProviderQuickSuggest" &&
UrlbarPrefs.get("quickSuggestBlockingEnabled") !=
lazy.UrlbarPrefs.get("quickSuggestBlockingEnabled") !=
item._buttons.has("block"));
if (needsNewContent) {
@ -1372,9 +1373,9 @@ class UrlbarView {
item._content.className = "urlbarView-row-inner";
item.appendChild(item._content);
item.removeAttribute("dynamicType");
if (item.result.type == UrlbarUtils.RESULT_TYPE.TIP) {
if (item.result.type == lazy.UrlbarUtils.RESULT_TYPE.TIP) {
this._createRowContentForTip(item);
} else if (item.result.type == UrlbarUtils.RESULT_TYPE.DYNAMIC) {
} else if (item.result.type == lazy.UrlbarUtils.RESULT_TYPE.DYNAMIC) {
this._createRowContentForDynamicType(item, result);
} else if (item.result.isBestMatch) {
this._createRowContentForBestMatch(item, result);
@ -1385,22 +1386,22 @@ class UrlbarView {
item._content.id = item.id + "-inner";
if (
result.type == UrlbarUtils.RESULT_TYPE.SEARCH &&
result.type == lazy.UrlbarUtils.RESULT_TYPE.SEARCH &&
!result.payload.providesSearchMode &&
!result.payload.inPrivateWindow
) {
item.setAttribute("type", "search");
} else if (result.type == UrlbarUtils.RESULT_TYPE.REMOTE_TAB) {
} else if (result.type == lazy.UrlbarUtils.RESULT_TYPE.REMOTE_TAB) {
item.setAttribute("type", "remotetab");
} else if (result.type == UrlbarUtils.RESULT_TYPE.TAB_SWITCH) {
} else if (result.type == lazy.UrlbarUtils.RESULT_TYPE.TAB_SWITCH) {
item.setAttribute("type", "switchtab");
} else if (result.type == UrlbarUtils.RESULT_TYPE.TIP) {
} else if (result.type == lazy.UrlbarUtils.RESULT_TYPE.TIP) {
item.setAttribute("type", "tip");
this._updateRowForTip(item, result);
return;
} else if (result.source == UrlbarUtils.RESULT_SOURCE.BOOKMARKS) {
} else if (result.source == lazy.UrlbarUtils.RESULT_SOURCE.BOOKMARKS) {
item.setAttribute("type", "bookmark");
} else if (result.type == UrlbarUtils.RESULT_TYPE.DYNAMIC) {
} else if (result.type == lazy.UrlbarUtils.RESULT_TYPE.DYNAMIC) {
item.setAttribute("type", "dynamic");
this._updateRowForDynamicType(item, result);
return;
@ -1416,12 +1417,12 @@ class UrlbarView {
let favicon = item._elements.get("favicon");
if (
result.type == UrlbarUtils.RESULT_TYPE.SEARCH ||
result.type == UrlbarUtils.RESULT_TYPE.KEYWORD
result.type == lazy.UrlbarUtils.RESULT_TYPE.SEARCH ||
result.type == lazy.UrlbarUtils.RESULT_TYPE.KEYWORD
) {
favicon.src = this._iconForResult(result);
} else {
favicon.src = result.payload.icon || UrlbarUtils.ICON.DEFAULT;
favicon.src = result.payload.icon || lazy.UrlbarUtils.ICON.DEFAULT;
}
let title = item._elements.get("title");
@ -1463,7 +1464,7 @@ class UrlbarView {
let isVisitAction = false;
let setURL = false;
switch (result.type) {
case UrlbarUtils.RESULT_TYPE.TAB_SWITCH:
case lazy.UrlbarUtils.RESULT_TYPE.TAB_SWITCH:
actionSetter = () => {
this._setElementL10n(action, {
id: "urlbar-result-action-switch-tab",
@ -1471,14 +1472,14 @@ class UrlbarView {
};
setURL = true;
break;
case UrlbarUtils.RESULT_TYPE.REMOTE_TAB:
case lazy.UrlbarUtils.RESULT_TYPE.REMOTE_TAB:
actionSetter = () => {
this._removeElementL10n(action);
action.textContent = result.payload.device;
};
setURL = true;
break;
case UrlbarUtils.RESULT_TYPE.SEARCH:
case lazy.UrlbarUtils.RESULT_TYPE.SEARCH:
if (result.payload.inPrivateWindow) {
if (result.payload.isPrivateEngine) {
actionSetter = () => {
@ -1512,10 +1513,10 @@ class UrlbarView {
};
}
break;
case UrlbarUtils.RESULT_TYPE.KEYWORD:
case lazy.UrlbarUtils.RESULT_TYPE.KEYWORD:
isVisitAction = result.payload.input.trim() == result.payload.keyword;
break;
case UrlbarUtils.RESULT_TYPE.OMNIBOX:
case lazy.UrlbarUtils.RESULT_TYPE.OMNIBOX:
actionSetter = () => {
this._removeElementL10n(action);
action.textContent = result.payload.content;
@ -1544,7 +1545,7 @@ class UrlbarView {
if (
result.payload.isSponsored &&
result.type != UrlbarUtils.RESULT_TYPE.TAB_SWITCH
result.type != lazy.UrlbarUtils.RESULT_TYPE.TAB_SWITCH
) {
item.toggleAttribute("sponsored", true);
actionSetter = () => {
@ -1618,22 +1619,22 @@ class UrlbarView {
_iconForResult(result, iconUrlOverride = null) {
return (
(result.source == UrlbarUtils.RESULT_SOURCE.HISTORY &&
(result.type == UrlbarUtils.RESULT_TYPE.SEARCH ||
result.type == UrlbarUtils.RESULT_TYPE.KEYWORD) &&
UrlbarUtils.ICON.HISTORY) ||
(result.source == lazy.UrlbarUtils.RESULT_SOURCE.HISTORY &&
(result.type == lazy.UrlbarUtils.RESULT_TYPE.SEARCH ||
result.type == lazy.UrlbarUtils.RESULT_TYPE.KEYWORD) &&
lazy.UrlbarUtils.ICON.HISTORY) ||
iconUrlOverride ||
result.payload.icon ||
((result.type == UrlbarUtils.RESULT_TYPE.SEARCH ||
result.type == UrlbarUtils.RESULT_TYPE.KEYWORD) &&
UrlbarUtils.ICON.SEARCH_GLASS) ||
UrlbarUtils.ICON.DEFAULT
((result.type == lazy.UrlbarUtils.RESULT_TYPE.SEARCH ||
result.type == lazy.UrlbarUtils.RESULT_TYPE.KEYWORD) &&
lazy.UrlbarUtils.ICON.SEARCH_GLASS) ||
lazy.UrlbarUtils.ICON.DEFAULT
);
}
_updateRowForTip(item, result) {
let favicon = item._elements.get("favicon");
favicon.src = result.payload.icon || UrlbarUtils.ICON.TIP;
favicon.src = result.payload.icon || lazy.UrlbarUtils.ICON.TIP;
favicon.id = item.id + "-icon";
let title = item._elements.get("title");
@ -1701,7 +1702,7 @@ class UrlbarView {
}
// Get the view update from the result's provider.
let provider = UrlbarProvidersManager.getProvider(result.providerName);
let provider = lazy.UrlbarProvidersManager.getProvider(result.providerName);
let viewUpdate = await provider.getViewUpdate(result, idsByName);
// Update each node in the view by name.
@ -1822,7 +1823,7 @@ class UrlbarView {
if (visible) {
label = this._rowLabel(item, currentLabel);
if (label) {
if (ObjectUtils.deepEqual(label, currentLabel)) {
if (lazy.ObjectUtils.deepEqual(label, currentLabel)) {
label = null;
} else {
currentLabel = label;
@ -1873,7 +1874,7 @@ class UrlbarView {
_rowLabel(row, currentLabel) {
// Labels aren't shown for top sites, i.e., when the search string is empty.
if (
UrlbarPrefs.get("groupLabels.enabled") &&
lazy.UrlbarPrefs.get("groupLabels.enabled") &&
this._queryContext?.searchString &&
!row.result.heuristic
) {
@ -1881,12 +1882,12 @@ class UrlbarView {
return { id: "urlbar-group-best-match" };
}
switch (row.result.type) {
case UrlbarUtils.RESULT_TYPE.KEYWORD:
case UrlbarUtils.RESULT_TYPE.REMOTE_TAB:
case UrlbarUtils.RESULT_TYPE.TAB_SWITCH:
case UrlbarUtils.RESULT_TYPE.URL:
case lazy.UrlbarUtils.RESULT_TYPE.KEYWORD:
case lazy.UrlbarUtils.RESULT_TYPE.REMOTE_TAB:
case lazy.UrlbarUtils.RESULT_TYPE.TAB_SWITCH:
case lazy.UrlbarUtils.RESULT_TYPE.URL:
return { id: "urlbar-group-firefox-suggest" };
case UrlbarUtils.RESULT_TYPE.SEARCH:
case lazy.UrlbarUtils.RESULT_TYPE.SEARCH:
// Show "{ $engine } suggestions" if it's not the first label.
if (currentLabel && row.result.payload.suggestion) {
let engineName =
@ -1906,8 +1907,8 @@ class UrlbarView {
row.style.display = visible ? "" : "none";
if (
!visible &&
row.result.type != UrlbarUtils.RESULT_TYPE.TIP &&
row.result.type != UrlbarUtils.RESULT_TYPE.DYNAMIC
row.result.type != lazy.UrlbarUtils.RESULT_TYPE.TIP &&
row.result.type != lazy.UrlbarUtils.RESULT_TYPE.DYNAMIC
) {
// Reset the overflow state of elements that can overflow in case their
// content changes while they're hidden. When making the row visible
@ -1994,7 +1995,9 @@ class UrlbarView {
this.input.setResultForCurrentValue(result);
}
let provider = UrlbarProvidersManager.getProvider(result?.providerName);
let provider = lazy.UrlbarProvidersManager.getProvider(
result?.providerName
);
if (provider) {
provider.tryMethod("onSelection", result, element);
}
@ -2283,7 +2286,7 @@ class UrlbarView {
return false;
}
let result = this._queryContext.results[0];
if (result.type != UrlbarUtils.RESULT_TYPE.TIP) {
if (result.type != lazy.UrlbarUtils.RESULT_TYPE.TIP) {
return false;
}
let tipButton = this._rows.firstElementChild.querySelector(
@ -2318,19 +2321,19 @@ class UrlbarView {
{ id: "urlbar-result-action-visit" },
];
if (UrlbarPrefs.get("groupLabels.enabled")) {
if (lazy.UrlbarPrefs.get("groupLabels.enabled")) {
idArgs.push({ id: "urlbar-group-firefox-suggest" });
if (
UrlbarPrefs.get("bestMatchEnabled") &&
UrlbarPrefs.get("suggest.bestmatch")
lazy.UrlbarPrefs.get("bestMatchEnabled") &&
lazy.UrlbarPrefs.get("suggest.bestmatch")
) {
idArgs.push({ id: "urlbar-group-best-match" });
}
}
if (
UrlbarPrefs.get("quickSuggestEnabled") &&
UrlbarPrefs.get("suggest.quicksuggest.sponsored")
lazy.UrlbarPrefs.get("quickSuggestEnabled") &&
lazy.UrlbarPrefs.get("suggest.quicksuggest.sponsored")
) {
idArgs.push({ id: "urlbar-result-action-sponsored" });
}
@ -2382,7 +2385,7 @@ class UrlbarView {
idArgs.push(...engineNames.map(name => ({ id, args: { engine: name } })));
}
if (UrlbarPrefs.get("groupLabels.enabled")) {
if (lazy.UrlbarPrefs.get("groupLabels.enabled")) {
idArgs.push(
...engineNames.map(name => ({
id: "urlbar-group-search-suggestions",
@ -2457,7 +2460,7 @@ class UrlbarView {
let localSearchMode;
if (source) {
localSearchMode = UrlbarUtils.LOCAL_SEARCH_MODES.find(
localSearchMode = lazy.UrlbarUtils.LOCAL_SEARCH_MODES.find(
m => m.source == source
);
}
@ -2468,8 +2471,8 @@ class UrlbarView {
let isPrivateSearchWithoutPrivateEngine =
result.payload.inPrivateWindow && !result.payload.isPrivateEngine;
let isSearchHistory =
result.type == UrlbarUtils.RESULT_TYPE.SEARCH &&
result.source == UrlbarUtils.RESULT_SOURCE.HISTORY;
result.type == lazy.UrlbarUtils.RESULT_TYPE.SEARCH &&
result.source == lazy.UrlbarUtils.RESULT_SOURCE.HISTORY;
let isSearchSuggestion = result.payload.suggestion && !isSearchHistory;
// For one-off buttons having a source, we update the action for the
@ -2515,7 +2518,7 @@ class UrlbarView {
// If an engine is selected, update search results to use that engine.
// Otherwise, restore their original engines.
if (result.type == UrlbarUtils.RESULT_TYPE.SEARCH) {
if (result.type == lazy.UrlbarUtils.RESULT_TYPE.SEARCH) {
if (engine) {
if (!result.payload.originalEngine) {
result.payload.originalEngine = result.payload.engine;
@ -2549,7 +2552,7 @@ class UrlbarView {
// Update result action text.
if (localSearchMode) {
// Update the result action text for a local one-off.
let name = UrlbarUtils.getResultSourceName(localSearchMode.source);
let name = lazy.UrlbarUtils.getResultSourceName(localSearchMode.source);
this._setElementL10n(action, {
id: `urlbar-result-action-search-${name}`,
});
@ -2568,7 +2571,7 @@ class UrlbarView {
if (item._originalActionSetter) {
item._originalActionSetter();
if (result.heuristic) {
favicon.src = result.payload.icon || UrlbarUtils.ICON.DEFAULT;
favicon.src = result.payload.icon || lazy.UrlbarUtils.ICON.DEFAULT;
}
} else {
Cu.reportError("An item is missing the action setter");
@ -2581,7 +2584,7 @@ class UrlbarView {
if (!iconOverride && (localSearchMode || engine)) {
// For one-offs without an icon, do not allow restyled URL results to
// use their own icons.
iconOverride = UrlbarUtils.ICON.SEARCH_GLASS;
iconOverride = lazy.UrlbarUtils.ICON.SEARCH_GLASS;
}
if (
result.heuristic ||
@ -2600,7 +2603,7 @@ class UrlbarView {
// If the view is open without the input being focused, it will not close
// automatically when the window loses focus. We might be in this state
// after a Search Tip is shown on an engine homepage.
if (!UrlbarPrefs.get("ui.popup.disable_autohide")) {
if (!lazy.UrlbarPrefs.get("ui.popup.disable_autohide")) {
this.close();
}
}
@ -2682,7 +2685,7 @@ class QueryContextCache {
// and therefore shouldn't be evicted except when the top sites change.
this._topSitesContext = null;
this._topSitesListener = () => (this._topSitesContext = null);
UrlbarProviderTopSites.addTopSitesListener(this._topSitesListener);
lazy.UrlbarProviderTopSites.addTopSitesListener(this._topSitesListener);
}
/**
@ -2718,7 +2721,8 @@ class QueryContextCache {
// use it too, like search mode. If the first result is from the top-sites
// provider, assume the context is top sites.
if (
queryContext.results?.[0]?.providerName == UrlbarProviderTopSites.name
queryContext.results?.[0]?.providerName ==
lazy.UrlbarProviderTopSites.name
) {
this._topSitesContext = queryContext;
}
@ -2757,7 +2761,7 @@ async function addDynamicStylesheet(window, stylesheetURL) {
// won't break the whole urlbar.
try {
let uri = Services.io.newURI(stylesheetURL);
let sheet = await styleSheetService.preloadSheetAsync(
let sheet = await lazy.styleSheetService.preloadSheetAsync(
uri,
Ci.nsIStyleSheetService.AGENT_SHEET
);

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

@ -17,7 +17,9 @@ const { UrlbarProvider, UrlbarUtils } = ChromeUtils.import(
"resource:///modules/UrlbarUtils.jsm"
);
XPCOMUtils.defineLazyModuleGetters(this, {
const lazy = {};
XPCOMUtils.defineLazyModuleGetters(lazy, {
AddonTestUtils: "resource://testing-common/AddonTestUtils.jsm",
BrowserTestUtils: "resource://testing-common/BrowserTestUtils.jsm",
BrowserUIUtils: "resource:///modules/BrowserUIUtils.jsm",
@ -123,8 +125,8 @@ var UrlbarTestUtils = {
// Using the value setter in some cases may trim and fetch unexpected
// results, then pick an alternate path.
if (
UrlbarPrefs.get("trimURLs") &&
value != BrowserUIUtils.trimURL(value)
lazy.UrlbarPrefs.get("trimURLs") &&
value != lazy.BrowserUIUtils.trimURL(value)
) {
window.gURLBar.inputField.value = value;
fireInputEvent = true;
@ -345,7 +347,7 @@ var UrlbarTestUtils = {
if (!httpserver) {
throw new Error("Must provide an http server");
}
return BrowserTestUtils.waitForCondition(
return lazy.BrowserTestUtils.waitForCondition(
() => httpserver.connectionNumber == count,
"Waiting for speculative connection setup"
);
@ -414,7 +416,7 @@ var UrlbarTestUtils = {
async withContextMenu(win, task) {
let textBox = win.gURLBar.querySelector("moz-input-box");
let cxmenu = textBox.menupopup;
let openPromise = BrowserTestUtils.waitForEvent(cxmenu, "popupshown");
let openPromise = lazy.BrowserTestUtils.waitForEvent(cxmenu, "popupshown");
this.EventUtils.synthesizeMouseAtCenter(
win.gURLBar.inputField,
{
@ -431,7 +433,10 @@ var UrlbarTestUtils = {
} finally {
// Close the context menu if the task didn't pick anything.
if (cxmenu.state == "open" || cxmenu.state == "showing") {
let closePromise = BrowserTestUtils.waitForEvent(cxmenu, "popuphidden");
let closePromise = lazy.BrowserTestUtils.waitForEvent(
cxmenu,
"popuphidden"
);
cxmenu.hidePopup();
await closePromise;
}
@ -472,7 +477,7 @@ var UrlbarTestUtils = {
// Check the input's placeholder.
const prefName =
"browser.urlbar.placeholderName" +
(PrivateBrowsingUtils.isWindowPrivate(window) ? ".private" : "");
(lazy.PrivateBrowsingUtils.isWindowPrivate(window) ? ".private" : "");
let engineName = Services.prefs.getStringPref(prefName, "");
this.Assert.deepEqual(
window.document.l10n.getAttributes(window.gURLBar.inputField),
@ -595,7 +600,7 @@ var UrlbarTestUtils = {
let engine = Services.search.getEngineByName(
expectedSearchMode.engineName
);
let engineRootDomain = UrlbarSearchUtils.getRootDomainFromEngine(
let engineRootDomain = lazy.UrlbarSearchUtils.getRootDomainFromEngine(
engine
);
let resultUrl = new URL(result.url);
@ -626,7 +631,7 @@ var UrlbarTestUtils = {
// Ensure the the one-offs are finished rebuilding and visible.
let oneOffs = this.getOneOffSearchButtons(window);
await TestUtils.waitForCondition(
await lazy.TestUtils.waitForCondition(
() => !oneOffs._rebuilding,
"Waiting for one-offs to finish rebuilding"
);
@ -770,7 +775,7 @@ var UrlbarTestUtils = {
* @returns {UrlbarController} A new controller.
*/
newMockController(options = {}) {
return new UrlbarController(
return new lazy.UrlbarController(
Object.assign(
{
input: {
@ -804,7 +809,7 @@ var UrlbarTestUtils = {
// This is necessary because UrlbarMuxerUnifiedComplete.sort calls
// Services.search.parseSubmissionURL, so we need engines.
try {
await AddonTestUtils.promiseStartupManager();
await lazy.AddonTestUtils.promiseStartupManager();
} catch (error) {
if (!error.message.includes("already started")) {
throw error;
@ -823,9 +828,9 @@ UrlbarTestUtils.formHistory = {
* The window containing the urlbar.
* @returns {Promise} resolved once the operation is complete.
*/
add(values = [], window = BrowserWindowTracker.getTopWindow()) {
add(values = [], window = lazy.BrowserWindowTracker.getTopWindow()) {
let fieldname = this.getFormHistoryName(window);
return FormHistoryTestUtils.add(fieldname, values);
return lazy.FormHistoryTestUtils.add(fieldname, values);
},
/**
@ -838,9 +843,9 @@ UrlbarTestUtils.formHistory = {
* The window containing the urlbar.
* @returns {Promise} resolved once the operation is complete.
*/
remove(values = [], window = BrowserWindowTracker.getTopWindow()) {
remove(values = [], window = lazy.BrowserWindowTracker.getTopWindow()) {
let fieldname = this.getFormHistoryName(window);
return FormHistoryTestUtils.remove(fieldname, values);
return lazy.FormHistoryTestUtils.remove(fieldname, values);
},
/**
@ -851,9 +856,9 @@ UrlbarTestUtils.formHistory = {
* The window containing the urlbar.
* @returns {Promise} resolved once the operation is complete.
*/
clear(window = BrowserWindowTracker.getTopWindow()) {
clear(window = lazy.BrowserWindowTracker.getTopWindow()) {
let fieldname = this.getFormHistoryName(window);
return FormHistoryTestUtils.clear(fieldname);
return lazy.FormHistoryTestUtils.clear(fieldname);
},
/**
@ -866,9 +871,9 @@ UrlbarTestUtils.formHistory = {
* @returns {Promise}
* A promise resolved with an array of found form history entries.
*/
search(criteria = {}, window = BrowserWindowTracker.getTopWindow()) {
search(criteria = {}, window = lazy.BrowserWindowTracker.getTopWindow()) {
let fieldname = this.getFormHistoryName(window);
return FormHistoryTestUtils.search(fieldname, criteria);
return lazy.FormHistoryTestUtils.search(fieldname, criteria);
},
/**
@ -880,7 +885,7 @@ UrlbarTestUtils.formHistory = {
* Resolved on the next specified form history change.
*/
promiseChanged(change = null) {
return TestUtils.topicObserved(
return lazy.TestUtils.topicObserved(
"satchel-storage-changed",
(subject, data) => !change || data == "formhistory-" + change
);
@ -894,7 +899,7 @@ UrlbarTestUtils.formHistory = {
* @returns {string}
* The form history name of the urlbar in the window.
*/
getFormHistoryName(window = BrowserWindowTracker.getTopWindow()) {
getFormHistoryName(window = lazy.BrowserWindowTracker.getTopWindow()) {
return window ? window.gURLBar.formHistoryName : "searchbar-history";
},
};
@ -960,7 +965,7 @@ class TestProvider extends UrlbarProvider {
addCallback(this, result);
} else {
await new Promise(resolve => {
setTimeout(() => {
lazy.setTimeout(() => {
addCallback(this, result);
resolve();
}, this._addTimeout);

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

@ -15,7 +15,9 @@ const {
PartnerLinkAttribution,
} = ChromeUtils.import("resource:///modules/PartnerLinkAttribution.jsm");
XPCOMUtils.defineLazyModuleGetters(this, {
const lazy = {};
XPCOMUtils.defineLazyModuleGetters(lazy, {
ExperimentAPI: "resource://nimbus/ExperimentAPI.jsm",
ExperimentFakes: "resource://testing-common/NimbusTestUtils.jsm",
ExperimentManager: "resource://nimbus/lib/ExperimentManager.jsm",
@ -30,7 +32,7 @@ XPCOMUtils.defineLazyModuleGetters(this, {
UrlbarUtils: "resource:///modules/UrlbarUtils.jsm",
});
XPCOMUtils.defineLazyGetter(this, "UrlbarTestUtils", () => {
XPCOMUtils.defineLazyGetter(lazy, "UrlbarTestUtils", () => {
const { UrlbarTestUtils: module } = ChromeUtils.import(
"resource://testing-common/UrlbarTestUtils.jsm"
);
@ -105,11 +107,11 @@ class QSTestUtils {
}
get BEST_MATCH_LEARN_MORE_URL() {
return UrlbarProviderQuickSuggest.bestMatchHelpUrl;
return lazy.UrlbarProviderQuickSuggest.bestMatchHelpUrl;
}
get SCALARS() {
return UrlbarProviderQuickSuggest.TELEMETRY_SCALARS;
return lazy.UrlbarProviderQuickSuggest.TELEMETRY_SCALARS;
}
get TELEMETRY_EVENT_CATEGORY() {
@ -183,21 +185,21 @@ class QSTestUtils {
this.info?.(
"ensureQuickSuggestInit awaiting UrlbarQuickSuggest.readyPromise"
);
await UrlbarQuickSuggest.readyPromise;
await lazy.UrlbarQuickSuggest.readyPromise;
this.info?.(
"ensureQuickSuggestInit done awaiting UrlbarQuickSuggest.readyPromise"
);
// Stub _queueSettingsSync() so any actual remote settings syncs that happen
// during the test are ignored.
let sandbox = sinon.createSandbox();
sandbox.stub(UrlbarQuickSuggest, "_queueSettingsSync");
let sandbox = lazy.sinon.createSandbox();
sandbox.stub(lazy.UrlbarQuickSuggest, "_queueSettingsSync");
let cleanup = () => sandbox.restore();
this.registerCleanupFunction?.(cleanup);
if (results) {
UrlbarQuickSuggest._resultsByKeyword.clear();
await UrlbarQuickSuggest._addResults(results);
lazy.UrlbarQuickSuggest._resultsByKeyword.clear();
await lazy.UrlbarQuickSuggest._addResults(results);
}
if (config) {
this.setConfig(config);
@ -219,14 +221,14 @@ class QSTestUtils {
*/
async initNimbusFeature(value = {}) {
this.info?.("initNimbusFeature awaiting ExperimentManager.onStartup");
await ExperimentManager.onStartup();
await lazy.ExperimentManager.onStartup();
this.info?.("initNimbusFeature awaiting ExperimentAPI.ready");
await ExperimentAPI.ready();
await lazy.ExperimentAPI.ready();
this.info?.("initNimbusFeature awaiting ExperimentFakes.enrollWithRollout");
let doCleanup = await ExperimentFakes.enrollWithRollout({
featureId: NimbusFeatures.urlbar.featureId,
let doCleanup = await lazy.ExperimentFakes.enrollWithRollout({
featureId: lazy.NimbusFeatures.urlbar.featureId,
value: { enabled: true, ...value },
});
@ -250,7 +252,7 @@ class QSTestUtils {
* @param {object} config
*/
setConfig(config) {
UrlbarQuickSuggest._setConfig(config);
lazy.UrlbarQuickSuggest._setConfig(config);
}
/**
@ -276,15 +278,15 @@ class QSTestUtils {
// If we try to set the scenario before a previous update has finished,
// `updateFirefoxSuggestScenario` will bail, so wait.
await this.waitForScenarioUpdated();
await UrlbarPrefs.updateFirefoxSuggestScenario({ scenario });
await lazy.UrlbarPrefs.updateFirefoxSuggestScenario({ scenario });
}
/**
* Waits for any prior scenario update to finish.
*/
async waitForScenarioUpdated() {
await TestUtils.waitForCondition(
() => !UrlbarPrefs.updatingFirefoxSuggestScenario,
await lazy.TestUtils.waitForCondition(
() => !lazy.UrlbarPrefs.updatingFirefoxSuggestScenario,
"Waiting for updatingFirefoxSuggestScenario to be false"
);
}
@ -322,7 +324,7 @@ class QSTestUtils {
);
if (index < 0) {
let resultCount = UrlbarTestUtils.getResultCount(window);
let resultCount = lazy.UrlbarTestUtils.getResultCount(window);
if (isBestMatch) {
index = 1;
this.Assert.greater(
@ -340,7 +342,10 @@ class QSTestUtils {
}
}
let details = await UrlbarTestUtils.getDetailsOfResultAt(window, index);
let details = await lazy.UrlbarTestUtils.getDetailsOfResultAt(
window,
index
);
let { result } = details;
this.info?.(
@ -352,7 +357,7 @@ class QSTestUtils {
"UrlbarProviderQuickSuggest",
"Result provider name is UrlbarProviderQuickSuggest"
);
this.Assert.equal(details.type, UrlbarUtils.RESULT_TYPE.URL);
this.Assert.equal(details.type, lazy.UrlbarUtils.RESULT_TYPE.URL);
this.Assert.equal(details.isSponsored, isSponsored, "Result isSponsored");
if (url) {
this.Assert.equal(details.url, url, "Result URL");
@ -387,13 +392,13 @@ class QSTestUtils {
if (!isBestMatch) {
this.Assert.equal(
!!blockButton,
UrlbarPrefs.get("quickSuggestBlockingEnabled"),
lazy.UrlbarPrefs.get("quickSuggestBlockingEnabled"),
"The block button is present iff quick suggest blocking is enabled"
);
} else {
this.Assert.equal(
!!blockButton,
UrlbarPrefs.get("bestMatchBlockingEnabled"),
lazy.UrlbarPrefs.get("bestMatchBlockingEnabled"),
"The block button is present iff best match blocking is enabled"
);
}
@ -409,7 +414,10 @@ class QSTestUtils {
* The index of the result.
*/
async assertIsNotQuickSuggest(window, index) {
let details = await UrlbarTestUtils.getDetailsOfResultAt(window, index);
let details = await lazy.UrlbarTestUtils.getDetailsOfResultAt(
window,
index
);
this.Assert.notEqual(
details.result.providerName,
"UrlbarProviderQuickSuggest",
@ -423,7 +431,7 @@ class QSTestUtils {
* @param {object} window
*/
async assertNoQuickSuggestResults(window) {
for (let i = 0; i < UrlbarTestUtils.getResultCount(window); i++) {
for (let i = 0; i < lazy.UrlbarTestUtils.getResultCount(window); i++) {
await this.assertIsNotQuickSuggest(window, i);
}
}
@ -437,10 +445,14 @@ class QSTestUtils {
* expect a scalar not to be incremented, don't include it.
*/
assertScalars(expectedIndexesByScalarName) {
let scalars = TelemetryTestUtils.getProcessScalars("parent", true, true);
let scalars = lazy.TelemetryTestUtils.getProcessScalars(
"parent",
true,
true
);
for (let scalarName of Object.values(this.SCALARS)) {
if (scalarName in expectedIndexesByScalarName) {
TelemetryTestUtils.assertKeyedScalar(
lazy.TelemetryTestUtils.assertKeyedScalar(
scalars,
scalarName,
expectedIndexesByScalarName[scalarName],
@ -470,7 +482,7 @@ class QSTestUtils {
* The options object to pass to `TelemetryTestUtils.assertEvents()`.
*/
assertEvents(expectedEvents, filterOverrides = {}, options = undefined) {
TelemetryTestUtils.assertEvents(
lazy.TelemetryTestUtils.assertEvents(
expectedEvents,
{
category: QuickSuggestTestUtils.TELEMETRY_EVENT_CATEGORY,
@ -494,7 +506,7 @@ class QSTestUtils {
* it otherwise.
*/
createTelemetryPingSpy() {
let sandbox = sinon.createSandbox();
let sandbox = lazy.sinon.createSandbox();
let spy = sandbox.spy(
PartnerLinkAttribution._pingCentre,
"sendStructuredIngestionPing"
@ -617,7 +629,10 @@ class QSTestUtils {
* }
*/
assertTimestampsReplaced(result, urls) {
let { TIMESTAMP_TEMPLATE, TIMESTAMP_LENGTH } = UrlbarProviderQuickSuggest;
let {
TIMESTAMP_TEMPLATE,
TIMESTAMP_LENGTH,
} = lazy.UrlbarProviderQuickSuggest;
// Parse the timestamp strings from each payload property and save them in
// `urls[key].timestamp`.
@ -689,7 +704,7 @@ class QSTestUtils {
*/
async enrollExperiment({ valueOverrides = {} }) {
this.info?.("Awaiting ExperimentAPI.ready");
await ExperimentAPI.ready();
await lazy.ExperimentAPI.ready();
// Wait for any prior scenario updates to finish. If updates are ongoing,
// UrlbarPrefs will ignore the Nimbus update when the experiment is
@ -701,15 +716,17 @@ class QSTestUtils {
// These notifications signal either that pref updates due to enrollment are
// done or that updates weren't necessary.
let updatePromise = Promise.race([
TestUtils.topicObserved(QuickSuggestTestUtils.UPDATE_TOPIC),
TestUtils.topicObserved(QuickSuggestTestUtils.UPDATE_SKIPPED_TOPIC),
lazy.TestUtils.topicObserved(QuickSuggestTestUtils.UPDATE_TOPIC),
lazy.TestUtils.topicObserved(QuickSuggestTestUtils.UPDATE_SKIPPED_TOPIC),
]);
let doExperimentCleanup = await ExperimentFakes.enrollWithFeatureConfig({
enabled: true,
featureId: "urlbar",
value: valueOverrides,
});
let doExperimentCleanup = await lazy.ExperimentFakes.enrollWithFeatureConfig(
{
enabled: true,
featureId: "urlbar",
value: valueOverrides,
}
);
// Wait for the pref updates triggered by the experiment enrollment.
this.info?.("Awaiting update after enrolling in experiment");
@ -719,8 +736,10 @@ class QSTestUtils {
// The same pref updates will be triggered by unenrollment, so wait for
// them again.
let unenrollUpdatePromise = Promise.race([
TestUtils.topicObserved(QuickSuggestTestUtils.UPDATE_TOPIC),
TestUtils.topicObserved(QuickSuggestTestUtils.UPDATE_SKIPPED_TOPIC),
lazy.TestUtils.topicObserved(QuickSuggestTestUtils.UPDATE_TOPIC),
lazy.TestUtils.topicObserved(
QuickSuggestTestUtils.UPDATE_SKIPPED_TOPIC
),
]);
this.info?.("Awaiting experiment cleanup");
@ -740,8 +759,8 @@ class QSTestUtils {
await new Promise(resolve => Services.tm.idleDispatchToMainThread(resolve));
Services.telemetry.clearEvents();
NimbusFeatures.urlbar._didSendExposureEvent = false;
UrlbarQuickSuggest._recordedExposureEvent = false;
lazy.NimbusFeatures.urlbar._didSendExposureEvent = false;
lazy.UrlbarQuickSuggest._recordedExposureEvent = false;
}
/**
@ -755,7 +774,7 @@ class QSTestUtils {
*/
async assertExposureEvent(expectedRecorded) {
this.Assert.equal(
UrlbarQuickSuggest._recordedExposureEvent,
lazy.UrlbarQuickSuggest._recordedExposureEvent,
expectedRecorded,
"_recordedExposureEvent is correct"
);
@ -781,7 +800,7 @@ class QSTestUtils {
// so likewise queue the assert to idle instead of doing it immediately.
await new Promise(resolve => {
Services.tm.idleDispatchToMainThread(() => {
TelemetryTestUtils.assertEvents(expectedEvents, filter);
lazy.TelemetryTestUtils.assertEvents(expectedEvents, filter);
resolve();
});
});

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

@ -64,13 +64,6 @@ module.exports = {
"no-redeclare": ["error", { builtinGlobals: false }],
},
},
{
// Temporarily disable until the proxy-based loader gets landed.
files: ["browser/components/urlbar/**"],
rules: {
"mozilla/reject-global-this": "off",
},
},
{
files: ["**/*.mjs", "**/*.jsm"],
rules: {