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 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546
|
var stylishCommon = {
XULNS: "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul",
//compares CSS, taking into account platform differences
cssAreEqual: function(css1, css2) {
if (css1 == null && css2 == null) {
return true;
}
if (css1 == null || css2 == null) {
return false;
}
return css1.replace(/\s/g, "") == css2.replace(/\s/g, "");
},
domApplyAttributes: function(element, json) {
for (var i in json)
element.setAttribute(i, json[i]);
},
// CustomEvent is available in Firefox 11. Before that, the "data" parameter does nothing. If "data"
// is a custom object, __exposedProps__ must be set.
dispatchEvent: function(doc, type, data) {
if (!doc) {
return;
}
if (typeof data == "undefined") {
data = null;
}
var stylishEvent = null;
if (typeof doc.defaultView.CustomEvent != "undefined") {
stylishEvent = new doc.defaultView.CustomEvent(type, {detail: data});
} else {
stylishEvent = doc.createEvent("Events");
stylishEvent.initEvent(type, false, false, doc.defaultView, null);
}
doc.dispatchEvent(stylishEvent);
},
getAppName: function() {
var appInfo = Components.classes["@mozilla.org/xre/app-info;1"].getService(Components.interfaces.nsIXULAppInfo);
return appInfo.name;
},
isXULAvailable: Components.classes["@mozilla.org/xre/app-info;1"].getService(Components.interfaces.nsIXULRuntime).widgetToolkit.toLowerCase() != "android",
deleteWithPrompt: function(style) {
const STRINGS = document.getElementById("stylish-common-strings");
var title = STRINGS.getString("deleteStyleTitle");
var prompt = STRINGS.getFormattedString("deleteStyle", [style.name]);
var prompts = Components.classes["@mozilla.org/embedcomp/prompt-service;1"].getService(Components.interfaces.nsIPromptService);
if (prompts.confirmEx(window, title, prompt, prompts.BUTTON_POS_0 * prompts.BUTTON_TITLE_IS_STRING + prompts.BUTTON_POS_1 * prompts.BUTTON_TITLE_CANCEL, STRINGS.getString("deleteStyleOK"), null, null, null, {})) {
return false;
}
style.delete();
return true;
},
fixXHR: function(request) {
//only a problem on 1.9 toolkit
var appInfo = Components.classes["@mozilla.org/xre/app-info;1"].getService(Components.interfaces.nsIXULAppInfo);
var versionChecker = Components.classes["@mozilla.org/xpcom/version-comparator;1"].getService(Components.interfaces.nsIVersionComparator);
if (versionChecker.compare(appInfo.version, "1.9") >= 0 && versionChecker.compare(appInfo.version, "1.9.3a1pre") <= 0) {
//https://bugzilla.mozilla.org/show_bug.cgi?id=437174
var ds = Components.classes["@mozilla.org/webshell;1"].createInstance(Components.interfaces.nsIDocShellTreeItem).QueryInterface(Components.interfaces.nsIInterfaceRequestor);
ds.itemType = Components.interfaces.nsIDocShellTreeItem.typeContent;
request.channel.loadGroup = ds.getInterface(Components.interfaces.nsILoadGroup);
request.channel.loadFlags |= Components.interfaces.nsIChannel.LOAD_DOCUMENT_URI;
}
},
getWindowName: function(prefix, id) {
return (prefix + (id || Math.random())).replace(/\W/g, "");
},
clearAllMenuItems: function(event) {
var popup = event.target;
for (var i = popup.childNodes.length - 1; i >= 0; i--) {
var child = popup.childNodes[i];
if (child.getAttribute("stylish-dont-clear") != "true") {
popup.removeChild(child);
}
}
},
focusWindow: function(name) {
//if a window is already open, openDialog will clobber the changes made. check for an open window for this style and focus to it
var windowsMediator = Components.classes["@mozilla.org/appshell/window-mediator;1"].getService(Components.interfaces.nsIWindowMediator);
var win = windowsMediator.getMostRecentWindow(name);
if (win) {
win.focus();
return true;
}
return false;
},
openEdit: function(name, params) {
if (stylishCommon.focusWindow(name)) {
return;
}
params.windowType = name;
return openDialog("chrome://stylish/content/edit.xul", name, "chrome,resizable,dialog=no,centerscreen", params);
},
openEditForStyle: function(style) {
return stylishCommon.openEdit(stylishCommon.getWindowName("stylishEdit", style.id), {style: style});
},
openEditForId: function(id) {
var service = Components.classes["@userstyles.org/style;1"].getService(Components.interfaces.stylishStyle);
var style = service.find(id, service.REGISTER_STYLE_ON_CHANGE | service.CALCULATE_META);
return stylishCommon.openEditForStyle(style);
},
// Installing from URLs, with prompting and UI and such. startedCallback is called after the user has entered their URLs,
// endedCallback is called when the process is done.
startInstallFromUrls: function(startedCallback, endedCallback) {
const STRINGS = Components.classes["@mozilla.org/intl/stringbundle;1"].getService(Components.interfaces.nsIStringBundleService).createBundle("chrome://stylish/locale/manage.properties")
var promptService = Components.classes["@mozilla.org/embedcomp/prompt-service;1"].getService(Components.interfaces.nsIPromptService);
var o = {value: ""};
if (!promptService.prompt(window, STRINGS.GetStringFromName("installfromurlsprompttitle"), STRINGS.GetStringFromName("installfromurlsprompt"), o, null, {})) {
return;
}
var urls = o.value.split(/\s+/);
if (urls.length == 0) {
return;
}
if (startedCallback) {
startedCallback();
}
// Run through each one, one at a time, keeping track of successes or failures
var currentIndex = 0;
var results = {successes: [], failures: []};
function processResult(result) {
// We'll consider "cancelled" and "existing" as success, so only "failure" is a failure.
(result != "failure" ? results.successes : results.failures).push(urls[currentIndex]);
currentIndex++;
if (currentIndex < urls.length) {
stylishCommon.installFromUrl(urls[currentIndex], processResult);
} else {
stylishCommon.endInstallFromUrls(results, endedCallback);
}
}
stylishCommon.installFromUrl(urls[currentIndex], processResult);
},
endInstallFromUrls: function(results, endedCallback) {
if (endedCallback) {
endedCallback();
}
if (results.failures.length > 0) {
const STRINGS = Components.classes["@mozilla.org/intl/stringbundle;1"].getService(Components.interfaces.nsIStringBundleService).createBundle("chrome://stylish/locale/manage.properties")
var promptService = Components.classes["@mozilla.org/embedcomp/prompt-service;1"].getService(Components.interfaces.nsIPromptService);
promptService.alert(window, STRINGS.GetStringFromName("installfromurlsprompttitle"), STRINGS.formatStringFromName("installfromurlserror", [results.failures.join(", ")], 1));
}
},
installFromUrl: function(url, callback) {
// Valid URLs can retrived a CSS file or a HTML file. We'll try HTML first, and if the
// content type comes back as CSS, we'll do that instead. These need to be separate requests
// because setting responseType to document (for HTML parsing) prevents access to responseText.
stylishCommon.installFromUrlHtml(url, function(result) {
if (result == "css") {
stylishCommon.installFromUrlCss(url, callback);
return;
}
callback(result);
});
},
installFromUrlHtml: function(url, callback) {
// Assume a local file is a CSS file.
if (/^file:.*/i.test(url)) {
callback("css");
return;
}
var xhr = new XMLHttpRequest();
xhr.onload = function() {
if (this.status != 200) {
Components.utils.reportError("Stylish install from URL '" + url + "' resulted in HTTP error code " + this.status + ".");
callback("failure");
return;
}
var contentType = this.getResponseHeader("Content-Type");
if (contentType.indexOf("text/css") == 0) {
callback("css");
return;
}
if (contentType.indexOf("text/html") == 0) {
stylishCommon.installFromSite(this.responseXML, callback);
return;
}
Components.utils.reportError("Stylish install from URL '" + url + "' resulted in unknown content type " + contentType + ".");
callback("failure");
}
try {
xhr.open("GET", url);
} catch (ex) {
// invalid url
Components.utils.reportError("Stylish install from URL '" + url + "' failed - not a valid URL.");
callback("failure");
return;
}
xhr.responseType = "document";
xhr.send();
},
installFromUrlCss: function(url, callback) {
var xhr = new XMLHttpRequest();
xhr.onload = function() {
if (xhr.status >= 400) {
Components.utils.reportError("Stylish install from URL '" + url + "' resulted in HTTP error code " + this.status + ".");
callback("failure");
return;
}
stylishCommon.installFromString(this.responseText, url, callback);
}
xhr.open("GET", url);
xhr.send();
},
// Callback passes a string parameter - installed, failure, cancelled, existing
installFromSite: function(doc, callback) {
// we want both the url and the content of the md5
var md5Url = stylishCommon.getMeta(doc, "stylish-md5-url");
var resourcesNeeded = [{name: "stylish-code", download: true}, {name: "stylish-description", download: true}, {name: "stylish-install-ping-url"}, {name: "stylish-update-url"}, {name: "stylish-md5-url", download: true}, {name: "stylish-id-url"}];
stylishCommon.getResourcesFromMetas(doc, resourcesNeeded, function(results) {
// This is the only required property
if (results["stylish-code"] == null || results["stylish-code"].length == 0) {
callback("failure")
return;
}
var uri = stylishCommon.cleanURI("documentURI" in doc ? doc.documentURI : doc.location.href);
if (results["stylish-id-url"] == null) {
results["stylish-id-url"] = uri
}
var style = Components.classes["@userstyles.org/style;1"].createInstance(Components.interfaces.stylishStyle);
style.mode = style.CALCULATE_META | style.REGISTER_STYLE_ON_CHANGE;
style.init(uri, results["stylish-id-url"], results["stylish-update-url"], md5Url, results["stylish-description"], results["stylish-code"], false, results["stylish-code"], results["stylish-md5-url"], null);
stylishCommon.openInstall({style: style, installPingURL: results["stylish-install-ping-url"], installCallback: callback});
});
},
// Results the value of the <link> with a "rel" of the passed name.
getMeta: function(doc, name) {
var e = doc.querySelector("link[rel='" + name + "']");
return e ? e.getAttribute("href") : null;
},
// Gets the values of the passed meta names.
// doc
// resourcesToGet: an array of:
// name: meta name to get
// download: if true, will download if the value is a remote URL
// callback: called with a hash of name to value
getResourcesFromMetas: function(doc, resourcesToGet, callback) {
var keyUrls = {};
var resourcesToDownload = [];
resourcesToGet.forEach(function(r) {
var c = stylishCommon.getMeta(doc, r.name);
if (r.download) {
resourcesToDownload.push({name: r.name, url: c});
} else {
keyUrls[r.name] = c;
}
});
stylishCommon.getResources(doc, resourcesToDownload, function(results) {
results.forEach(function(r) {
keyUrls[r.name] = r.value;
});
callback(keyUrls);
});
},
// Gets the values of the passed URLs.
// doc
// resources: an array of:
// name: name of the resource
// url: url of the resource
// callback: called with a hash of name to value
getResources: function(doc, resources, callback) {
var results = [];
function assembleResults(name, value) {
results.push({name: name, value: value});
if (results.length == resources.length) {
callback(results);
}
}
resources.forEach(function(resource) {
stylishCommon.getResource(doc, resource.name, resource.url, assembleResults);
});
},
// Get the value of the passed URL.
getResource: function(doc, name, url, callback) {
if (url == null) {
callback(name, null);
return;
}
if (url.indexOf("#") == 0) {
callback(name, doc.getElementById(url.substring(1)).textContent);
return;
}
var xhr = new XMLHttpRequest();
xhr.onload = function() {
if (xhr.status >= 400) {
callback(name, null);
} else {
callback(name, xhr.responseText);
}
}
if (url.length > 2000) {
var parts = url.split("?");
xhr.open("POST", parts[0], true);
xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xhr.send(parts[1]);
} else {
xhr.open("GET", url, true);
xhr.send();
}
},
installFromFile: function(doc) {
stylishCommon.installFromString(doc.body.textContent, doc.location.href);
},
installFromString: function(css, uri, callback) {
uri = stylishCommon.cleanURI(uri);
var style = Components.classes["@userstyles.org/style;1"].createInstance(Components.interfaces.stylishStyle);
style.mode = style.CALCULATE_META | style.REGISTER_STYLE_ON_CHANGE;
style.init(uri, uri, uri, null, null, css, false, css, null, null);
stylishCommon.openInstall({style: style, installCallback: callback});
},
openInstall: function(params) {
var style = params.style;
// let's check if it's already installed
var service = Components.classes["@userstyles.org/style;1"].getService(Components.interfaces.stylishStyle);
if (service.findByUrl(style.idUrl, 0) != null) {
if (params.installCallback) {
params.installCallback("existing");
}
return;
}
if (!stylishCommon.isXULAvailable) {
var installStrings = Components.classes["@mozilla.org/intl/stringbundle;1"].getService(Components.interfaces.nsIStringBundleService).createBundle("chrome://stylish/locale/install.properties");
var promptService = Components.classes["@mozilla.org/embedcomp/prompt-service;1"].getService(Components.interfaces.nsIPromptService);
var promptTitle = typeof stylishStrings == "undefined" ? "Install user style" : stylishStrings.title;
var result;
if (style.name) {
var installPrompt = installStrings.formatStringFromName("installintro", [style.name], 1);
// title is read from entity in overlay-mobile.xul, but not available in manage.html (which is not localized anyway!)
result = promptService.confirm(window, promptTitle, installPrompt);
} else {
var installPrompt = "Give the style from '" + style.idUrl + "' a name.";
var name = {value: ""};
result = promptService.prompt(window, promptTitle, installPrompt, name, null, {});
if (result) {
style.name = name.value;
}
}
if (result) {
style.enabled = true;
style.save();
if (params.installPingURL) {
var req = new XMLHttpRequest();
req.open("GET", params.installPingURL, true);
stylishCommon.fixXHR(req);
req.send(null);
}
if (params.installCallback) {
params.installCallback("installed");
}
} else {
if (params.installCallback) {
params.installCallback("cancelled");
}
}
return;
}
function fillName(prefix) {
params.windowType = stylishCommon.getWindowName(prefix, params.triggeringDocument ? stylishCommon.cleanURI(params.triggeringDocument.location.href) : null);
}
if (Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefBranch).getBoolPref("extensions.stylish.editOnInstall")) {
fillName("stylishEdit");
stylishCommon.openEdit(params.windowType, params);
} else {
fillName("stylishInstall");
if (!stylishCommon.focusWindow(params.windowType)) {
openDialog("chrome://stylish/content/install.xul", params.windowType, "chrome,resizable,dialog=no,centerscreen,resizable", params);
}
}
},
cleanURI: function(uri) {
var hash = uri.indexOf("#");
if (hash > -1) {
uri = uri.substring(0, hash);
}
return uri;
},
// Removes whitespace and duplicate tags. Pass in a string and receive an array.
cleanTags: function(tags) {
tags = tags.split(/[\s,]+/);
var uniqueTags = [];
tags.filter(function(tag) {
return !/^\s*$/.test(tag);
}).forEach(function(tag) {
if (!uniqueTags.some(function(utag) {
return utag.toLowerCase() == tag.toLowerCase();
})) {
uniqueTags.push(tag);
}
});
return uniqueTags;
},
addCode: function(code) {
var style = Components.classes["@userstyles.org/style;1"].createInstance(Components.interfaces.stylishStyle);
style.mode = style.CALCULATE_META | style.REGISTER_STYLE_ON_CHANGE;
style.init(null, null, null, null, null, code, false, null, null, null);
stylishCommon.openEdit(stylishCommon.getWindowName("stylishEdit"), {style: style});
},
generateSelectors: function(node) {
if (!(node instanceof Element)) {
return;
}
var selectors = [];
//element selector
selectors.push(node.nodeName);
//id selector
if (node.hasAttribute("id")) {
selectors.push("#" + node.getAttribute("id"));
}
//class selector
if (node.hasAttribute("class")) {
var classes = node.getAttribute("class").split(/\s+/);
selectors.push("." + classes.join("."));
}
//attribute selectors. it's pointless to create a complicated attribute selector including an id or only a class
if (node.attributes.length > 1 || (node.attributes.length == 1 && node.attributes[0].name != "id" && node.attributes[0].name != "class")) {
var selector = node.nodeName;
for (var i = 0; i < node.attributes.length; i++) {
if (node.attributes[i].name != "id") {
selector += "[" + node.attributes[i].name + "=\"" + node.attributes[i].value + "\"]";
}
}
selectors.push(selector);
}
//position selector - worthless if we have an id
if (!node.hasAttribute("id") && node != node.ownerDocument.documentElement) {
selectors.push(stylishCommon.getPositionalSelector(node));
}
return selectors;
},
getPositionalSelector: function(node) {
if (node instanceof Document) {
return "";
}
if (node.hasAttribute("id")) {
return "#" + node.getAttribute("id");
}
//are we the only child of the parent with this node name?
var uniqueChild = true;
var nodeName = node.nodeName;
for (var i = 0; i < node.parentNode.childNodes.length; i++) {
var currentNode = node.parentNode.childNodes[i];
//css ignores everything but elements
if (!(currentNode instanceof Element)) {
continue;
}
if (node != currentNode && node.nodeName == currentNode.nodeName) {
uniqueChild = false;
break;
}
}
if (uniqueChild) {
return stylishCommon.getParentPositionalSelector(node) + node.nodeName;
}
//are we the first child?
if (stylishCommon.isCSSFirstChild(node)) {
return stylishCommon.getParentPositionalSelector(node) + node.nodeName + ":first-child";
}
//are we the last child?
if (stylishCommon.isCSSLastChild(node)) {
return stylishCommon.getParentPositionalSelector(node) + node.nodeName + ":last-child";
}
//get our position among our siblings
var elementPosition = 1;
var selectorWithinSiblings = "";
for (var i = 0; i < node.parentNode.childNodes.length; i++) {
var currentNode = node.parentNode.childNodes[i];
//css ignores everything but elements
if (!(currentNode instanceof Element)) {
continue;
}
if (currentNode == node) {
break;
}
elementPosition++;
}
return stylishCommon.getParentPositionalSelector(node) + node.nodeName + ":nth-child(" + elementPosition + ")";
},
isCSSFirstChild: function(node) {
for (var i = 0; i < node.parentNode.childNodes.length; i++) {
var currentNode = node.parentNode.childNodes[i];
if (currentNode instanceof Element) {
return currentNode == node;
}
}
return false;
},
isCSSLastChild: function(node) {
for (var i = node.parentNode.childNodes.length - 1; i >= 0 ; i--) {
var currentNode = node.parentNode.childNodes[i];
if (currentNode instanceof Element) {
return currentNode == node;
}
}
return false;
},
getParentPositionalSelector: function(node) {
if (node.parentNode instanceof Document) {
return "";
}
return stylishCommon.getPositionalSelector(node.parentNode) + " > ";
}
}
|