forked from aminomancer/uc.css.js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
aboutUserChrome.sys.mjs
388 lines (356 loc) · 12.5 KB
/
aboutUserChrome.sys.mjs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
// ==UserScript==
// @name about:userchrome
// @version 1.1.6
// @author aminomancer
// @homepageURL https://github.com/aminomancer/uc.css.js
// @long-description
// @description
/*
A manager for your userscripts. This allows you to automatically update scripts that include an updateURL or downloadURL field in their script metadata. Requires the content in [resources/aboutuserchrome][] to function. Visit about:userchrome to get started.
[resources/aboutuserchrome]: https://github.com/aminomancer/uc.css.js/tree/master/resources/aboutuserchrome
*/
// @downloadURL https://cdn.jsdelivr.net/gh/aminomancer/uc.css.js@master/JS/aboutUserChrome.sys.mjs
// @updateURL https://cdn.jsdelivr.net/gh/aminomancer/uc.css.js@master/JS/aboutUserChrome.sys.mjs
// @license This Source Code Form is subject to the terms of the Creative Commons Attribution-NonCommercial-ShareAlike International License, v. 4.0. If a copy of the CC BY-NC-SA 4.0 was not distributed with this file, You can obtain one at http://creativecommons.org/licenses/by-nc-sa/4.0/ or send a letter to Creative Commons, PO Box 1866, Mountain View, CA 94042, USA.
// ==/UserScript==
import { XPCOMUtils } from "resource://gre/modules/XPCOMUtils.sys.mjs";
const lazy = {};
try {
ChromeUtils.defineESModuleGetters(lazy, {
AppMenuNotifications: "resource://gre/modules/AppMenuNotifications.sys.mjs",
gScriptUpdater:
"chrome://userchrome/content/aboutuserchrome/modules/UCMSingletonData.sys.mjs",
PREF_NOTIFICATIONS_ENABLED:
"chrome://userchrome/content/aboutuserchrome/modules/UCMSingletonData.sys.mjs",
UPDATE_CHANGED_TOPIC:
"chrome://userchrome/content/aboutuserchrome/modules/UCMSingletonData.sys.mjs",
});
XPCOMUtils.defineLazyModuleGetters(lazy, {
EveryWindow: "resource:///modules/EveryWindow.jsm",
});
} catch (error) {
console.error(error);
}
const registrar = Components.manager.QueryInterface(Ci.nsIComponentRegistrar);
const chromeRegistry = Cc["@mozilla.org/chrome/chrome-registry;1"].getService(
Ci.nsIChromeRegistry
);
const fphs = Cc["@mozilla.org/network/protocol;1?name=file"].getService(
Ci.nsIFileProtocolHandler
);
function findResources() {
let url = "chrome://userchrome/content/aboutuserchrome/aboutuserchrome.html";
let uri = Services.io.newURI(url);
let fileUri = chromeRegistry.convertChromeURL(uri);
let file = fphs.getFileFromURLSpec(fileUri.spec).QueryInterface(Ci.nsIFile);
if (file.exists()) return url;
// eslint-disable-next-line no-console
console.warn(
`about:userchrome source files not found.
Please download them from https://github.com/aminomancer/uc.css.js/tree/master/resources/aboutuserchrome`
);
return false;
}
function generateFreeCID() {
let uuid = Components.ID(Services.uuid.generateUUID().toString());
while (registrar.isCIDRegistered(uuid)) {
uuid = Components.ID(Services.uuid.generateUUID().toString());
}
return uuid;
}
function AboutUserChrome() {}
let urlString = findResources();
AboutUserChrome.prototype = {
get uri() {
if (!urlString) return null;
return this._uri || (this._uri = Services.io.newURI(urlString));
},
newChannel(_uri, loadInfo) {
const ch = Services.io.newChannelFromURIWithLoadInfo(this.uri, loadInfo);
ch.owner = Services.scriptSecurityManager.getSystemPrincipal();
return ch;
},
getURIFlags(_uri) {
return (
Ci.nsIAboutModule.ALLOW_SCRIPT | Ci.nsIAboutModule.IS_SECURE_CHROME_UI
);
},
getChromeURI(_uri) {
return this.uri;
},
QueryInterface: ChromeUtils.generateQI(["nsIAboutModule"]),
};
var AboutModuleFactory = {
createInstance(aIID) {
return new AboutUserChrome().QueryInterface(aIID);
},
QueryInterface: ChromeUtils.generateQI(["nsIFactory"]),
};
if (urlString) {
// Register the about:userchrome page.
registrar.registerFactory(
generateFreeCID(),
"about:userchrome",
"@mozilla.org/network/protocol/about;1?what=userchrome",
AboutModuleFactory
);
}
function initUserChromeNotifications() {
let gUserChromeNotifications;
let gStylesheet;
try {
let sss = Cc["@mozilla.org/content/style-sheet-service;1"].getService(
Ci.nsIStyleSheetService
);
gStylesheet = sss.preloadSheet(
Services.io.newURI(
"chrome://userchrome/content/aboutuserchrome/chrome/userchrome-notifications.css"
),
sss.AUTHOR_SHEET
);
} catch (error) {
console.error(`Failed to load aboutUserChrome stylesheet: ${error.name}`); // eslint-disable-line no-console
}
/** Per-window class to handle app menu banners. */
class UserChromeWindowNotifications {
/** @param {Window} win chrome window */
constructor(win) {
this.win = win;
if (!win._ucUtils) return;
this.utils = win._ucUtils;
if (win.gBrowserInit.delayedStartupFinished) this.#init();
else Services.obs.addObserver(this, "browser-delayed-startup-finished");
}
#init() {
if (this.#initialized) return;
if (!gUserChromeNotifications) {
gUserChromeNotifications = new UserChromeNotifications(this.utils);
}
Services.obs.addObserver(this, lazy.UPDATE_CHANGED_TOPIC);
try {
this.win.windowUtils.addSheet(
gStylesheet,
Ci.nsIDOMWindowUtils.AUTHOR_SHEET
);
} catch (error) {
// eslint-disable-next-line no-console
console.error(
`Failed to load aboutUserChrome stylesheet: ${error.name}`
);
}
this.#updateBanner();
this.#initialized = true;
}
uninit() {
Services.obs.removeObserver(this, "browser-delayed-startup-finished");
Services.obs.removeObserver(this, lazy.UPDATE_CHANGED_TOPIC);
}
observe(subject, topic, data) {
switch (topic) {
case lazy.UPDATE_CHANGED_TOPIC:
this.#updateBanner();
break;
case "browser-delayed-startup-finished":
Services.obs.removeObserver(this, topic);
this.#init();
break;
}
}
#updateBanner() {
let { notificationId } = gUserChromeNotifications;
if (notificationId) {
if (!this.#banner) {
let sibling = this.win.PanelMultiView.getViewNode(
this.win.document,
"appMenu-proton-update-banner"
);
let banner = sibling.ownerDocument.createXULElement("toolbarbutton");
banner.className = "panel-banner-item subviewbutton";
banner.id = "userChromeManager-notification";
banner.setAttribute("wrap", "true");
banner.setAttribute(
"oncommand",
`if (this.getAttribute("notificationid") === "script-updates-restart") {
setTimeout(() => _ucUtils.restart(true), 300);
PanelMultiView.forNode(this.closest("panelmultiview")).hidePopup();
} else {
switchToTabHavingURI("about:userchrome", true);
}
event.preventDefault();`
);
this.#setBannerAttributes(banner, notificationId);
sibling.after(banner);
this.#banner = banner;
} else {
this.#setBannerAttributes(this.#banner, notificationId);
}
} else if (this.#banner) {
this.#banner.remove();
this.#banner = null;
}
}
/**
* Set the banner text and notificationid attribute.
* @param {Element} banner The banner to update
* @param {string} notification The notification id to set
*/
#setBannerAttributes(banner, notification) {
if (banner.getAttribute("notificationid") === notification) return;
let text =
notification === "script-updates-available"
? "Script updates available"
: "Restart to update scripts";
banner.setAttribute("label", text);
banner.setAttribute("notificationid", notification);
}
#banner;
#initialized = false;
}
/** Singleton class to handle badge notifications. */
class UserChromeNotifications {
/**
* @param {Object} utils The _ucUtils object fx-autoconfig defines on each
* chrome window. This is used to get the script data and header parsing
* behavior. fx-autoconfig only exposes this to windows, so to use it from
* this module context we have to pass it in.
*/
constructor(utils) {
this.utils = utils;
Services.obs.addObserver(this, lazy.UPDATE_CHANGED_TOPIC);
utils.getScriptData().forEach(script => {
lazy.gScriptUpdater.getHandle(script).checkRemoteFile();
});
this.#updateBadge();
}
observe(subject, topic, data) {
if (topic === lazy.UPDATE_CHANGED_TOPIC) this.#updateBadge();
}
#updateBadge() {
let { notificationId } = this;
if (!notificationId) {
lazy.AppMenuNotifications.removeNotification(
"script-updates-available"
);
lazy.AppMenuNotifications.removeNotification("script-updates-restart");
} else if (notificationId === "script-updates-restart") {
lazy.AppMenuNotifications.removeNotification(
"script-updates-available"
);
lazy.AppMenuNotifications.showBadgeOnlyNotification(notificationId);
} else {
lazy.AppMenuNotifications.removeNotification("script-updates-restart");
lazy.AppMenuNotifications.showBadgeOnlyNotification(notificationId);
}
}
get notificationId() {
let { handles } = lazy.gScriptUpdater;
let updates = handles.filter(handle => {
if (!handle.remoteFile || handle.writing || handle.updateError) {
return false;
}
let remoteScriptData = this.utils.parseStringAsScriptInfo(
handle.filename,
handle.remoteFile
);
let newVersion = remoteScriptData.version;
return Services.vc.compare(newVersion, handle.currentVersion) > 0;
});
if (!updates.length) {
return null;
}
if (updates.every(handle => handle.pendingRestart)) {
return "script-updates-restart";
}
return "script-updates-available";
}
}
class UserChromeManagerEntryPoints {
constructor(win) {
this.win = win;
if (!win._ucUtils) return;
this.utils = win._ucUtils;
if (win.gBrowserInit.delayedStartupFinished) {
this.#init();
} else {
let delayedListener = (subject, topic) => {
if (
topic == "browser-delayed-startup-finished" &&
subject == this.win
) {
Services.obs.removeObserver(delayedListener, topic);
this.#init();
}
};
Services.obs.addObserver(
delayedListener,
"browser-delayed-startup-finished"
);
}
}
#init() {
if (this.#initialized) return;
this.#initialized = true;
this.#addHotkey();
this.#addMenuitem();
this.#addToolbarbutton();
}
#addMenuitem() {
let addonsItem = this.win.document.getElementById("menu_openAddons");
let item = this.utils.createElement(this.win.document, "menuitem", {
id: "menu_openUserChrome",
label: "UserChrome Manager",
accesskey: "U",
key: "key_openAboutUserchrome",
oncommand: `switchToTabHavingURI("about:userchrome", true)`,
});
addonsItem.after(item);
}
#addToolbarbutton() {
let addonsButton = this.win.PanelMultiView.getViewNode(
this.win.document,
"appMenu-extensions-themes-button"
);
let button = this.utils.createElement(
addonsButton.ownerDocument,
"toolbarbutton",
{
id: "appMenu-userChrome-button",
class: "subviewbutton",
label: "UserChrome Manager",
key: "key_openAboutUserchrome",
oncommand: `switchToTabHavingURI("about:userchrome", true)`,
}
);
addonsButton.after(button);
}
#addHotkey() {
this.utils.registerHotkey(
{ modifiers: "accel shift", key: "U", id: "key_openAboutUserchrome" },
win => {
if (win === this.win) {
this.win.switchToTabHavingURI("about:userchrome", true);
}
}
);
}
#initialized;
}
// Setup for each window.
lazy.EveryWindow.registerCallback(
"userChromeNotifications",
win => {
win.userChromeWindowNotifications = new UserChromeWindowNotifications(
win
);
new UserChromeManagerEntryPoints(win);
},
win => {
win.userChromeWindowNotifications.uninit();
}
);
}
const defaultPrefs = Services.prefs.getDefaultBranch("");
defaultPrefs.setBoolPref(lazy.PREF_NOTIFICATIONS_ENABLED, true);
if (Services.prefs.getBoolPref(lazy.PREF_NOTIFICATIONS_ENABLED, true)) {
initUserChromeNotifications();
}