1 // Copyright (c) 2006-2008 by Martin Stubenschrott <stubenschrott@vimperator.org>
2 // Copyright (c) 2007-2011 by Doug Kearns <dougkearns@gmail.com>
3 // Copyright (c) 2008-2011 by Kris Maglione <maglione.k@gmail.com>
5 // This work is licensed for reuse under an MIT license. Details are
6 // given in the LICENSE.txt file included with this file.
11 Components.utils.import("resource://dactyl/bootstrap.jsm");
13 defineModule("util", {
14 exports: ["frag", "FailedAssertion", "Math", "NS", "Point", "Util", "XBL", "XHTML", "XUL", "util"],
15 require: ["services"],
16 use: ["commands", "config", "highlight", "storage", "template"]
19 var XBL = Namespace("xbl", "http://www.mozilla.org/xbl");
20 var XHTML = Namespace("html", "http://www.w3.org/1999/xhtml");
21 var XUL = Namespace("xul", "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul");
22 var NS = Namespace("dactyl", "http://vimperator.org/namespaces/liberator");
23 default xml namespace = XHTML;
25 var FailedAssertion = Class("FailedAssertion", ErrorBase, {
26 init: function init(message, level, noTrace) {
27 if (noTrace !== undefined)
28 this.noTrace = noTrace;
29 init.supercall(this, message, level);
37 var Point = Struct("x", "y");
39 var wrapCallback = function wrapCallback(fn) {
40 fn.wrapper = function wrappedCallback () {
42 return fn.apply(this, arguments);
49 fn.wrapper.wrapped = fn;
53 var getAttr = function getAttr(elem, ns, name)
54 elem.hasAttributeNS(ns, name) ? elem.getAttributeNS(ns, name) : null;
55 var setAttr = function setAttr(elem, ns, name, val) {
57 elem.removeAttributeNS(ns, name);
59 elem.setAttributeNS(ns, name, val);
62 var Util = Module("Util", XPCOM([Ci.nsIObserver, Ci.nsISupportsWeakReference]), {
66 this.addObserver(this);
70 cleanup: function cleanup() {
71 for (let { document: doc } in iter(services.windowMediator.getEnumerator(null))) {
72 for (let elem in values(doc.dactylOverlayElements || []))
74 elem.parentNode.removeChild(elem);
76 for (let [elem, ns, name, orig, value] in values(doc.dactylOverlayAttributes || []))
77 if (getAttr(elem, ns, name) === value)
78 setAttr(elem, ns, name, orig);
80 delete doc.dactylOverlayElements;
81 delete doc.dactylOverlayAttributes;
82 delete doc.dactylOverlays;
86 // FIXME: Only works for Pentadactyl
87 get activeWindow() services.windowMediator.getMostRecentWindow("navigator:browser"),
88 dactyl: update(function dactyl(obj) {
90 var global = Class.objectGlobal(obj);
92 __noSuchMethod__: function (meth, args) {
93 let win = util.activeWindow;
94 var dactyl = global && global.dactyl || win && win.dactyl;
98 let prop = dactyl[meth];
100 return prop.apply(dactyl, args);
105 __noSuchMethod__: function () this().__noSuchMethod__.apply(null, arguments)
109 * Registers a obj as a new observer with the observer service. obj.observe
110 * must be an object where each key is the name of a target to observe and
111 * each value is a function(subject, data) to be called when the given
112 * target is broadcast. obj.observe will be replaced with a new opaque
113 * function. The observer is automatically unregistered on application
116 * @param {object} obj
118 addObserver: function (obj) {
120 obj.observers = obj.observe;
122 function register(meth) {
123 for (let target in set(["dactyl-cleanup-modules", "quit-application"].concat(Object.keys(obj.observers))))
125 services.observer[meth](obj, target, true);
130 Class.replaceProperty(obj, "observe",
131 function (subject, target, data) {
133 if (target == "quit-application" || target == "dactyl-cleanup-modules")
134 register("removeObserver");
135 if (obj.observers[target])
136 obj.observers[target].call(obj, subject, data);
139 if (typeof util === "undefined")
140 dump("dactyl: error: " + e + "\n" + (e.stack || Error().stack).replace(/^/gm, "dactyl: "));
146 obj.observe.unregister = function () register("removeObserver");
147 register("addObserver");
151 * Tests a condition and throws a FailedAssertion error on
154 * @param {boolean} condition The condition to test.
155 * @param {string} message The message to present to the
158 assert: function (condition, message, quiet) {
160 throw FailedAssertion(message, 1, quiet === undefined ? true : quiet);
164 * Capitalizes the first character of the given string.
165 * @param {string} str The string to capitalize
168 capitalize: function capitalize(str) str && str[0].toUpperCase() + str.slice(1),
171 * Returns a RegExp object that matches characters specified in the range
172 * expression *list*, or signals an appropriate error if *list* is invalid.
174 * @param {string} list Character list, e.g., "a b d-xA-Z" produces /[abd-xA-Z]/.
175 * @param {string} accepted Character range(s) to accept, e.g. "a-zA-Z" for
176 * ASCII letters. Used to validate *list*.
179 charListToRegexp: function charListToRegexp(list, accepted) {
180 list = list.replace(/\s+/g, "");
182 // check for chars not in the accepted range
183 this.assert(RegExp("^[" + accepted + "-]+$").test(list),
184 "Character list outside the range " + accepted.quote());
186 // check for illegal ranges
187 for (let [match] in this.regexp.iterate(/.-./g, list))
188 this.assert(match.charCodeAt(0) <= match.charCodeAt(2),
189 "Invalid character range: " + list.slice(list.indexOf(match)))
191 return RegExp("[" + util.regexp.escape(list) + "]");
194 get chromePackages() {
197 function process(manifest) {
198 for each (let line in manifest.split(/\n+/)) {
199 let match = /^\s*(content|skin|locale|resource)\s+([^\s#]+)\s/.exec(line);
201 res[match[2]] = true;
204 function processJar(file) {
205 let jar = services.ZipReader(file);
207 if (jar.hasEntry("chrome.manifest"))
208 process(File.readStream(jar.getInputStream("chrome.manifest")));
213 for each (let dir in ["UChrm", "AChrom"]) {
214 dir = File(services.directory.get(dir, Ci.nsIFile));
215 if (dir.exists() && dir.isDirectory())
216 for (let file in dir.iterDirectory())
217 if (/\.manifest$/.test(file.leafName))
218 process(file.read());
220 dir = File(dir.parent);
221 if (dir.exists() && dir.isDirectory())
222 for (let file in dir.iterDirectory())
223 if (/\.jar$/.test(file.leafName))
226 dir = dir.child("extensions");
227 if (dir.exists() && dir.isDirectory())
228 for (let ext in dir.iterDirectory()) {
229 if (/\.xpi$/.test(ext.leafName))
233 ext = File(ext.read().replace(/\n*$/, ""));
234 let mf = ext.child("chrome.manifest");
240 return Object.keys(res).sort();
244 * Returns a shallow copy of *obj*.
246 * @param {Object} obj
249 cloneObject: function cloneObject(obj) {
253 for (let [k, v] in Iterator(obj))
259 * Clips a string to a given length. If the input string is longer
260 * than *length*, an ellipsis is appended.
262 * @param {string} str The string to truncate.
263 * @param {number} length The length of the returned string.
266 clip: function clip(str, length) {
267 return str.length <= length ? str : str.substr(0, length - 3) + "...";
271 * Compares two strings, case insensitively. Return values are as
272 * in String#localeCompare.
278 compareIgnoreCase: function compareIgnoreCase(a, b) String.localeCompare(a.toLowerCase(), b.toLowerCase()),
280 compileFormat: function compileFormat(format) {
281 let stack = [frame()];
282 stack.__defineGetter__("top", function () this[this.length - 1]);
284 function frame() update(
286 _frame === stack.top || _frame.valid(obj) ?
287 _frame.elements.map(function (e) callable(e) ? e(obj) : e).join("") : "",
291 valid: function (obj) this.elements.every(function (e) !e.test || e.test(obj))
295 for (let match in util.regexp.iterate(/(.*?)%(.)/gy, format)) {
297 let [, prefix, char] = match;
298 end += match[0].length;
301 stack.top.elements.push(prefix);
303 stack.top.elements.push("%");
304 else if (char === "[") {
306 stack.top.elements.push(f);
309 else if (char === "]") {
311 util.assert(stack.length, "Unmatched %] in format");
314 let quote = function quote(obj, char) obj[char];
315 if (char !== char.toLowerCase())
316 quote = function quote(obj, char) Commands.quote(obj[char]);
317 char = char.toLowerCase();
319 stack.top.elements.push(update(
320 function (obj) obj[char] != null ? quote(obj, char) : "",
321 { test: function (obj) obj[char] != null }));
323 for (let elem in array.iterValues(stack))
324 elem.seen[char] = true;
327 if (end < format.length)
328 stack.top.elements.push(format.substr(end));
330 util.assert(stack.length === 1, "Unmatched %[ in format");
334 compileMacro: function compileMacro(macro, keepUnknown) {
335 let stack = [frame()];
336 stack.__defineGetter__("top", function () this[this.length - 1]);
338 let unknown = util.identity;
340 unknown = function () "";
342 function frame() update(
344 _frame === stack.top || _frame.valid(obj) ?
345 _frame.elements.map(function (e) callable(e) ? e(obj) : e).join("") : "",
349 valid: function (obj) this.elements.every(function (e) !e.test || e.test(obj))
352 let defaults = { lt: "<", gt: ">" };
354 let re = util.regexp(<![CDATA[
358 (< ((?:[a-z]-)?[a-z-]+?) >) | // 3 4
362 macro = String(macro);
364 for (let match in re.iterate(macro)) {
365 let [, prefix, open, full, macro, close] = match;
366 end += match[0].length;
369 stack.top.elements.push(prefix);
372 stack.top.elements.push(f);
377 util.assert(stack.length, "Unmatched %] in macro");
380 let [, flags, name] = /^((?:[a-z]-)*)(.*)/.exec(macro);
383 let quote = util.identity;
385 quote = function quote(obj) typeof obj === "number" ? obj : String.quote(obj);
387 quote = function quote(obj) "";
389 if (set.has(defaults, name))
390 stack.top.elements.push(quote(defaults[name]));
392 stack.top.elements.push(update(
393 function (obj) obj[name] != null ? quote(obj[name]) : set.has(obj, name) ? "" : unknown(full),
394 { test: function (obj) obj[name] != null && obj[name] !== false && (!flags.e || obj[name] != "") }));
396 for (let elem in array.iterValues(stack))
397 elem.seen[name] = true;
401 if (end < macro.length)
402 stack.top.elements.push(macro.substr(end));
404 util.assert(stack.length === 1, "Unmatched <{ in macro");
408 compileMatcher: function compileMatcher(list) {
409 let xpath = [], css = [];
410 for (let elem in values(list))
411 if (/^xpath:/.test(elem))
412 xpath.push(elem.substr(6));
417 function matcher(node) {
419 for (let elem in util.evaluateXPath(matcher.xpath, node))
423 for (let [, elem] in iter(node.querySelectorAll(matcher.css)))
427 xpath: xpath.join(" | ")
431 validateMatcher: function validateMatcher(values) {
432 let evaluator = services.XPathEvaluator();
433 let node = util.xmlToDom(<div/>, document);
434 return this.testValues(values, function (value) {
435 if (/^xpath:/.test(value))
436 evaluator.createExpression(value.substr(6), util.evaluateXPath.resolver);
438 node.querySelector(value);
444 * Returns an object representing a Node's computed CSS style.
449 computedStyle: function computedStyle(node) {
450 while (!(node instanceof Ci.nsIDOMElement) && node.parentNode)
451 node = node.parentNode;
453 var res = node.ownerDocument.defaultView.getComputedStyle(node, null);
457 util.dumpStack(_("error.nullComputedStyle", node));
458 Cu.reportError(Error(_("error.nullComputedStyle", node)));
465 * Converts any arbitrary string into an URI object. Returns null on
468 * @param {string} str
469 * @returns {nsIURI|null}
471 createURI: function createURI(str) {
473 return services.urifixup.createFixupURI(str, services.urifixup.FIXUP_FLAG_ALLOW_KEYWORD_LOOKUP);
481 * Expands brace globbing patterns in a string.
484 * "a{b,c}d" => ["abd", "acd"]
486 * @param {string} pattern The pattern to deglob.
487 * @returns [string] The resulting strings.
489 debrace: function debrace(pattern) {
490 if (pattern.indexOf("{") == -1)
493 function split(pattern, re, fn, dequote) {
494 let end = 0, match, res = [];
495 while (match = re.exec(pattern)) {
496 end = match.index + match[0].length;
501 res.push(pattern.substr(end));
502 return res.map(function (s) util.dequote(s, dequote));
504 let patterns = [], res = [];
505 let substrings = split(pattern, /((?:[^\\{]|\\.)*)\{((?:[^\\}]|\\.)*)\}/gy,
507 patterns.push(split(match[2], /((?:[^\\,]|\\.)*),/gy,
511 if (acc.length == patterns.length)
512 res.push(array(substrings).zip(acc).flatten().join(""));
514 for (let [, pattern] in Iterator(patterns[acc.length]))
515 rec(acc.concat(pattern));
522 * Removes certain backslash-quoted characters while leaving other
523 * backslash-quoting sequences untouched.
525 * @param {string} pattern The string to unquote.
526 * @param {string} chars The characters to unquote.
529 dequote: function dequote(pattern, chars)
530 pattern.replace(/\\(.)/, function (m0, m1) chars.indexOf(m1) >= 0 ? m1 : m0),
532 domToString: function (node, html) {
533 if (node instanceof Ci.nsISelection && node.isCollapsed)
536 if (node instanceof Ci.nsIDOMNode) {
537 let range = node.ownerDocument.createRange();
538 range.selectNode(node);
541 let doc = (node.getRangeAt ? node.getRangeAt(0) : node).startContainer.ownerDocument;
543 let encoder = services.HtmlEncoder();
544 encoder.init(doc, "text/unicode", encoder.OutputRaw|encoder.OutputPreformatted);
545 if (node instanceof Ci.nsISelection)
546 encoder.setSelection(node);
547 else if (node instanceof Ci.nsIDOMRange)
548 encoder.setRange(node);
550 let str = services.String(encoder.encodeToString());
554 let [result, length] = [{}, {}];
555 services.HtmlConverter().convert("text/html", str, str.data.length*2, "text/unicode", result, length);
556 return result.value.QueryInterface(Ci.nsISupportsString).data;
560 * Prints a message to the console. If *msg* is an object it is pretty
563 * @param {string|Object} msg The message to print.
565 dump: defineModule.dump,
567 stackLines: function (stack) {
569 let match, re = /([^]*?)@([^@\n]*)(?:\n|$)/g;
570 while (match = re.exec(stack))
571 lines.push(match[1].replace(/\n/g, "\\n").substr(0, 80) + "@" +
572 util.fixURI(match[2]));
577 * Dumps a stack trace to the console.
579 * @param {string} msg The trace message.
580 * @param {number} frames The number of frames to print.
582 dumpStack: function dumpStack(msg, frames) {
583 let stack = util.stackLines(Error().stack);
584 stack = stack.slice(1, 1 + (frames || stack.length)).join("\n").replace(/^/gm, " ");
585 util.dump((arguments.length == 0 ? "Stack" : msg) + "\n" + stack + "\n");
589 * The set of input element type attribute values that mark the element as
592 editableInputs: set(["date", "datetime", "datetime-local", "email", "file",
593 "month", "number", "password", "range", "search",
594 "tel", "text", "time", "url", "week"]),
597 * Converts HTML special characters in *str* to the equivalent HTML
600 * @param {string} str
603 escapeHTML: function escapeHTML(str) {
604 return str.replace(/&/g, "&").replace(/</g, "<");
608 * Escapes quotes, newline and tab characters in *str*. The returned string
609 * is delimited by *delimiter* or " if *delimiter* is not specified.
610 * {@see String#quote}.
612 * @param {string} str
613 * @param {string} delimiter
616 escapeString: function escapeString(str, delimiter) {
617 if (delimiter == undefined)
619 return delimiter + str.replace(/([\\'"])/g, "\\$1").replace("\n", "\\n", "g").replace("\t", "\\t", "g") + delimiter;
623 * Evaluates an XPath expression in the current or provided
624 * document. It provides the xhtml, xhtml2 and dactyl XML
625 * namespaces. The result may be used as an iterator.
627 * @param {string} expression The XPath expression to evaluate.
628 * @param {Node} elem The context element.
629 * @default The current document.
630 * @param {boolean} asIterator Whether to return the results as an
632 * @returns {Object} Iterable result of the evaluation.
634 evaluateXPath: update(
635 function evaluateXPath(expression, elem, asIterator) {
638 elem = util.activeWindow.content.document;
639 let doc = elem.ownerDocument || elem;
640 if (isArray(expression))
641 expression = util.makeXPath(expression);
643 let result = doc.evaluate(expression, elem,
644 evaluateXPath.resolver,
645 asIterator ? Ci.nsIDOMXPathResult.ORDERED_NODE_ITERATOR_TYPE : Ci.nsIDOMXPathResult.ORDERED_NODE_SNAPSHOT_TYPE,
649 return Object.create(result, {
651 value: asIterator ? function () { let elem; while ((elem = this.iterateNext())) yield elem; }
652 : function () { for (let i = 0; i < this.snapshotLength; i++) yield this.snapshotItem(i); }
657 throw e.stack ? e : Error(e);
661 resolver: function lookupNamespaceURI(prefix) ({
664 xhtml2: "http://www.w3.org/2002/06/xhtml2",
669 extend: function extend(dest) {
670 Array.slice(arguments, 1).filter(util.identity).forEach(function (src) {
671 for (let [k, v] in Iterator(src)) {
672 let get = src.__lookupGetter__(k),
673 set = src.__lookupSetter__(k);
677 dest.__defineGetter__(k, get);
679 dest.__defineSetter__(k, set);
686 * Converts *bytes* to a pretty printed data size string.
688 * @param {number} bytes The number of bytes.
689 * @param {string} decimalPlaces The number of decimal places to use if
690 * *humanReadable* is true.
691 * @param {boolean} humanReadable Use byte multiples.
694 formatBytes: function formatBytes(bytes, decimalPlaces, humanReadable) {
695 const unitVal = ["Bytes", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB", "ZiB", "YiB"];
697 let tmpNum = parseInt(bytes, 10) || 0;
698 let strNum = [tmpNum + ""];
701 while (tmpNum >= 1024) {
703 if (++unitIndex > (unitVal.length - 1))
707 let decPower = Math.pow(10, decimalPlaces);
708 strNum = ((Math.round(tmpNum * decPower) / decPower) + "").split(".", 2);
713 while (strNum[1].length < decimalPlaces) // pad with "0" to the desired decimalPlaces)
717 for (let u = strNum[0].length - 3; u > 0; u -= 3) // make a 10000 a 10,000
718 strNum[0] = strNum[0].substr(0, u) + "," + strNum[0].substr(u);
720 if (unitIndex) // decimalPlaces only when > Bytes
721 strNum[0] += "." + strNum[1];
723 return strNum[0] + " " + unitVal[unitIndex];
727 * Converts *seconds* into a human readable time string.
729 * @param {number} seconds
732 formatSeconds: function formatSeconds(seconds) {
733 function pad(n, val) ("0000000" + val).substr(-Math.max(n, String(val).length));
734 function div(num, denom) [Math.round(num / denom), Math.round(num % denom)];
735 let days, hours, minutes;
737 [minutes, seconds] = div(seconds, 60);
738 [hours, minutes] = div(minutes, 60);
739 [days, hours] = div(hours, 24);
741 return days + " days " + hours + " hours"
743 return hours + "h " + minutes + "m";
745 return minutes + ":" + pad(2, seconds);
746 return seconds + "s";
750 * Returns the file which backs a given URL, if available.
752 * @param {nsIURI} uri The URI for which to find a file.
753 * @returns {File|null}
755 getFile: function getFile(uri) {
758 uri = util.newURI(util.fixURI(uri));
760 if (uri instanceof Ci.nsIFileURL)
761 return File(uri.QueryInterface(Ci.nsIFileURL).file);
763 let channel = services.io.newChannelFromURI(uri);
764 channel.cancel(Cr.NS_BINDING_ABORTED);
765 if (channel instanceof Ci.nsIFileChannel)
766 return File(channel.QueryInterface(Ci.nsIFileChannel).file);
773 * Returns the host for the given URL, or null if invalid.
775 * @param {string} url
776 * @returns {string|null}
778 getHost: function (url) {
780 return util.createURI(url).host;
787 * Returns true if the current Gecko runtime is of the given version
790 * @param {string} ver The required version.
793 haveGecko: function (ver) services.versionCompare.compare(services.runtime.platformVersion, ver) >= 0,
796 * Sends a synchronous or asynchronous HTTP request to *url* and returns
797 * the XMLHttpRequest object. If *callback* is specified the request is
798 * asynchronous and the *callback* is invoked with the object as its
801 * @param {string} url
802 * @param {function(XMLHttpRequest)} callback
803 * @returns {XMLHttpRequest}
805 httpGet: function httpGet(url, callback, self) {
806 let params = callback;
807 if (!isObject(params))
808 params = { callback: params && function () callback.apply(self, arguments) };
811 let xmlhttp = services.Xmlhttp();
812 xmlhttp.mozBackgroundRequest = true;
814 let async = params.callback || params.onload || params.onerror;
816 xmlhttp.onload = function handler(event) { util.trapErrors(params.onload || params.callback, params, xmlhttp, event) };
817 xmlhttp.onerror = function handler(event) { util.trapErrors(params.onerror || params.callback, params, xmlhttp, event) };
820 xmlhttp.overrideMimeType(params.mimeType);
822 xmlhttp.open(params.method || "GET", url, async,
823 params.user, params.pass);
829 util.dactyl.log("Error opening " + String.quote(url) + ": " + e, 1);
835 * The identity function.
840 identity: function identity(k) k,
843 * Returns the intersection of two rectangles.
849 intersection: function (r1, r2) ({
850 get width() this.right - this.left,
851 get height() this.bottom - this.top,
852 left: Math.max(r1.left, r2.left),
853 right: Math.min(r1.right, r2.right),
854 top: Math.max(r1.top, r2.top),
855 bottom: Math.min(r1.bottom, r2.bottom)
859 * Returns true if the given stack frame resides in Dactyl code.
861 * @param {nsIStackFrame} frame
864 isDactyl: Class.memoize(function () {
865 let base = util.regexp.escape(Components.stack.filename.replace(/[^\/]+$/, ""));
866 let re = RegExp("^(?:.* -> )?(?:resource://dactyl(?!-content/eval.js)|" + base + ")\\S+$");
867 return function isDactyl(frame) re.test(frame.filename);
871 * Returns true if *url* is in the domain *domain*.
873 * @param {string} url
874 * @param {string} domain
877 isDomainURL: function isDomainURL(url, domain) util.isSubdomain(util.getHost(url), domain),
879 /** Dactyl's notion of the current operating system platform. */
881 _arch: services.runtime.OS,
883 * @property {string} The normalised name of the OS. This is one of
884 * "Windows", "Mac OS X" or "Unix".
886 get name() this.isWindows ? "Windows" : this.isMacOSX ? "Mac OS X" : "Unix",
887 /** @property {boolean} True if the OS is Windows. */
888 get isWindows() this._arch == "WINNT",
889 /** @property {boolean} True if the OS is Mac OS X. */
890 get isMacOSX() this._arch == "Darwin",
891 /** @property {boolean} True if the OS is some other *nix variant. */
892 get isUnix() !this.isWindows && !this.isMacOSX,
893 /** @property {RegExp} A RegExp which matches illegal characters in path components. */
894 get illegalCharacters() this.isWindows ? /[<>:"/\\|?*\x00-\x1f]/g : /\//g
898 * Returns true if *host* is a subdomain of *domain*.
900 * @param {string} host The host to check.
901 * @param {string} domain The base domain to check the host against.
904 isSubdomain: function isSubdomain(host, domain) {
907 let idx = host.lastIndexOf(domain);
908 return idx > -1 && idx + domain.length == host.length && (idx == 0 || host[idx - 1] == ".");
912 * Returns true if the given DOM node is currently visible.
917 isVisible: function (node) {
918 let style = util.computedStyle(node);
919 return style.visibility == "visible" && style.display != "none";
923 * Iterates over all currently open documents, including all
924 * top-level window and sub-frames thereof.
926 iterDocuments: function iterDocuments() {
927 let windows = services.windowMediator.getXULWindowEnumerator(null);
928 while (windows.hasMoreElements()) {
929 let window = windows.getNext().QueryInterface(Ci.nsIXULWindow);
930 for each (let type in ["typeChrome", "typeContent"]) {
931 let docShells = window.docShell.getDocShellEnumerator(Ci.nsIDocShellTreeItem[type],
932 Ci.nsIDocShell.ENUMERATE_FORWARDS);
933 while (docShells.hasMoreElements())
934 let (viewer = docShells.getNext().QueryInterface(Ci.nsIDocShell).contentViewer) {
936 yield viewer.DOMDocument;
943 * Returns an XPath union expression constructed from the specified node
944 * tests. An expression is built with node tests for both the null and
945 * XHTML namespaces. See {@link Buffer#evaluateXPath}.
947 * @param nodes {Array(string)}
950 makeXPath: function makeXPath(nodes) {
951 return array(nodes).map(util.debrace).flatten()
952 .map(function (node) [node, "xhtml:" + node]).flatten()
953 .map(function (node) "//" + node).join(" | ");
956 map: deprecated("iter.map", function map(obj, fn, self) iter(obj).map(fn, self).toArray()),
957 writeToClipboard: deprecated("dactyl.clipboardWrite", function writeToClipboard(str, verbose) util.dactyl.clipboardWrite(str, verbose)),
958 readFromClipboard: deprecated("dactyl.clipboardRead", function readFromClipboard() util.dactyl.clipboardRead(false)),
961 * Converts a URI string into a URI object.
963 * @param {string} uri
966 // FIXME: createURI needed too?
967 newURI: function (uri, charset, base) services.io.newURI(uri, charset, base),
970 * Removes leading garbage prepended to URIs by the subscript
973 fixURI: function fixURI(url) String.replace(url, /.* -> /, ""),
976 * Pretty print a JavaScript object. Use HTML markup to color certain items
977 * if *color* is true.
979 * @param {Object} object The object to pretty print.
980 * @param {boolean} color Whether the output should be colored.
983 objectToString: function objectToString(object, color) {
984 // Use E4X literals so html is automatically quoted
985 // only when it's asked for. No one wants to see <
986 // on their console or :map :foo in their buffer
987 // when they expect :map <C-f> :foo.
988 XML.prettyPrinting = false;
989 XML.ignoreWhitespace = false;
992 return object + "\n";
994 if (!isObject(object))
995 return String(object);
997 function namespaced(node) {
998 var ns = NAMESPACES[node.namespaceURI] || /^(?:(.*?):)?/.exec(node.name)[0];
1000 return node.localName;
1002 return <><span highlight="HelpXMLNamespace">{ns}</span>{node.localName}</>
1003 return ns + ":" + node.localName;
1006 if (object instanceof Ci.nsIDOMElement) {
1007 const NAMESPACES = array.toObject([
1013 if (elem.nodeType == elem.TEXT_NODE)
1017 let hasChildren = elem.firstChild && (!/^\s*$/.test(elem.firstChild) || elem.firstChild.nextSibling)
1019 return <span highlight="HelpXMLBlock"><span highlight="HelpXMLTagStart"><{
1021 template.map(array.iterValues(elem.attributes),
1023 <span highlight="HelpXMLAttribute">{namespaced(attr)}</span> +
1024 <span highlight="HelpXMLString">{attr.value}</span>,
1026 }{ !hasChildren ? "/>" : ">"
1027 }</span>{ !hasChildren ? "" : <>...</> +
1028 <span highlight="HtmlTagEnd"><{namespaced(elem)}></span>
1031 let tag = "<" + [namespaced(elem)].concat(
1032 [namespaced(a) + "=" + template.highlight(a.value, true)
1033 for ([i, a] in array.iterItems(elem.attributes))]).join(" ");
1034 return tag + (!hasChildren ? "/>" : ">...</" + namespaced(elem) + ">");
1037 return {}.toString.call(elem);
1041 try { // for window.JSON
1042 var obj = String(object);
1045 obj = Object.prototype.toString.call(obj);
1047 obj = template.highlightFilter(util.clip(obj, 150), "\n", !color ? function () "^J" : function () <span highlight="NonText">^J</span>);
1048 let string = <><span highlight="Title Object">{obj}</span>::
</>;
1052 // window.content often does not want to be queried with "var i in object"
1054 let hasValue = !("__iterator__" in object || isinstance(object, ["Generator", "Iterator"]));
1055 if (object.dactyl && object.modules && object.modules.modules == object.modules) {
1056 object = Iterator(object);
1059 for (let i in object) {
1060 let value = <![CDATA[<no value>]]>;
1066 if (isArray(i) && i.length == 2)
1072 value = template.highlight(value, true, 150);
1073 let key = <span highlight="Key">{i}</span>;
1076 else if (/^[A-Z_]+$/.test(i))
1078 keys.push([i, <>{key}{noVal ? "" : <>: {value}</>}
</>]);
1083 function compare(a, b) {
1084 if (!isNaN(a[0]) && !isNaN(b[0]))
1086 return String.localeCompare(a[0], b[0]);
1088 string += template.map(keys.sort(compare), function (f) f[1]);
1089 return color ? <div style="white-space: pre-wrap;">{string}</div> : [s for each (s in string)].join("");
1093 "dactyl-cleanup-modules": function () {
1094 defineModule.loadLog.push("dactyl: util: observe: dactyl-cleanup-modules");
1096 for (let module in values(defineModule.modules))
1097 if (module.cleanup) {
1098 util.dump("cleanup: " + module.constructor.className);
1099 util.trapErrors(module.cleanup, module);
1102 JSMLoader.cleanup();
1104 if (!this.rehashing)
1105 services.observer.addObserver(this, "dactyl-rehash", true);
1107 "dactyl-rehash": function () {
1108 services.observer.removeObserver(this, "dactyl-rehash");
1110 defineModule.loadLog.push("dactyl: util: observe: dactyl-rehash");
1111 if (!this.rehashing)
1112 for (let module in values(defineModule.modules)) {
1113 defineModule.loadLog.push("dactyl: util: init(" + module + ")");
1120 "dactyl-purge": function () {
1123 "toplevel-window-ready": function (window, data) {
1124 window.addEventListener("DOMContentLoaded", wrapCallback(function listener(event) {
1125 if (event.originalTarget === window.document) {
1126 window.removeEventListener("DOMContentLoaded", listener.wrapper, true);
1127 util._loadOverlays(window);
1131 "chrome-document-global-created": function (window, uri) { this.observe(window, "toplevel-window-ready", null); },
1132 "content-document-global-created": function (window, uri) { this.observe(window, "toplevel-window-ready", null); }
1135 _loadOverlays: function _loadOverlays(window) {
1136 if (!window.dactylOverlays)
1137 window.dactylOverlays = [];
1139 for each (let obj in util.overlays[window.document.documentURI] || []) {
1140 if (window.dactylOverlays.indexOf(obj) >= 0)
1142 window.dactylOverlays.push(obj);
1143 this._loadOverlay(window, obj(window));
1147 _loadOverlay: function _loadOverlay(window, obj) {
1148 let doc = window.document;
1149 if (!doc.dactylOverlayElements) {
1150 doc.dactylOverlayElements = [];
1151 doc.dactylOverlayAttributes = [];
1154 function overlay(key, fn) {
1156 let iterator = Iterator(obj[key]);
1157 if (!isObject(obj[key]))
1158 iterator = ([elem.@id, elem.elements(), elem.@*::*.(function::name() != "id")] for each (elem in obj[key]));
1160 for (let [elem, xml, attr] in iterator) {
1161 if (elem = doc.getElementById(elem)) {
1162 let node = util.xmlToDom(xml, doc, obj.objects);
1163 if (!(node instanceof Ci.nsIDOMDocumentFragment))
1164 doc.dactylOverlayElements.push(node);
1166 for (let n in array.iterValues(node.childNodes))
1167 doc.dactylOverlayElements.push(n);
1170 for each (let attr in attr || []) {
1171 let ns = attr.namespace(), name = attr.localName();
1172 doc.dactylOverlayAttributes.push([elem, ns, name, getAttr(elem, ns, name), String(attr)]);
1173 if (attr.name() != "highlight")
1174 elem.setAttributeNS(ns, name, String(attr));
1176 highlight.highlightNode(elem, String(attr));
1183 overlay("before", function (elem, dom) elem.parentNode.insertBefore(dom, elem));
1184 overlay("after", function (elem, dom) elem.parentNode.insertBefore(dom, elem.nextSibling));
1185 overlay("append", function (elem, dom) elem.appendChild(dom));
1186 overlay("prepend", function (elem, dom) elem.insertBefore(dom, elem.firstChild));
1191 if (doc.readyState === "complete")
1194 doc.addEventListener("load", wrapCallback(function load(event) {
1195 if (event.originalTarget === event.target) {
1196 doc.removeEventListener("load", load.wrapper, true);
1197 obj.load(window, event);
1202 overlayObject: function (object, overrides) {
1203 let original = Object.create(object);
1204 overrides = update(Object.create(original), overrides);
1206 Object.getOwnPropertyNames(overrides).forEach(function (k) {
1207 let orig, desc = Object.getOwnPropertyDescriptor(overrides, k);
1208 if (desc.value instanceof Class.Property)
1209 desc = desc.value.init(k) || desc.value;
1211 for (let obj = object; obj && !orig; obj = Object.getPrototypeOf(obj))
1212 if (orig = Object.getOwnPropertyDescriptor(obj, k))
1213 Object.defineProperty(original, k, orig);
1215 // Guard against horrible add-ons that use eval-based monkey
1217 if (callable(desc.value)) {
1218 let value = desc.value;
1220 let sentinel = "(function DactylOverlay() {}())"
1221 value.toString = function toString() toString.toString.call(this).replace(/\}?$/, sentinel + "; $&");
1222 value.toSource = function toSource() toString.toSource.call(this).replace(/\}?$/, sentinel + "; $&");
1225 delete desc.writable;
1226 desc.get = function get() value;
1227 desc.set = function set(val) {
1228 if (String(val).indexOf(sentinel) < 0)
1229 Class.replaceProperty(this, k, val);
1231 let package_ = util.newURI(util.fixURI(Components.stack.caller.filename)).host;
1232 util.reportError(Error(_("error.monkeyPatchOverlay", package_)));
1233 util.dactyl.echoerr(_("error.monkeyPatchOverlay", package_));
1238 Object.defineProperty(object, k, desc);
1241 return function unwrap() {
1242 for each (let k in Object.getOwnPropertyNames(original))
1243 Object.defineProperty(object, k, Object.getOwnPropertyDescriptor(original, k));
1247 overlayWindow: function (url, fn) {
1248 if (url instanceof Ci.nsIDOMWindow)
1249 util._loadOverlay(url, fn);
1251 Array.concat(url).forEach(function (url) {
1252 if (!this.overlays[url])
1253 this.overlays[url] = [];
1254 this.overlays[url].push(fn);
1257 for (let doc in util.iterDocuments())
1258 if (["interactive", "complete"].indexOf(doc.readyState) >= 0)
1259 this._loadOverlays(doc.defaultView);
1261 this.observe(doc.defaultView, "toplevel-window-ready");
1266 * Parses the fields of a form and returns a URL/POST-data pair
1267 * that is the equivalent of submitting the form.
1269 * @param {nsINode} field One of the fields of the given form.
1272 // Nuances gleaned from browser.jar/content/browser/browser.js
1273 parseForm: function parseForm(field) {
1274 function encode(name, value, param) {
1275 param = param ? "%s" : "";
1277 return name + "=" + encodeComponent(value + param);
1278 return encodeComponent(name) + "=" + encodeComponent(value) + param;
1281 let form = field.form;
1282 let doc = form.ownerDocument;
1284 let charset = doc.characterSet;
1285 let converter = services.CharsetConv(charset);
1286 for each (let cs in form.acceptCharset.split(/\s*,\s*|\s+/)) {
1287 let c = services.CharsetConv(cs);
1289 converter = services.CharsetConv(cs);
1294 let uri = util.newURI(doc.baseURI.replace(/\?.*/, ""), charset);
1295 let url = util.newURI(form.action, charset, uri).spec;
1297 let post = form.method.toUpperCase() == "POST";
1299 let encodeComponent = encodeURIComponent;
1300 if (charset !== "UTF-8")
1301 encodeComponent = function encodeComponent(str)
1302 escape(converter.ConvertFromUnicode(str) + converter.Finish());
1305 if (field instanceof Ci.nsIDOMHTMLInputElement && field.type == "submit")
1306 elems.push(encode(field.name, field.value));
1308 for (let [, elem] in iter(form.elements)) {
1309 if (set.has(util.editableInputs, elem.type)
1310 || /^(?:hidden|textarea)$/.test(elem.type)
1311 || elem.checked && /^(?:checkbox|radio)$/.test(elem.type))
1312 elems.push(encode(elem.name, elem.value, elem === field));
1313 else if (elem instanceof Ci.nsIDOMHTMLSelectElement) {
1314 for (let [, opt] in Iterator(elem.options))
1316 elems.push(encode(elem.name, opt.value));
1320 return [url, elems.join('&'), charset, elems];
1321 return [url + "?" + elems.join('&'), null, charset, elems];
1325 * A generator that returns the values between *start* and *end*, in *step*
1328 * @param {number} start The interval's start value.
1329 * @param {number} end The interval's end value.
1330 * @param {boolean} step The value to step the range by. May be
1331 * negative. @default 1
1332 * @returns {Iterator(Object)}
1334 range: function range(start, end, step) {
1338 for (; start < end; start += step)
1343 yield start += step;
1348 * An interruptible generator that returns all values between *start* and
1349 * *end*. The thread yields every *time* milliseconds.
1351 * @param {number} start The interval's start value.
1352 * @param {number} end The interval's end value.
1353 * @param {number} time The time in milliseconds between thread yields.
1354 * @returns {Iterator(Object)}
1356 interruptibleRange: function interruptibleRange(start, end, time) {
1357 let endTime = Date.now() + time;
1358 while (start < end) {
1359 if (Date.now() > endTime) {
1360 util.threadYield(true, true);
1361 endTime = Date.now() + time;
1368 * Creates a new RegExp object based on the value of expr stripped
1369 * of all white space and interpolated with the values from tokens.
1370 * If tokens, any string in the form of <key> in expr is replaced
1371 * with the value of the property, 'key', from tokens, if that
1372 * property exists. If the property value is itself a RegExp, its
1373 * source is substituted rather than its string value.
1375 * Additionally, expr is stripped of all JavaScript comments.
1377 * This is similar to Perl's extended regular expression format.
1379 * @param {string|XML} expr The expression to compile into a RegExp.
1380 * @param {string} flags Flags to apply to the new RegExp.
1381 * @param {object} tokens The tokens to substitute. @optional
1382 * @returns {RegExp} A custom regexp object.
1384 regexp: update(function (expr, flags, tokens) {
1385 flags = flags || [k for ([k, v] in Iterator({ g: "global", i: "ignorecase", m: "multiline", y: "sticky" }))
1386 if (expr[v])].join("");
1388 if (isinstance(expr, ["RegExp"]))
1391 expr = String.replace(expr, /\\(.)/, function (m, m1) {
1393 flags = flags.replace(/i/g, "") + "i";
1395 flags = flags.replace(/i/g, "");
1401 // Replace replacement <tokens>.
1403 expr = String.replace(expr, /(\(?P)?<(\w+)>/g, function (m, n1, n2) !n1 && set.has(tokens, n2) ? tokens[n2].dactylSource || tokens[n2].source || tokens[n2] : m);
1405 // Strip comments and white space.
1406 if (/x/.test(flags))
1407 expr = String.replace(expr, /(\\.)|\/\/[^\n]*|\/\*[^]*?\*\/|\s+/gm, function (m, m1) m1 || "");
1409 // Replace (?P<named> parameters)
1410 if (/\(\?P</.test(expr)) {
1412 let groups = ["wholeMatch"];
1413 expr = expr.replace(/((?:[^[(\\]|\\.|\[(?:[^\]]|\\.)*\])*)\((?:\?P<([^>]+)>|(\?))?/gy,
1414 function (m0, m1, m2, m3) {
1416 groups.push(m2 || "-group-" + groups.length);
1417 return m1 + "(" + (m3 || "");
1419 var struct = Struct.apply(null, groups);
1422 let res = update(RegExp(expr, flags.replace("x", "")), {
1423 closure: Class.Property(Object.getOwnPropertyDescriptor(Class.prototype, "closure")),
1424 dactylPropertyNames: ["exec", "match", "test", "toSource", "toString", "global", "ignoreCase", "lastIndex", "multiLine", "source", "sticky"],
1425 iterate: function (str, idx) util.regexp.iterate(this, str, idx)
1428 // Return a struct with properties for named parameters if we
1432 exec: function exec() let (match = exec.superapply(this, arguments)) match && struct.fromArray(match),
1433 dactylSource: source, struct: struct
1438 * Escapes Regular Expression special characters in *str*.
1440 * @param {string} str
1443 escape: function regexp_escape(str) str.replace(/([\\{}()[\]^$.?*+|])/g, "\\$1"),
1446 * Given a RegExp, returns its source in the form showable to the user.
1448 * @param {RegExp} re The regexp showable source of which is to be returned.
1451 getSource: function regexp_getSource(re) re.source.replace(/\\(.)/g, function (m0, m1) m1 === "/" ? "/" : m0),
1454 * Iterates over all matches of the given regexp in the given
1457 * @param {RegExp} regexp The regular expression to execute.
1458 * @param {string} string The string to search.
1459 * @param {number} lastIndex The index at which to begin searching. @optional
1461 iterate: function iterate(regexp, string, lastIndex) iter(function () {
1462 regexp.lastIndex = lastIndex = lastIndex || 0;
1464 while (match = regexp.exec(string)) {
1465 lastIndex = regexp.lastIndex;
1467 regexp.lastIndex = lastIndex;
1468 if (match[0].length == 0 || !regexp.global)
1474 rehash: function (args) {
1475 JSMLoader.commandlineArgs = args;
1476 this.timeout(function () {
1477 this.rehashing = true;
1478 let addon = config.addon;
1479 addon.userDisabled = true;
1480 addon.userDisabled = false;
1485 errors: Class.memoize(function () []),
1487 reportError: function (error) {
1491 if (isString(error))
1492 error = Error(error);
1495 Cu.reportError(error);
1500 let obj = update({}, error, {
1501 toString: function () String(error),
1502 stack: <>{util.stackLines(String(error.stack || Error().stack)).join("\n").replace(/^/mg, "\t")}</>
1505 this.errors.push([new Date, obj + "\n" + obj.stack]);
1506 this.errors = this.errors.slice(-this.maxErrors);
1507 this.errors.toString = function () [k + "\n" + v for ([k, v] in array.iterValues(this))].join("\n\n");
1509 this.dump(String(error));
1515 this.dump(String(error));
1516 this.dump(util.stackLines(error.stack).join("\n"));
1518 catch (e) { dump(e + "\n"); }
1521 // ctypes.open("libc.so.6").declare("kill", ctypes.default_abi, ctypes.void_t, ctypes.int, ctypes.int)(
1522 // ctypes.open("libc.so.6").declare("getpid", ctypes.default_abi, ctypes.int)(), 2)
1526 * Given a domain, returns an array of all non-toplevel subdomains
1529 * @param {string} host The host for which to find subdomains.
1530 * @returns {[string]}
1532 subdomains: function subdomains(host) {
1533 if (/(^|\.)\d+$|:.*:/.test(host))
1534 // IP address or similar
1537 let base = host.replace(/.*\.(.+?\..+?)$/, "$1");
1539 base = services.tld.getBaseDomainFromHost(host);
1543 let ary = host.split(".");
1544 ary = [ary.slice(i).join(".") for (i in util.range(ary.length - 1, 0, -1))];
1545 return ary.filter(function (h) h.length >= base.length);
1549 * Scrolls an element into view if and only if it's not already
1552 * @param {Node} elem The element to make visible.
1554 scrollIntoView: function scrollIntoView(elem, alignWithTop) {
1555 let win = elem.ownerDocument.defaultView;
1556 let rect = elem.getBoundingClientRect();
1557 if (!(rect && rect.bottom <= win.innerHeight && rect.top >= 0 && rect.left < win.innerWidth && rect.right > 0))
1558 elem.scrollIntoView(arguments.length > 1 ? alignWithTop : Math.abs(rect.top) < Math.abs(win.innerHeight - rect.bottom));
1562 * Returns the selection controller for the given window.
1564 * @param {Window} window
1565 * @returns {nsISelectionController}
1567 selectionController: function (win)
1568 win.QueryInterface(Ci.nsIInterfaceRequestor).getInterface(Ci.nsIWebNavigation)
1569 .QueryInterface(Ci.nsIInterfaceRequestor).getInterface(Ci.nsISelectionDisplay)
1570 .QueryInterface(Ci.nsISelectionController),
1573 * Suspend execution for at least *delay* milliseconds. Functions by
1574 * yielding execution to the next item in the main event queue, and
1575 * so may lead to unexpected call graphs, and long delays if another
1576 * handler yields execution while waiting.
1578 * @param {number} delay The time period for which to sleep in milliseconds.
1580 sleep: function (delay) {
1581 let mainThread = services.threading.mainThread;
1583 let end = Date.now() + delay;
1584 while (Date.now() < end)
1585 mainThread.processNextEvent(true);
1589 highlightFilter: function highlightFilter(str, filter, highlight) {
1590 return this.highlightSubstrings(str, (function () {
1591 if (filter.length == 0)
1593 let lcstr = String.toLowerCase(str);
1594 let lcfilter = filter.toLowerCase();
1596 while ((start = lcstr.indexOf(lcfilter, start)) > -1) {
1597 yield [start, filter.length];
1598 start += filter.length;
1600 })(), highlight || template.filter);
1604 * Behaves like String.split, except that when *limit* is reached,
1605 * the trailing element contains the entire trailing portion of the
1608 * util.split("a, b, c, d, e", /, /, 3) -> ["a", "b", "c, d, e"]
1610 * @param {string} str The string to split.
1611 * @param {RegExp|string} re The regular expression on which to split the string.
1612 * @param {number} limit The maximum number of elements to return.
1613 * @returns {[string]}
1615 split: function (str, re, limit) {
1618 re = RegExp(re.source || re, "g");
1619 let match, start = 0, res = [];
1620 while (--limit && (match = re.exec(str)) && match[0].length) {
1621 res.push(str.substring(start, match.index));
1622 start = match.index + match[0].length;
1624 res.push(str.substring(start));
1629 * Split a string on literal occurrences of a marker.
1631 * Specifically this ignores occurrences preceded by a backslash, or
1632 * contained within 'single' or "double" quotes.
1634 * It assumes backslash escaping on strings, and will thus not count quotes
1635 * that are preceded by a backslash or within other quotes as starting or
1636 * ending quoted sections of the string.
1638 * @param {string} str
1639 * @param {RegExp} marker
1640 * @returns {[string]}
1642 splitLiteral: function splitLiteral(str, marker) {
1644 let resep = RegExp(/^(([^\\'"]|\\.|'([^\\']|\\.)*'|"([^\\"]|\\.)*")*?)/.source + marker.source);
1649 str = str.replace(resep, function (match, before) {
1650 results.push(before);
1651 cont = match !== "";
1661 threadYield: function (flush, interruptable) {
1664 let mainThread = services.threading.mainThread;
1666 util.interrupted = false;
1668 mainThread.processNextEvent(!flush);
1669 if (util.interrupted)
1670 throw new Error("Interrupted");
1672 while (flush === true && mainThread.hasPendingEvents());
1679 waitFor: function waitFor(test, self, timeout, interruptable) {
1680 let end = timeout && Date.now() + timeout, result;
1682 let timer = services.Timer(function () {}, 10, services.Timer.TYPE_REPEATING_SLACK);
1684 while (!(result = test.call(self)) && (!end || Date.now() < end))
1685 this.threadYield(false, interruptable);
1693 yieldable: function yieldable(func)
1695 let gen = func.apply(this, arguments);
1698 util.timeout(next, gen.next());
1700 catch (e if e instanceof StopIteration) {};
1704 wrapCallback: wrapCallback,
1707 * Returns the top-level chrome window for the given window.
1709 * @param {Window} win The child window.
1710 * @returns {Window} The top-level parent window.
1712 topWindow: function topWindow(win)
1713 win.QueryInterface(Ci.nsIInterfaceRequestor).getInterface(Ci.nsIWebNavigation)
1714 .QueryInterface(Ci.nsIDocShellTreeItem).rootTreeItem
1715 .QueryInterface(Ci.nsIInterfaceRequestor).getInterface(Ci.nsIDOMWindow),
1718 * Traps errors in the called function, possibly reporting them.
1720 * @param {function} func The function to call
1721 * @param {object} self The 'this' object for the function.
1723 trapErrors: function trapErrors(func, self) {
1727 return func.apply(self || this, Array.slice(arguments, 2));
1730 util.reportError(e);
1735 urlPath: function urlPath(url) {
1737 return util.getFile(url).path;
1744 visibleHosts: function (win) {
1745 let res = [], seen = {};
1746 (function rec(frame) {
1748 res = res.concat(util.subdomains(frame.location.host));
1751 Array.forEach(frame.frames, rec);
1753 return res.filter(function (h) !set.add(seen, h));
1756 visibleURIs: function (win) {
1757 let res = [], seen = {};
1758 (function rec(frame) {
1760 res = res.concat(util.newURI(frame.location.href));
1763 Array.forEach(frame.frames, rec);
1765 return res.filter(function (h) !set.add(seen, h.spec));
1769 * Converts an E4X XML literal to a DOM node. Any attribute named
1770 * highlight is present, it is transformed into dactyl:highlight,
1771 * and the named highlight groups are guaranteed to be loaded.
1773 * @param {Node} node
1774 * @param {Document} doc
1775 * @param {Object} nodes If present, nodes with the "key" attribute are
1776 * stored here, keyed to the value thereof.
1779 xmlToDom: function xmlToDom(node, doc, nodes) {
1780 XML.prettyPrinting = false;
1781 if (typeof node === "string") // Sandboxes can't currently pass us XML objects.
1784 if (node.length() != 1) {
1785 let domnode = doc.createDocumentFragment();
1786 for each (let child in node)
1787 domnode.appendChild(xmlToDom(child, doc, nodes));
1791 switch (node.nodeKind()) {
1793 return doc.createTextNode(String(node));
1795 let domnode = doc.createElementNS(node.namespace(), node.localName());
1797 for each (let attr in node.@*::*)
1798 if (attr.name() != "highlight")
1799 domnode.setAttributeNS(attr.namespace(), attr.localName(), String(attr));
1801 for each (let child in node.*::*)
1802 domnode.appendChild(xmlToDom(child, doc, nodes));
1803 if (nodes && node.@key)
1804 nodes[node.@key] = domnode;
1806 if ("@highlight" in node)
1807 highlight.highlightNode(domnode, String(node.@highlight), nodes || true);
1818 * Math utility methods.
1821 var GlobalMath = Math;
1822 var Math = update(Object.create(GlobalMath), {
1824 * Returns the specified *value* constrained to the range *min* - *max*.
1826 * @param {number} value The value to constrain.
1827 * @param {number} min The minimum constraint.
1828 * @param {number} max The maximum constraint.
1831 constrain: function constrain(value, min, max) Math.min(Math.max(min, value), max)
1836 } catch(e){ if (!e.stack) e = Error(e); dump(e.fileName+":"+e.lineNumber+": "+e+"\n" + e.stack); }
1838 // vim: set fdm=marker sw=4 ts=4 et ft=javascript: