summaryrefslogtreecommitdiffstats
path: root/application/basilisk/components/newtab
diff options
context:
space:
mode:
authorwolfbeast <mcwerewolf@gmail.com>2018-06-04 13:17:38 +0200
committerwolfbeast <mcwerewolf@gmail.com>2018-06-04 13:17:38 +0200
commita1be17c1cea81ebb1e8b131a662c698d78f3f7f2 (patch)
treea92f7de513be600cc07bac458183e9af40e00c06 /application/basilisk/components/newtab
parentbf11fdd304898ac675e39b01b280d39550e419d0 (diff)
downloadUXP-a1be17c1cea81ebb1e8b131a662c698d78f3f7f2.tar
UXP-a1be17c1cea81ebb1e8b131a662c698d78f3f7f2.tar.gz
UXP-a1be17c1cea81ebb1e8b131a662c698d78f3f7f2.tar.lz
UXP-a1be17c1cea81ebb1e8b131a662c698d78f3f7f2.tar.xz
UXP-a1be17c1cea81ebb1e8b131a662c698d78f3f7f2.zip
Issue #303 Part 1: Move basilisk files from /browser to /application/basilisk
Diffstat (limited to 'application/basilisk/components/newtab')
-rw-r--r--application/basilisk/components/newtab/NewTabComponents.manifest2
-rw-r--r--application/basilisk/components/newtab/NewTabMessages.jsm242
-rw-r--r--application/basilisk/components/newtab/NewTabPrefsProvider.jsm114
-rw-r--r--application/basilisk/components/newtab/NewTabRemoteResources.jsm15
-rw-r--r--application/basilisk/components/newtab/NewTabSearchProvider.jsm103
-rw-r--r--application/basilisk/components/newtab/NewTabURL.jsm36
-rw-r--r--application/basilisk/components/newtab/NewTabWebChannel.jsm299
-rw-r--r--application/basilisk/components/newtab/PlacesProvider.jsm211
-rw-r--r--application/basilisk/components/newtab/PreviewProvider.jsm49
-rw-r--r--application/basilisk/components/newtab/aboutNewTabService.js289
-rw-r--r--application/basilisk/components/newtab/moz.build27
-rw-r--r--application/basilisk/components/newtab/nsIAboutNewTabService.idl63
12 files changed, 1450 insertions, 0 deletions
diff --git a/application/basilisk/components/newtab/NewTabComponents.manifest b/application/basilisk/components/newtab/NewTabComponents.manifest
new file mode 100644
index 000000000..42db65acd
--- /dev/null
+++ b/application/basilisk/components/newtab/NewTabComponents.manifest
@@ -0,0 +1,2 @@
+component {dfcd2adc-7867-4d3a-ba70-17501f208142} aboutNewTabService.js
+contract @mozilla.org/browser/aboutnewtab-service;1 {dfcd2adc-7867-4d3a-ba70-17501f208142}
diff --git a/application/basilisk/components/newtab/NewTabMessages.jsm b/application/basilisk/components/newtab/NewTabMessages.jsm
new file mode 100644
index 000000000..0816ed65a
--- /dev/null
+++ b/application/basilisk/components/newtab/NewTabMessages.jsm
@@ -0,0 +1,242 @@
+/* global
+ NewTabWebChannel,
+ NewTabPrefsProvider,
+ PlacesProvider,
+ PreviewProvider,
+ NewTabSearchProvider,
+ Preferences,
+ XPCOMUtils,
+ Task
+*/
+
+/* exported NewTabMessages */
+
+"use strict";
+
+const {utils: Cu} = Components;
+Cu.import("resource://gre/modules/Preferences.jsm");
+Cu.import("resource://gre/modules/XPCOMUtils.jsm");
+Cu.import("resource://gre/modules/Task.jsm");
+
+XPCOMUtils.defineLazyModuleGetter(this, "PlacesProvider",
+ "resource:///modules/PlacesProvider.jsm");
+XPCOMUtils.defineLazyModuleGetter(this, "PreviewProvider",
+ "resource:///modules/PreviewProvider.jsm");
+XPCOMUtils.defineLazyModuleGetter(this, "NewTabPrefsProvider",
+ "resource:///modules/NewTabPrefsProvider.jsm");
+XPCOMUtils.defineLazyModuleGetter(this, "NewTabSearchProvider",
+ "resource:///modules/NewTabSearchProvider.jsm");
+XPCOMUtils.defineLazyModuleGetter(this, "NewTabWebChannel",
+ "resource:///modules/NewTabWebChannel.jsm");
+
+this.EXPORTED_SYMBOLS = ["NewTabMessages"];
+
+const PREF_ENABLED = "browser.newtabpage.remote";
+const CURRENT_ENGINE = "browser-search-engine-modified";
+
+// Action names are from the content's perspective. in from chrome == out from content
+// Maybe replace the ACTION objects by a bi-directional Map a bit later?
+const ACTIONS = {
+ inboundActions: [
+ "REQUEST_PREFS",
+ "REQUEST_THUMB",
+ "REQUEST_FRECENT",
+ "REQUEST_UISTRINGS",
+ "REQUEST_SEARCH_SUGGESTIONS",
+ "REQUEST_MANAGE_ENGINES",
+ "REQUEST_SEARCH_STATE",
+ "REQUEST_REMOVE_FORM_HISTORY",
+ "REQUEST_PERFORM_SEARCH",
+ "REQUEST_CYCLE_ENGINE",
+ ],
+ prefs: {
+ inPrefs: "REQUEST_PREFS",
+ outPrefs: "RECEIVE_PREFS",
+ },
+ preview: {
+ inThumb: "REQUEST_THUMB",
+ outThumb: "RECEIVE_THUMB",
+ },
+ links: {
+ inFrecent: "REQUEST_FRECENT",
+ outFrecent: "RECEIVE_FRECENT",
+ outPlacesChange: "RECEIVE_PLACES_CHANGE",
+ },
+ search: {
+ inSearch: {
+ UIStrings: "REQUEST_UISTRINGS",
+ suggestions: "REQUEST_SEARCH_SUGGESTIONS",
+ manageEngines: "REQUEST_MANAGE_ENGINES",
+ state: "REQUEST_SEARCH_STATE",
+ removeFormHistory: "REQUEST_REMOVE_FORM_HISTORY",
+ performSearch: "REQUEST_PERFORM_SEARCH",
+ cycleEngine: "REQUEST_CYCLE_ENGINE"
+ },
+ outSearch: {
+ UIStrings: "RECEIVE_UISTRINGS",
+ suggestions: "RECEIVE_SEARCH_SUGGESTIONS",
+ state: "RECEIVE_SEARCH_STATE",
+ currentEngine: "RECEIVE_CURRENT_ENGINE"
+ },
+ }
+};
+
+let NewTabMessages = {
+
+ _prefs: {},
+
+ /** NEWTAB EVENT HANDLERS **/
+
+ handleContentRequest(actionName, {data, target}) {
+ switch (actionName) {
+ case ACTIONS.prefs.inPrefs:
+ // Return to the originator all newtabpage prefs
+ let results = NewTabPrefsProvider.prefs.newtabPagePrefs;
+ NewTabWebChannel.send(ACTIONS.prefs.outPrefs, results, target);
+ break;
+ case ACTIONS.preview.inThumb:
+ // Return to the originator a preview URL
+ PreviewProvider.getThumbnail(data).then(imgData => {
+ NewTabWebChannel.send(ACTIONS.preview.outThumb, {url: data, imgData}, target);
+ });
+ break;
+ case ACTIONS.links.inFrecent:
+ // Return to the originator the top frecent links
+ PlacesProvider.links.getLinks().then(links => {
+ NewTabWebChannel.send(ACTIONS.links.outFrecent, links, target);
+ });
+ break;
+ case ACTIONS.search.inSearch.UIStrings:
+ // Return to the originator all search strings to display
+ let strings = NewTabSearchProvider.search.searchSuggestionUIStrings;
+ NewTabWebChannel.send(ACTIONS.search.outSearch.UIStrings, strings, target);
+ break;
+ case ACTIONS.search.inSearch.suggestions:
+ // Return to the originator all search suggestions
+ Task.spawn(function*() {
+ try {
+ let {engineName, searchString} = data;
+ let suggestions = yield NewTabSearchProvider.search.asyncGetSuggestions(engineName, searchString, target);
+ NewTabWebChannel.send(ACTIONS.search.outSearch.suggestions, suggestions, target);
+ } catch (e) {
+ Cu.reportError(e);
+ }
+ });
+ break;
+ case ACTIONS.search.inSearch.manageEngines:
+ // Open about:preferences to manage search state
+ NewTabSearchProvider.search.manageEngines(target.browser);
+ break;
+ case ACTIONS.search.inSearch.state:
+ // Return the state of the search component (i.e current engine and visible engine details)
+ Task.spawn(function*() {
+ try {
+ let state = yield NewTabSearchProvider.search.asyncGetState();
+ NewTabWebChannel.broadcast(ACTIONS.search.outSearch.state, state);
+ } catch (e) {
+ Cu.reportError(e);
+ }
+ });
+ break;
+ case ACTIONS.search.inSearch.removeFormHistory:
+ // Remove a form history entry from the search component
+ let suggestion = data;
+ NewTabSearchProvider.search.removeFormHistory(target, suggestion);
+ break;
+ case ACTIONS.search.inSearch.performSearch:
+ // Perform a search
+ NewTabSearchProvider.search.asyncPerformSearch(target, data).catch(Cu.reportError);
+ break;
+ case ACTIONS.search.inSearch.cycleEngine:
+ // Set the new current engine
+ NewTabSearchProvider.search.asyncCycleEngine(data).catch(Cu.reportError);
+ break;
+ }
+ },
+
+ /*
+ * Broadcast places change to all open newtab pages
+ */
+ handlePlacesChange(type, data) {
+ NewTabWebChannel.broadcast(ACTIONS.links.outPlacesChange, {type, data});
+ },
+
+ /*
+ * Broadcast current engine has changed to all open newtab pages
+ */
+ _handleCurrentEngineChange(name, value) { // jshint unused: false
+ let engine = value;
+ NewTabWebChannel.broadcast(ACTIONS.search.outSearch.currentEngine, engine);
+ },
+
+ /*
+ * Broadcast preference changes to all open newtab pages
+ */
+ handlePrefChange(actionName, value) {
+ let prefChange = {};
+ prefChange[actionName] = value;
+ NewTabWebChannel.broadcast(ACTIONS.prefs.outPrefs, prefChange);
+ },
+
+ _handleEnabledChange(prefName, value) {
+ if (prefName === PREF_ENABLED) {
+ if (this._prefs.enabled && !value) {
+ this.uninit();
+ } else if (!this._prefs.enabled && value) {
+ this.init();
+ }
+ }
+ },
+
+ init() {
+ this.handleContentRequest = this.handleContentRequest.bind(this);
+ this._handleEnabledChange = this._handleEnabledChange.bind(this);
+ this._handleCurrentEngineChange = this._handleCurrentEngineChange.bind(this);
+
+ PlacesProvider.links.init();
+ NewTabPrefsProvider.prefs.init();
+ NewTabSearchProvider.search.init();
+ NewTabWebChannel.init();
+
+ this._prefs.enabled = Preferences.get(PREF_ENABLED, false);
+
+ if (this._prefs.enabled) {
+ for (let action of ACTIONS.inboundActions) {
+ NewTabWebChannel.on(action, this.handleContentRequest);
+ }
+
+ NewTabPrefsProvider.prefs.on(PREF_ENABLED, this._handleEnabledChange);
+ NewTabSearchProvider.search.on(CURRENT_ENGINE, this._handleCurrentEngineChange);
+
+ for (let pref of NewTabPrefsProvider.newtabPagePrefSet) {
+ NewTabPrefsProvider.prefs.on(pref, this.handlePrefChange);
+ }
+
+ PlacesProvider.links.on("deleteURI", this.handlePlacesChange);
+ PlacesProvider.links.on("clearHistory", this.handlePlacesChange);
+ PlacesProvider.links.on("linkChanged", this.handlePlacesChange);
+ PlacesProvider.links.on("manyLinksChanged", this.handlePlacesChange);
+ }
+ },
+
+ uninit() {
+ this._prefs.enabled = Preferences.get(PREF_ENABLED, false);
+
+ if (this._prefs.enabled) {
+ NewTabPrefsProvider.prefs.off(PREF_ENABLED, this._handleEnabledChange);
+ NewTabSearchProvider.search.off(CURRENT_ENGINE, this._handleCurrentEngineChange);
+
+ for (let action of ACTIONS.inboundActions) {
+ NewTabWebChannel.off(action, this.handleContentRequest);
+ }
+
+ for (let pref of NewTabPrefsProvider.newtabPagePrefSet) {
+ NewTabPrefsProvider.prefs.off(pref, this.handlePrefChange);
+ }
+ }
+
+ NewTabPrefsProvider.prefs.uninit();
+ NewTabSearchProvider.search.uninit();
+ NewTabWebChannel.uninit();
+ }
+};
diff --git a/application/basilisk/components/newtab/NewTabPrefsProvider.jsm b/application/basilisk/components/newtab/NewTabPrefsProvider.jsm
new file mode 100644
index 000000000..c1d8b4149
--- /dev/null
+++ b/application/basilisk/components/newtab/NewTabPrefsProvider.jsm
@@ -0,0 +1,114 @@
+/* global Services, Preferences, EventEmitter, XPCOMUtils */
+/* exported NewTabPrefsProvider */
+
+"use strict";
+
+this.EXPORTED_SYMBOLS = ["NewTabPrefsProvider"];
+
+const {interfaces: Ci, utils: Cu} = Components;
+Cu.import("resource://gre/modules/Services.jsm");
+Cu.import("resource://gre/modules/Preferences.jsm");
+Cu.import("resource://gre/modules/XPCOMUtils.jsm");
+
+XPCOMUtils.defineLazyGetter(this, "EventEmitter", function() {
+ const {EventEmitter} = Cu.import("resource://devtools/shared/event-emitter.js", {});
+ return EventEmitter;
+});
+
+// Supported prefs and data type
+const gPrefsMap = new Map([
+ ["browser.newtabpage.remote", "bool"],
+ ["browser.newtabpage.remote.mode", "str"],
+ ["browser.newtabpage.remote.version", "str"],
+ ["browser.newtabpage.enabled", "bool"],
+ ["browser.newtabpage.enhanced", "bool"],
+ ["browser.newtabpage.introShown", "bool"],
+ ["browser.newtabpage.updateIntroShown", "bool"],
+ ["browser.newtabpage.pinned", "str"],
+ ["browser.newtabpage.blocked", "str"],
+ ["intl.locale.matchOS", "bool"],
+ ["general.useragent.locale", "localized"],
+ ["browser.search.hiddenOneOffs", "str"],
+]);
+
+// prefs that are important for the newtab page
+const gNewtabPagePrefs = new Set([
+ "browser.newtabpage.enabled",
+ "browser.newtabpage.enhanced",
+ "browser.newtabpage.pinned",
+ "browser.newtabpage.blocked",
+ "browser.newtabpage.introShown",
+ "browser.newtabpage.updateIntroShown",
+ "browser.search.hiddenOneOffs",
+]);
+
+let PrefsProvider = function PrefsProvider() {
+ EventEmitter.decorate(this);
+};
+
+PrefsProvider.prototype = {
+
+ observe(subject, topic, data) { // jshint ignore:line
+ if (topic === "nsPref:changed") {
+ if (gPrefsMap.has(data)) {
+ switch (gPrefsMap.get(data)) {
+ case "bool":
+ this.emit(data, Preferences.get(data, false));
+ break;
+ case "str":
+ this.emit(data, Preferences.get(data, ""));
+ break;
+ case "localized":
+ try {
+ this.emit(data, Preferences.get(data, "", Ci.nsIPrefLocalizedString));
+ } catch (e) {
+ this.emit(data, Preferences.get(data, ""));
+ }
+ break;
+ default:
+ this.emit(data);
+ break;
+ }
+ }
+ } else {
+ Cu.reportError(new Error("NewTabPrefsProvider observing unknown topic"));
+ }
+ },
+
+ /*
+ * Return the preferences that are important to the newtab page
+ */
+ get newtabPagePrefs() {
+ let results = {};
+ for (let pref of gNewtabPagePrefs) {
+ results[pref] = Preferences.get(pref, null);
+ }
+ return results;
+ },
+
+ get prefsMap() {
+ return gPrefsMap;
+ },
+
+ init() {
+ for (let pref of gPrefsMap.keys()) {
+ Services.prefs.addObserver(pref, this, false);
+ }
+ },
+
+ uninit() {
+ for (let pref of gPrefsMap.keys()) {
+ Services.prefs.removeObserver(pref, this, false);
+ }
+ }
+};
+
+/**
+ * Singleton that serves as the default new tab pref provider for the grid.
+ */
+const gPrefs = new PrefsProvider();
+
+let NewTabPrefsProvider = {
+ prefs: gPrefs,
+ newtabPagePrefSet: gNewtabPagePrefs,
+};
diff --git a/application/basilisk/components/newtab/NewTabRemoteResources.jsm b/application/basilisk/components/newtab/NewTabRemoteResources.jsm
new file mode 100644
index 000000000..57351b15c
--- /dev/null
+++ b/application/basilisk/components/newtab/NewTabRemoteResources.jsm
@@ -0,0 +1,15 @@
+/* exported NewTabRemoteResources */
+
+"use strict";
+
+this.EXPORTED_SYMBOLS = ["NewTabRemoteResources"];
+
+const NewTabRemoteResources = {
+ MODE_CHANNEL_MAP: {
+ production: {origin: "https://content.cdn.mozilla.net"},
+ staging: {origin: "https://s3_proxy_tiles.stage.mozaws.net"},
+ test: {origin: "https://example.com"},
+ test2: {origin: "http://mochi.test:8888"},
+ dev: {origin: "http://localhost:8888"}
+ }
+};
diff --git a/application/basilisk/components/newtab/NewTabSearchProvider.jsm b/application/basilisk/components/newtab/NewTabSearchProvider.jsm
new file mode 100644
index 000000000..a50d8c706
--- /dev/null
+++ b/application/basilisk/components/newtab/NewTabSearchProvider.jsm
@@ -0,0 +1,103 @@
+/* global XPCOMUtils, ContentSearch, Task, Services, EventEmitter */
+/* exported NewTabSearchProvider */
+
+"use strict";
+
+this.EXPORTED_SYMBOLS = ["NewTabSearchProvider"];
+
+const {utils: Cu, interfaces: Ci} = Components;
+const CURRENT_ENGINE = "browser-search-engine-modified";
+
+Cu.import("resource://gre/modules/XPCOMUtils.jsm");
+Cu.import("resource://gre/modules/Task.jsm");
+Cu.import("resource://gre/modules/Services.jsm");
+
+XPCOMUtils.defineLazyModuleGetter(this, "ContentSearch",
+ "resource:///modules/ContentSearch.jsm");
+
+XPCOMUtils.defineLazyGetter(this, "EventEmitter", function() {
+ const {EventEmitter} = Cu.import("resource://devtools/shared/event-emitter.js", {});
+ return EventEmitter;
+});
+
+function SearchProvider() {
+ EventEmitter.decorate(this);
+}
+
+SearchProvider.prototype = {
+
+ observe(subject, topic, data) { // jshint unused:false
+ // all other topics are not relevant to content searches and can be
+ // ignored by NewTabSearchProvider
+ if (data === "engine-current" && topic === CURRENT_ENGINE) {
+ Task.spawn(function* () {
+ try {
+ let state = yield ContentSearch.currentStateObj(true);
+ let engine = state.currentEngine;
+ this.emit(CURRENT_ENGINE, engine);
+ } catch (e) {
+ Cu.reportError(e);
+ }
+ }.bind(this));
+ }
+ },
+
+ init() {
+ try {
+ Services.obs.addObserver(this, CURRENT_ENGINE, true);
+ } catch (e) {
+ Cu.reportError(e);
+ }
+ },
+
+ QueryInterface: XPCOMUtils.generateQI([Ci.nsIObserver,
+ Ci.nsISupportsWeakReference
+ ]),
+
+ uninit() {
+ try {
+ Services.obs.removeObserver(this, CURRENT_ENGINE, true);
+ } catch (e) {
+ Cu.reportError(e);
+ }
+ },
+
+ get searchSuggestionUIStrings() {
+ return ContentSearch.searchSuggestionUIStrings;
+ },
+
+ removeFormHistory({browser}, suggestion) {
+ ContentSearch.removeFormHistoryEntry({target: browser}, suggestion);
+ },
+
+ manageEngines(browser) {
+ const browserWin = browser.ownerGlobal;
+ browserWin.openPreferences("paneSearch");
+ },
+
+ asyncGetState: Task.async(function*() {
+ let state = yield ContentSearch.currentStateObj(true);
+ return state;
+ }),
+
+ asyncPerformSearch: Task.async(function*({browser}, searchData) {
+ ContentSearch.performSearch({target: browser}, searchData);
+ yield ContentSearch.addFormHistoryEntry({target: browser}, searchData.searchString);
+ }),
+
+ asyncCycleEngine: Task.async(function*(engineName) {
+ Services.search.currentEngine = Services.search.getEngineByName(engineName);
+ let state = yield ContentSearch.currentStateObj(true);
+ let newEngine = state.currentEngine;
+ this.emit(CURRENT_ENGINE, newEngine);
+ }),
+
+ asyncGetSuggestions: Task.async(function*(engineName, searchString, target) {
+ let suggestions = ContentSearch.getSuggestions(engineName, searchString, target.browser);
+ return suggestions;
+ }),
+};
+
+const NewTabSearchProvider = {
+ search: new SearchProvider(),
+};
diff --git a/application/basilisk/components/newtab/NewTabURL.jsm b/application/basilisk/components/newtab/NewTabURL.jsm
new file mode 100644
index 000000000..5000eae2e
--- /dev/null
+++ b/application/basilisk/components/newtab/NewTabURL.jsm
@@ -0,0 +1,36 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+/* globals XPCOMUtils, aboutNewTabService*/
+/* exported NewTabURL */
+
+"use strict";
+
+const {utils: Cu} = Components;
+
+this.EXPORTED_SYMBOLS = ["NewTabURL"];
+
+Cu.import("resource://gre/modules/XPCOMUtils.jsm");
+XPCOMUtils.defineLazyServiceGetter(this, "aboutNewTabService",
+ "@mozilla.org/browser/aboutnewtab-service;1",
+ "nsIAboutNewTabService");
+
+this.NewTabURL = {
+
+ get: function() {
+ return aboutNewTabService.newTabURL;
+ },
+
+ get overridden() {
+ return aboutNewTabService.overridden;
+ },
+
+ override: function(newURL) {
+ aboutNewTabService.newTabURL = newURL;
+ },
+
+ reset: function() {
+ aboutNewTabService.resetNewTabURL();
+ }
+};
diff --git a/application/basilisk/components/newtab/NewTabWebChannel.jsm b/application/basilisk/components/newtab/NewTabWebChannel.jsm
new file mode 100644
index 000000000..40ee73684
--- /dev/null
+++ b/application/basilisk/components/newtab/NewTabWebChannel.jsm
@@ -0,0 +1,299 @@
+/* global
+ NewTabPrefsProvider,
+ Services,
+ EventEmitter,
+ Preferences,
+ XPCOMUtils,
+ WebChannel,
+ NewTabRemoteResources
+*/
+/* exported NewTabWebChannel */
+
+"use strict";
+
+this.EXPORTED_SYMBOLS = ["NewTabWebChannel"];
+
+const {utils: Cu} = Components;
+Cu.import("resource://gre/modules/XPCOMUtils.jsm");
+Cu.import("resource://gre/modules/Services.jsm");
+Cu.import("resource://gre/modules/Preferences.jsm");
+
+XPCOMUtils.defineLazyModuleGetter(this, "NewTabPrefsProvider",
+ "resource:///modules/NewTabPrefsProvider.jsm");
+XPCOMUtils.defineLazyModuleGetter(this, "NewTabRemoteResources",
+ "resource:///modules/NewTabRemoteResources.jsm");
+XPCOMUtils.defineLazyModuleGetter(this, "WebChannel",
+ "resource://gre/modules/WebChannel.jsm");
+XPCOMUtils.defineLazyGetter(this, "EventEmitter", function() {
+ const {EventEmitter} = Cu.import("resource://devtools/shared/event-emitter.js", {});
+ return EventEmitter;
+});
+
+const CHAN_ID = "newtab";
+const PREF_ENABLED = "browser.newtabpage.remote";
+const PREF_MODE = "browser.newtabpage.remote.mode";
+
+/**
+ * NewTabWebChannel is the conduit for all communication with unprivileged newtab instances.
+ *
+ * It allows for the ability to broadcast to all newtab browsers.
+ * If the browser.newtab.remote pref is false, the object will be in an uninitialized state.
+ *
+ * Mode choices:
+ * 'production': pages from our production CDN
+ * 'staging': pages from our staging CDN
+ * 'test': intended for tests
+ * 'test2': intended for tests
+ * 'dev': intended for development
+ *
+ * An unknown mode will result in 'production' mode, which is the default
+ *
+ * Incoming messages are expected to be JSON-serialized and in the format:
+ *
+ * {
+ * type: "REQUEST_SCREENSHOT",
+ * data: {
+ * url: "https://example.com"
+ * }
+ * }
+ *
+ * Or:
+ *
+ * {
+ * type: "REQUEST_SCREENSHOT",
+ * }
+ *
+ * Outgoing messages are expected to be objects serializable by structured cloning, in a similar format:
+ * {
+ * type: "RECEIVE_SCREENSHOT",
+ * data: {
+ * "url": "https://example.com",
+ * "image": "dataURi:....."
+ * }
+ * }
+ */
+let NewTabWebChannelImpl = function NewTabWebChannelImpl() {
+ EventEmitter.decorate(this);
+ this._handlePrefChange = this._handlePrefChange.bind(this);
+ this._incomingMessage = this._incomingMessage.bind(this);
+};
+
+NewTabWebChannelImpl.prototype = {
+ _prefs: {},
+ _channel: null,
+
+ // a WeakMap containing browsers as keys and a weak ref to their principal
+ // as value
+ _principals: null,
+
+ // a Set containing weak refs to browsers
+ _browsers: null,
+
+ /*
+ * Returns current channel's ID
+ */
+ get chanId() {
+ return CHAN_ID;
+ },
+
+ /*
+ * Returns the number of browsers currently tracking
+ */
+ get numBrowsers() {
+ return this._getBrowserRefs().length;
+ },
+
+ /*
+ * Returns current channel's origin
+ */
+ get origin() {
+ if (!(this._prefs.mode in NewTabRemoteResources.MODE_CHANNEL_MAP)) {
+ this._prefs.mode = "production";
+ }
+ return NewTabRemoteResources.MODE_CHANNEL_MAP[this._prefs.mode].origin;
+ },
+
+ /*
+ * Unloads all browsers and principals
+ */
+ _unloadAll() {
+ if (this._principals != null) {
+ this._principals = new WeakMap();
+ }
+ this._browsers = new Set();
+ this.emit("targetUnloadAll");
+ },
+
+ /*
+ * Checks if a browser is known
+ *
+ * This will cause an iteration through all known browsers.
+ * That's ok, we don't expect a lot of browsers
+ */
+ _isBrowserKnown(browser) {
+ for (let bRef of this._getBrowserRefs()) {
+ let b = bRef.get();
+ if (b && b.permanentKey === browser.permanentKey) {
+ return true;
+ }
+ }
+
+ return false;
+ },
+
+ /*
+ * Obtains all known browser refs
+ */
+ _getBrowserRefs() {
+ // Some code may try to emit messages after teardown.
+ if (!this._browsers) {
+ return [];
+ }
+ let refs = [];
+ for (let bRef of this._browsers) {
+ /*
+ * even though we hold a weak ref to browser, it seems that browser
+ * objects aren't gc'd immediately after a tab closes. They stick around
+ * in memory, but thankfully they don't have a documentURI in that case
+ */
+ let browser = bRef.get();
+ if (browser && browser.documentURI) {
+ refs.push(bRef);
+ } else {
+ // need to clean up principals because the browser object is not gc'ed
+ // immediately
+ this._principals.delete(browser);
+ this._browsers.delete(bRef);
+ this.emit("targetUnload");
+ }
+ }
+ return refs;
+ },
+
+ /*
+ * Receives a message from content.
+ *
+ * Keeps track of browsers for broadcast, relays messages to listeners.
+ */
+ _incomingMessage(id, message, target) {
+ if (this.chanId !== id) {
+ Cu.reportError(new Error("NewTabWebChannel unexpected message destination"));
+ }
+
+ /*
+ * need to differentiate by browser, because event targets are created each
+ * time a message is sent.
+ */
+ if (!this._isBrowserKnown(target.browser)) {
+ this._browsers.add(Cu.getWeakReference(target.browser));
+ this._principals.set(target.browser, Cu.getWeakReference(target.principal));
+ this.emit("targetAdd");
+ }
+
+ try {
+ let msg = JSON.parse(message);
+ this.emit(msg.type, {data: msg.data, target: target});
+ } catch (err) {
+ Cu.reportError(err);
+ }
+ },
+
+ /*
+ * Sends a message to all known browsers
+ */
+ broadcast(actionType, message) {
+ for (let bRef of this._getBrowserRefs()) {
+ let browser = bRef.get();
+ try {
+ let principal = this._principals.get(browser).get();
+ if (principal && browser && browser.documentURI) {
+ this._channel.send({type: actionType, data: message}, {browser, principal});
+ }
+ } catch (e) {
+ Cu.reportError(new Error("NewTabWebChannel WeakRef is dead"));
+ this._principals.delete(browser);
+ }
+ }
+ },
+
+ /*
+ * Sends a message to a specific target
+ */
+ send(actionType, message, target) {
+ try {
+ this._channel.send({type: actionType, data: message}, target);
+ } catch (e) {
+ // Web Channel might be dead
+ Cu.reportError(e);
+ }
+ },
+
+ /*
+ * Pref change observer callback
+ */
+ _handlePrefChange(prefName, newState, forceState) { // eslint-disable-line no-unused-vars
+ switch (prefName) {
+ case PREF_ENABLED:
+ if (!this._prefs.enabled && newState) {
+ // changing state from disabled to enabled
+ this.setupState();
+ } else if (this._prefs.enabled && !newState) {
+ // changing state from enabled to disabled
+ this.tearDownState();
+ }
+ break;
+ case PREF_MODE:
+ if (this._prefs.mode !== newState) {
+ // changing modes
+ this.tearDownState();
+ this.setupState();
+ }
+ break;
+ }
+ },
+
+ /*
+ * Sets up the internal state
+ */
+ setupState() {
+ this._prefs.enabled = Preferences.get(PREF_ENABLED, false);
+
+ let mode = Preferences.get(PREF_MODE, "production");
+ if (!(mode in NewTabRemoteResources.MODE_CHANNEL_MAP)) {
+ mode = "production";
+ }
+ this._prefs.mode = mode;
+ this._principals = new WeakMap();
+ this._browsers = new Set();
+
+ if (this._prefs.enabled) {
+ this._channel = new WebChannel(this.chanId, Services.io.newURI(this.origin, null, null));
+ this._channel.listen(this._incomingMessage);
+ }
+ },
+
+ tearDownState() {
+ if (this._channel) {
+ this._channel.stopListening();
+ }
+ this._prefs = {};
+ this._unloadAll();
+ this._channel = null;
+ this._principals = null;
+ this._browsers = null;
+ },
+
+ init() {
+ this.setupState();
+ NewTabPrefsProvider.prefs.on(PREF_ENABLED, this._handlePrefChange);
+ NewTabPrefsProvider.prefs.on(PREF_MODE, this._handlePrefChange);
+ },
+
+ uninit() {
+ this.tearDownState();
+ NewTabPrefsProvider.prefs.off(PREF_ENABLED, this._handlePrefChange);
+ NewTabPrefsProvider.prefs.off(PREF_MODE, this._handlePrefChange);
+ }
+};
+
+let NewTabWebChannel = new NewTabWebChannelImpl();
diff --git a/application/basilisk/components/newtab/PlacesProvider.jsm b/application/basilisk/components/newtab/PlacesProvider.jsm
new file mode 100644
index 000000000..f478b5c5c
--- /dev/null
+++ b/application/basilisk/components/newtab/PlacesProvider.jsm
@@ -0,0 +1,211 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+/* global XPCOMUtils, Services, PlacesUtils, EventEmitter */
+/* global gLinks */
+/* exported PlacesProvider */
+
+"use strict";
+
+this.EXPORTED_SYMBOLS = ["PlacesProvider"];
+
+const {interfaces: Ci, utils: Cu} = Components;
+Cu.import("resource://gre/modules/Services.jsm");
+Cu.import("resource://gre/modules/XPCOMUtils.jsm");
+
+XPCOMUtils.defineLazyModuleGetter(this, "PlacesUtils",
+ "resource://gre/modules/PlacesUtils.jsm");
+
+XPCOMUtils.defineLazyGetter(this, "EventEmitter", function() {
+ const {EventEmitter} = Cu.import("resource://devtools/shared/event-emitter.js", {});
+ return EventEmitter;
+});
+
+XPCOMUtils.defineLazyModuleGetter(this, "Task",
+ "resource://gre/modules/Task.jsm");
+XPCOMUtils.defineLazyModuleGetter(this, "NewTabUtils",
+ "resource://gre/modules/NewTabUtils.jsm");
+
+// The maximum number of results PlacesProvider retrieves from history.
+const HISTORY_RESULTS_LIMIT = 100;
+
+/* Queries history to retrieve the most visited sites. Emits events when the
+ * history changes.
+ * Implements the EventEmitter interface.
+ */
+let Links = function Links() {
+ EventEmitter.decorate(this);
+};
+
+Links.prototype = {
+ /**
+ * Set this to change the maximum number of links the provider will provide.
+ */
+ get maxNumLinks() {
+ // getter, so it can't be replaced dynamically
+ return HISTORY_RESULTS_LIMIT;
+ },
+
+ /**
+ * A set of functions called by @mozilla.org/browser/nav-historyservice
+ * All history events are emitted from this object.
+ */
+ historyObserver: {
+ onDeleteURI: function historyObserver_onDeleteURI(aURI) {
+ // let observers remove sensetive data associated with deleted visit
+ gLinks.emit("deleteURI", {
+ url: aURI.spec,
+ });
+ },
+
+ onClearHistory: function historyObserver_onClearHistory() {
+ gLinks.emit("clearHistory");
+ },
+
+ onFrecencyChanged: function historyObserver_onFrecencyChanged(aURI,
+ aNewFrecency, aGUID, aHidden, aLastVisitDate) { // jshint ignore:line
+ // The implementation of the query in getLinks excludes hidden and
+ // unvisited pages, so it's important to exclude them here, too.
+ if (!aHidden && aLastVisitDate &&
+ NewTabUtils.linkChecker.checkLoadURI(aURI.spec)) {
+ gLinks.emit("linkChanged", {
+ url: aURI.spec,
+ frecency: aNewFrecency,
+ lastVisitDate: aLastVisitDate,
+ type: "history",
+ });
+ }
+ },
+
+ onManyFrecenciesChanged: function historyObserver_onManyFrecenciesChanged() {
+ // Called when frecencies are invalidated and also when clearHistory is called
+ // See toolkit/components/places/tests/unit/test_frecency_observers.js
+ gLinks.emit("manyLinksChanged");
+ },
+
+ onTitleChanged: function historyObserver_onTitleChanged(aURI, aNewTitle) {
+ if (NewTabUtils.linkChecker.checkLoadURI(aURI.spec)) {
+ gLinks.emit("linkChanged", {
+ url: aURI.spec,
+ title: aNewTitle
+ });
+ }
+ },
+
+ QueryInterface: XPCOMUtils.generateQI([Ci.nsINavHistoryObserver,
+ Ci.nsISupportsWeakReference])
+ },
+
+ /**
+ * Must be called before the provider is used.
+ * Makes it easy to disable under pref
+ */
+ init: function PlacesProvider_init() {
+ try {
+ PlacesUtils.history.addObserver(this.historyObserver, true);
+ } catch (e) {
+ Cu.reportError(e);
+ }
+ },
+
+ /**
+ * Gets the current set of links delivered by this provider.
+ *
+ * @returns {Promise} Returns a promise with the array of links as payload.
+ */
+ getLinks: Task.async(function*() {
+ // Select a single page per host with highest frecency, highest recency.
+ // Choose N top such pages. Note +rev_host, to turn off optimizer per :mak
+ // suggestion.
+ let sqlQuery = `SELECT url, title, frecency,
+ last_visit_date as lastVisitDate,
+ "history" as type
+ FROM moz_places
+ WHERE frecency in (
+ SELECT MAX(frecency) as frecency
+ FROM moz_places
+ WHERE hidden = 0 AND last_visit_date NOTNULL
+ GROUP BY +rev_host
+ ORDER BY frecency DESC
+ LIMIT :limit
+ )
+ GROUP BY rev_host HAVING MAX(lastVisitDate)
+ ORDER BY frecency DESC, lastVisitDate DESC, url`;
+
+ let links = yield this.executePlacesQuery(sqlQuery, {
+ columns: ["url", "title", "lastVisitDate", "frecency", "type"],
+ params: {limit: this.maxNumLinks}
+ });
+
+ return links.filter(link => NewTabUtils.linkChecker.checkLoadURI(link.url));
+ }),
+
+ /**
+ * Executes arbitrary query against places database
+ *
+ * @param {String} aSql
+ * SQL query to execute
+ * @param {Object} [optional] aOptions
+ * aOptions.columns - an array of column names. if supplied the returned
+ * items will consist of objects keyed on column names. Otherwise
+ * an array of raw values is returned in the select order
+ * aOptions.param - an object of SQL binding parameters
+ * aOptions.callback - a callback to handle query rows
+ *
+ * @returns {Promise} Returns a promise with the array of retrieved items
+ */
+ executePlacesQuery: Task.async(function*(aSql, aOptions={}) {
+ let {columns, params, callback} = aOptions;
+ let items = [];
+ let queryError = null;
+ let conn = yield PlacesUtils.promiseDBConnection();
+ yield conn.executeCached(aSql, params, aRow => {
+ try {
+ // check if caller wants to handle query raws
+ if (callback) {
+ callback(aRow);
+ }
+ // otherwise fill in the item and add items array
+ else {
+ let item = null;
+ // if columns array is given construct an object
+ if (columns && Array.isArray(columns)) {
+ item = {};
+ columns.forEach(column => {
+ item[column] = aRow.getResultByName(column);
+ });
+ } else {
+ // if no columns - make an array of raw values
+ item = [];
+ for (let i = 0; i < aRow.numEntries; i++) {
+ item.push(aRow.getResultByIndex(i));
+ }
+ }
+ items.push(item);
+ }
+ } catch (e) {
+ queryError = e;
+ throw StopIteration;
+ }
+ });
+ if (queryError) {
+ throw new Error(queryError);
+ }
+ return items;
+ }),
+};
+
+/**
+ * Singleton that serves as the default link provider for the grid.
+ */
+const gLinks = new Links(); // jshint ignore:line
+
+let PlacesProvider = {
+ links: gLinks,
+};
+
+// Kept only for backwards-compatibility
+XPCOMUtils.defineLazyGetter(PlacesProvider, "LinkChecker",
+ () => NewTabUtils.linkChecker);
+
diff --git a/application/basilisk/components/newtab/PreviewProvider.jsm b/application/basilisk/components/newtab/PreviewProvider.jsm
new file mode 100644
index 000000000..8624b8544
--- /dev/null
+++ b/application/basilisk/components/newtab/PreviewProvider.jsm
@@ -0,0 +1,49 @@
+/* global XPCOMUtils, BackgroundPageThumbs, FileUtils, PageThumbsStorage, Task, MIMEService */
+/* exported PreviewProvider */
+
+"use strict";
+
+this.EXPORTED_SYMBOLS = ["PreviewProvider"];
+
+const {utils: Cu} = Components;
+Cu.import("resource://gre/modules/XPCOMUtils.jsm");
+Cu.import("resource://gre/modules/Task.jsm");
+Cu.import("resource://gre/modules/PageThumbs.jsm");
+Cu.import("resource://gre/modules/FileUtils.jsm");
+const {OS} = Cu.import("resource://gre/modules/osfile.jsm");
+
+XPCOMUtils.defineLazyModuleGetter(this, "BackgroundPageThumbs",
+ "resource://gre/modules/BackgroundPageThumbs.jsm");
+XPCOMUtils.defineLazyServiceGetter(this, "MIMEService",
+ "@mozilla.org/mime;1", "nsIMIMEService");
+
+let PreviewProvider = {
+ /**
+ * Returns a thumbnail as a data URI for a url, creating it if necessary
+ *
+ * @param {String} url
+ * a url to obtain a thumbnail for
+ * @return {Promise} A Promise that resolves with a base64 encoded thumbnail
+ */
+ getThumbnail: Task.async(function* PreviewProvider_getThumbnail(url) {
+ try {
+ yield BackgroundPageThumbs.captureIfMissing(url);
+ let imgPath = PageThumbsStorage.getFilePathForURL(url);
+
+ // OS.File object used to easily read off-thread
+ let file = yield OS.File.open(imgPath, {read: true, existing: true});
+
+ // nsIFile object needed for MIMEService
+ let nsFile = FileUtils.File(imgPath);
+
+ let contentType = MIMEService.getTypeFromFile(nsFile);
+ let bytes = yield file.read();
+ let encodedData = btoa(String.fromCharCode.apply(null, bytes));
+ file.close();
+ return `data:${contentType};base64,${encodedData}`;
+ } catch (err) {
+ Cu.reportError(`PreviewProvider_getThumbnail error: ${err}`);
+ throw err;
+ }
+ })
+};
diff --git a/application/basilisk/components/newtab/aboutNewTabService.js b/application/basilisk/components/newtab/aboutNewTabService.js
new file mode 100644
index 000000000..54c3749e8
--- /dev/null
+++ b/application/basilisk/components/newtab/aboutNewTabService.js
@@ -0,0 +1,289 @@
+/*
+ * This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/.
+*/
+
+/* globals XPCOMUtils, NewTabPrefsProvider, Services,
+ Locale, UpdateUtils, NewTabRemoteResources
+*/
+"use strict";
+
+const {utils: Cu, interfaces: Ci} = Components;
+
+Cu.import("resource://gre/modules/XPCOMUtils.jsm");
+Cu.import("resource://gre/modules/Services.jsm");
+
+XPCOMUtils.defineLazyModuleGetter(this, "UpdateUtils",
+ "resource://gre/modules/UpdateUtils.jsm");
+XPCOMUtils.defineLazyModuleGetter(this, "NewTabPrefsProvider",
+ "resource:///modules/NewTabPrefsProvider.jsm");
+XPCOMUtils.defineLazyModuleGetter(this, "Locale",
+ "resource://gre/modules/Locale.jsm");
+XPCOMUtils.defineLazyModuleGetter(this, "NewTabRemoteResources",
+ "resource:///modules/NewTabRemoteResources.jsm");
+
+const LOCAL_NEWTAB_URL = "chrome://browser/content/newtab/newTab.xhtml";
+
+const REMOTE_NEWTAB_PATH = "/newtab/v%VERSION%/%CHANNEL%/%LOCALE%/index.html";
+
+const ABOUT_URL = "about:newtab";
+
+// Pref that tells if remote newtab is enabled
+const PREF_REMOTE_ENABLED = "browser.newtabpage.remote";
+
+// Pref branch necesssary for testing
+const PREF_REMOTE_CS_TEST = "browser.newtabpage.remote.content-signing-test";
+
+// The preference that tells whether to match the OS locale
+const PREF_MATCH_OS_LOCALE = "intl.locale.matchOS";
+
+// The preference that tells what locale the user selected
+const PREF_SELECTED_LOCALE = "general.useragent.locale";
+
+// The preference that tells what remote mode is enabled.
+const PREF_REMOTE_MODE = "browser.newtabpage.remote.mode";
+
+// The preference that tells which remote version is expected.
+const PREF_REMOTE_VERSION = "browser.newtabpage.remote.version";
+
+const VALID_CHANNELS = new Set(["esr", "release", "beta", "aurora", "nightly"]);
+
+function AboutNewTabService() {
+ NewTabPrefsProvider.prefs.on(PREF_REMOTE_ENABLED, this._handleToggleEvent.bind(this));
+
+ this._updateRemoteMaybe = this._updateRemoteMaybe.bind(this);
+
+ // trigger remote change if needed, according to pref
+ this.toggleRemote(Services.prefs.getBoolPref(PREF_REMOTE_ENABLED));
+}
+
+/*
+ * A service that allows for the overriding, at runtime, of the newtab page's url.
+ * Additionally, the service manages pref state between a remote and local newtab page.
+ *
+ * There is tight coupling with browser/about/AboutRedirector.cpp.
+ *
+ * 1. Browser chrome access:
+ *
+ * When the user issues a command to open a new tab page, usually clicking a button
+ * in the browser chrome or using shortcut keys, the browser chrome code invokes the
+ * service to obtain the newtab URL. It then loads that URL in a new tab.
+ *
+ * When not overridden, the default URL emitted by the service is "about:newtab".
+ * When overridden, it returns the overriden URL.
+ *
+ * 2. Redirector Access:
+ *
+ * When the URL loaded is about:newtab, the default behavior, or when entered in the
+ * URL bar, the redirector is hit. The service is then called to return either of
+ * two URLs, a chrome or remote one, based on the browser.newtabpage.remote pref.
+ *
+ * NOTE: "about:newtab" will always result in a default newtab page, and never an overridden URL.
+ *
+ * Access patterns:
+ *
+ * The behavior is different when accessing the service via browser chrome or via redirector
+ * largely to maintain compatibility with expectations of add-on developers.
+ *
+ * Loading a chrome resource, or an about: URL in the redirector with either the
+ * LOAD_NORMAL or LOAD_REPLACE flags yield unexpected behaviors, so a roundtrip
+ * to the redirector from browser chrome is avoided.
+ */
+AboutNewTabService.prototype = {
+
+ _newTabURL: ABOUT_URL,
+ _remoteEnabled: false,
+ _remoteURL: null,
+ _overridden: false,
+
+ classID: Components.ID("{dfcd2adc-7867-4d3a-ba70-17501f208142}"),
+ QueryInterface: XPCOMUtils.generateQI([Ci.nsIAboutNewTabService]),
+ _xpcom_categories: [{
+ service: true
+ }],
+
+ _handleToggleEvent(prefName, stateEnabled, forceState) { // jshint unused:false
+ if (this.toggleRemote(stateEnabled, forceState)) {
+ Services.obs.notifyObservers(null, "newtab-url-changed", ABOUT_URL);
+ }
+ },
+
+ /**
+ * React to changes to the remote newtab pref.
+ *
+ * If browser.newtabpage.remote is true, this will change the default URL to the
+ * remote newtab page URL. If browser.newtabpage.remote is false, the default URL
+ * will be a local chrome URL.
+ *
+ * This will only act if there is a change of state and if not overridden.
+ *
+ * @returns {Boolean} Returns if there has been a state change
+ *
+ * @param {Boolean} stateEnabled remote state to set to
+ * @param {Boolean} forceState force state change
+ */
+ toggleRemote(stateEnabled, forceState) {
+
+ if (!forceState && (this._overriden || stateEnabled === this._remoteEnabled)) {
+ // exit there is no change of state
+ return false;
+ }
+
+ let csTest = Services.prefs.getBoolPref(PREF_REMOTE_CS_TEST);
+ if (stateEnabled) {
+ if (!csTest) {
+ this._remoteURL = this.generateRemoteURL();
+ } else {
+ this._remoteURL = this._newTabURL;
+ }
+ NewTabPrefsProvider.prefs.on(
+ PREF_SELECTED_LOCALE,
+ this._updateRemoteMaybe);
+ NewTabPrefsProvider.prefs.on(
+ PREF_MATCH_OS_LOCALE,
+ this._updateRemoteMaybe);
+ NewTabPrefsProvider.prefs.on(
+ PREF_REMOTE_MODE,
+ this._updateRemoteMaybe);
+ NewTabPrefsProvider.prefs.on(
+ PREF_REMOTE_VERSION,
+ this._updateRemoteMaybe);
+ this._remoteEnabled = true;
+ } else {
+ NewTabPrefsProvider.prefs.off(PREF_SELECTED_LOCALE, this._updateRemoteMaybe);
+ NewTabPrefsProvider.prefs.off(PREF_MATCH_OS_LOCALE, this._updateRemoteMaybe);
+ NewTabPrefsProvider.prefs.off(PREF_REMOTE_MODE, this._updateRemoteMaybe);
+ NewTabPrefsProvider.prefs.off(PREF_REMOTE_VERSION, this._updateRemoteMaybe);
+ this._remoteEnabled = false;
+ }
+ if (!csTest) {
+ this._newTabURL = ABOUT_URL;
+ }
+ return true;
+ },
+
+ /*
+ * Generate a default url based on remote mode, version, locale and update channel
+ */
+ generateRemoteURL() {
+ let releaseName = this.releaseFromUpdateChannel(UpdateUtils.UpdateChannel);
+ let path = REMOTE_NEWTAB_PATH
+ .replace("%VERSION%", this.remoteVersion)
+ .replace("%LOCALE%", Locale.getLocale())
+ .replace("%CHANNEL%", releaseName);
+ let mode = Services.prefs.getCharPref(PREF_REMOTE_MODE, "production");
+ if (!(mode in NewTabRemoteResources.MODE_CHANNEL_MAP)) {
+ mode = "production";
+ }
+ return NewTabRemoteResources.MODE_CHANNEL_MAP[mode].origin + path;
+ },
+
+ /*
+ * Returns the default URL.
+ *
+ * This URL only depends on the browser.newtabpage.remote pref. Overriding
+ * the newtab page has no effect on the result of this function.
+ *
+ * The result is also the remote URL if this is in a test (PREF_REMOTE_CS_TEST)
+ *
+ * @returns {String} the default newtab URL, remote or local depending on browser.newtabpage.remote
+ */
+ get defaultURL() {
+ let csTest = Services.prefs.getBoolPref(PREF_REMOTE_CS_TEST);
+ if (this._remoteEnabled || csTest) {
+ return this._remoteURL;
+ }
+ return LOCAL_NEWTAB_URL;
+ },
+
+ /*
+ * Updates the remote location when the page is not overriden.
+ *
+ * Useful when there is a dependent pref change
+ */
+ _updateRemoteMaybe() {
+ if (!this._remoteEnabled || this._overridden) {
+ return;
+ }
+
+ let url = this.generateRemoteURL();
+ if (url !== this._remoteURL) {
+ this._remoteURL = url;
+ Services.obs.notifyObservers(null, "newtab-url-changed",
+ this._remoteURL);
+ }
+ },
+
+ /**
+ * Returns the release name from an Update Channel name
+ *
+ * @returns {String} a release name based on the update channel. Defaults to nightly
+ */
+ releaseFromUpdateChannel(channelName) {
+ return VALID_CHANNELS.has(channelName) ? channelName : "nightly";
+ },
+
+ get newTabURL() {
+ return this._newTabURL;
+ },
+
+ get remoteVersion() {
+ return Services.prefs.getCharPref(PREF_REMOTE_VERSION, "1");
+ },
+
+ get remoteReleaseName() {
+ return this.releaseFromUpdateChannel(UpdateUtils.UpdateChannel);
+ },
+
+ set newTabURL(aNewTabURL) {
+ let csTest = Services.prefs.getBoolPref(PREF_REMOTE_CS_TEST);
+ aNewTabURL = aNewTabURL.trim();
+ if (aNewTabURL === ABOUT_URL) {
+ // avoid infinite redirects in case one sets the URL to about:newtab
+ this.resetNewTabURL();
+ return;
+ } else if (aNewTabURL === "") {
+ aNewTabURL = "about:blank";
+ }
+ let remoteURL = this.generateRemoteURL();
+ let prefRemoteEnabled = Services.prefs.getBoolPref(PREF_REMOTE_ENABLED);
+ let isResetLocal = !prefRemoteEnabled && aNewTabURL === LOCAL_NEWTAB_URL;
+ let isResetRemote = prefRemoteEnabled && aNewTabURL === remoteURL;
+
+ if (isResetLocal || isResetRemote) {
+ if (this._overriden && !csTest) {
+ // only trigger a reset if previously overridden and this is no test
+ this.resetNewTabURL();
+ }
+ return;
+ }
+ // turn off remote state if needed
+ if (!csTest) {
+ this.toggleRemote(false);
+ } else {
+ // if this is a test, we want the remoteURL to be set
+ this._remoteURL = aNewTabURL;
+ }
+ this._newTabURL = aNewTabURL;
+ this._overridden = true;
+ Services.obs.notifyObservers(null, "newtab-url-changed", this._newTabURL);
+ },
+
+ get overridden() {
+ return this._overridden;
+ },
+
+ get remoteEnabled() {
+ return this._remoteEnabled;
+ },
+
+ resetNewTabURL() {
+ this._overridden = false;
+ this._newTabURL = ABOUT_URL;
+ this.toggleRemote(Services.prefs.getBoolPref(PREF_REMOTE_ENABLED), true);
+ Services.obs.notifyObservers(null, "newtab-url-changed", this._newTabURL);
+ }
+};
+
+this.NSGetFactory = XPCOMUtils.generateNSGetFactory([AboutNewTabService]);
diff --git a/application/basilisk/components/newtab/moz.build b/application/basilisk/components/newtab/moz.build
new file mode 100644
index 000000000..3d3be6454
--- /dev/null
+++ b/application/basilisk/components/newtab/moz.build
@@ -0,0 +1,27 @@
+# -*- Mode: python; indent-tabs-mode: nil; tab-width: 40 -*-
+# vim: set filetype=python:
+# This Source Code Form is subject to the terms of the Mozilla Public
+# License, v. 2.0. If a copy of the MPL was not distributed with this
+# file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+EXTRA_JS_MODULES += [
+ 'NewTabMessages.jsm',
+ 'NewTabPrefsProvider.jsm',
+ 'NewTabRemoteResources.jsm',
+ 'NewTabSearchProvider.jsm',
+ 'NewTabURL.jsm',
+ 'NewTabWebChannel.jsm',
+ 'PlacesProvider.jsm',
+ 'PreviewProvider.jsm'
+]
+
+XPIDL_SOURCES += [
+ 'nsIAboutNewTabService.idl',
+]
+
+XPIDL_MODULE = 'browser-newtab'
+
+EXTRA_COMPONENTS += [
+ 'aboutNewTabService.js',
+ 'NewTabComponents.manifest',
+]
diff --git a/application/basilisk/components/newtab/nsIAboutNewTabService.idl b/application/basilisk/components/newtab/nsIAboutNewTabService.idl
new file mode 100644
index 000000000..bc25c7492
--- /dev/null
+++ b/application/basilisk/components/newtab/nsIAboutNewTabService.idl
@@ -0,0 +1,63 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include "nsISupports.idl"
+
+/**
+ * Allows to override about:newtab to point to a different location
+ * than the one specified within AboutRedirector.cpp
+ */
+
+[scriptable, uuid(dfcd2adc-7867-4d3a-ba70-17501f208142)]
+interface nsIAboutNewTabService : nsISupports
+{
+ /**
+ * Returns the url of the resource for the newtab page if not overridden,
+ * otherwise a string represenation of the new URL.
+ */
+ attribute ACString newTabURL;
+
+ /**
+ * Returns the default URL (remote or local depending on pref)
+ */
+ attribute ACString defaultURL;
+
+ /**
+ * Returns true if the default resource got overridden.
+ */
+ readonly attribute bool overridden;
+
+ /**
+ * Returns true if the default resource is remotely hosted and isn't
+ * overridden
+ */
+ readonly attribute bool remoteEnabled;
+
+
+ /**
+ * Returns the version of the remote newtab page expected
+ */
+ readonly attribute ACString remoteVersion;
+
+ /**
+ * Returns the expected channel for the remote the newtab page
+ */
+ readonly attribute ACString remoteReleaseName;
+
+ /**
+ * Generates and returns the remote newtab page url
+ */
+ ACString generateRemoteURL();
+
+ /**
+ * Returns a remote new tab release name given an update channel name
+ */
+ ACString releaseFromUpdateChannel(in ACString channelName);
+
+ /**
+ * Resets to the default resource and also resets the
+ * overridden attribute to false.
+ */
+ void resetNewTabURL();
+};