2 * (C) Copyright 2004-2007 Shawn Betts
3 * (C) Copyright 2007-2010 John J. Foerch
4 * (C) Copyright 2007-2008 Jeremy Maitin-Shepard
6 * Use, modification, and distribution are subject to the terms specified in the
14 function string_hashset () {}
15 string_hashset.prototype = {
16 constructor: string_hashset,
22 contains: function (s) {
23 return (("-" + s) in this);
26 remove: function (s) {
30 for_each: function (f) {
37 iterator: function () {
45 function string_hashmap () {}
46 string_hashmap.prototype = {
47 constructor: string_hashmap,
49 put: function (s,value) {
50 this["-" + s] = value;
53 contains: function (s) {
54 return (("-" + s) in this);
57 get: function (s, default_value) {
63 get_put_default: function (s, default_value) {
66 return (this["-" + s] = default_value);
69 remove: function (s) {
73 for_each: function (f) {
76 f(i.slice(1), this[i]);
80 for_each_value: function (f) {
87 iterator: function (only_keys) {
89 for (let k in Iterator(this, true)) {
94 for (let [k,v] in Iterator(this, false)) {
103 // Put the string on the clipboard
104 function writeToClipboard (str) {
105 var gClipboardHelper = Cc["@mozilla.org/widget/clipboardhelper;1"]
106 .getService(Ci.nsIClipboardHelper);
107 gClipboardHelper.copyString(str);
111 function makeURLAbsolute (base, url) {
113 var ioService = Cc["@mozilla.org/network/io-service;1"]
114 .getService(Ci.nsIIOService);
115 var baseURI = ioService.newURI(base, null, null);
116 return ioService.newURI(baseURI.resolve(url), null, null).spec;
120 function make_file (path) {
121 if (path instanceof Ci.nsILocalFile)
124 return get_home_directory();
126 path = path.replace("/", "\\", "g");
127 if ((POSIX && path.substring(0,2) == "~/") ||
128 (WINDOWS && path.substring(0,2) == "~\\"))
130 var f = get_home_directory();
131 f.appendRelativePath(path.substring(2));
133 f = Cc["@mozilla.org/file/local;1"]
134 .createInstance(Ci.nsILocalFile);
135 f.initWithPath(path);
141 function make_file_from_chrome (url) {
142 var crs = Cc['@mozilla.org/chrome/chrome-registry;1']
143 .getService(Ci.nsIChromeRegistry);
144 var file = crs.convertChromeURL(make_uri(url));
145 return make_file(file.path);
148 function get_document_content_disposition (document_o) {
149 var content_disposition = null;
151 content_disposition = document_o.defaultView
152 .QueryInterface(Components.interfaces.nsIInterfaceRequestor)
153 .getInterface(Components.interfaces.nsIDOMWindowUtils)
154 .getDocumentMetadata("content-disposition");
156 return content_disposition;
160 function set_focus_no_scroll (window, element) {
161 window.document.commandDispatcher.suppressFocusScroll = true;
163 window.document.commandDispatcher.suppressFocusScroll = false;
166 function do_repeatedly_positive (func, n) {
167 var args = Array.prototype.slice.call(arguments, 2);
169 func.apply(null, args);
172 function do_repeatedly (func, n, positive_args, negative_args) {
174 do func.apply(null, negative_args); while (++n < 0);
176 while (n-- > 0) func.apply(null, positive_args);
181 * Given a node, returns its position relative to the document.
183 * @param node The node to get the position of.
184 * @return An object with properties "x" and "y" representing its offset from
185 * the left and top of the document, respectively.
187 function abs_point (node) {
191 pt.x = node.offsetLeft;
192 pt.y = node.offsetTop;
193 // find imagemap's coordinates
194 if (node.tagName == "AREA") {
195 var coords = node.getAttribute("coords").split(",");
196 pt.x += Number(coords[0]);
197 pt.y += Number(coords[1]);
200 node = node.offsetParent;
201 // Sometimes this fails, so just return what we got.
203 while (node.tagName != "BODY") {
204 pt.x += node.offsetLeft;
205 pt.y += node.offsetTop;
206 node = node.offsetParent;
210 // while (node.tagName != "BODY") {
211 // alert("okay: " + node + " " + node.tagName + " " + pt.x + " " + pt.y);
212 // node = node.offsetParent;
219 const XHTML_NS = "http://www.w3.org/1999/xhtml";
220 const XUL_NS = "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul";
221 const MATHML_NS = "http://www.w3.org/1998/Math/MathML";
222 const XLINK_NS = "http://www.w3.org/1999/xlink";
223 const SVG_NS = "http://www.w3.org/2000/svg";
225 function create_XUL (window, tag_name) {
226 return window.document.createElementNS(XUL_NS, tag_name);
230 /* Used in calls to XPath evaluate */
231 function xpath_lookup_namespace (prefix) {
240 function method_caller (obj, func) {
242 func.apply(obj, arguments);
247 function get_window_from_frame (frame) {
249 var window = frame.QueryInterface(Ci.nsIInterfaceRequestor)
250 .getInterface(Ci.nsIWebNavigation)
251 .QueryInterface(Ci.nsIDocShellTreeItem)
253 .QueryInterface(Ci.nsIInterfaceRequestor)
254 .getInterface(Ci.nsIDOMWindow).wrappedJSObject;
255 /* window is now an XPCSafeJSObjectWrapper */
256 window.escape_wrapper(function (w) { window = w; });
257 /* window is now completely unwrapped */
264 function get_buffer_from_frame (window, frame) {
265 var count = window.buffers.count;
266 for (var i = 0; i < count; ++i) {
267 var b = window.buffers.get_buffer(i);
268 if (b.top_frame == frame.top)
275 function dom_generator (document, ns) {
276 this.document = document;
279 dom_generator.prototype = {
280 constructor: dom_generator,
281 element: function (tag, parent) {
282 var node = this.document.createElementNS(this.ns, tag);
284 if (parent != null && (parent instanceof Ci.nsIDOMNode)) {
285 parent.appendChild(node);
288 for (var nargs = arguments.length; i < nargs; i += 2)
289 node.setAttribute(arguments[i], arguments[i+1]);
293 text: function (str, parent) {
294 var node = this.document.createTextNode(str);
296 parent.appendChild(node);
301 stylesheet_link: function (href, parent) {
302 var node = this.element("link");
303 node.setAttribute("rel", "stylesheet");
304 node.setAttribute("type", "text/css");
305 node.setAttribute("href", href);
307 parent.appendChild(node);
312 add_stylesheet: function (url) {
313 var head = this.document.documentElement.firstChild;
314 this.stylesheet_link(url, head);
319 * Generates a QueryInterface function suitable for an implemenation
320 * of an XPCOM interface. Unlike XPCOMUtils, this uses the Function
321 * constructor to generate a slightly more efficient version. The
322 * arguments can be either Strings or elements of
323 * Components.interfaces.
325 function generate_QI () {
326 var args = Array.prototype.slice.call(arguments).map(String).concat(["nsISupports"]);
328 Array.prototype.map.call(args, function (x) {
329 return "iid.equals(Components.interfaces." + x + ")";
332 ") return this; throw Components.results.NS_ERROR_NO_INTERFACE;";
333 return new Function("iid", fstr);
337 function abort (str) {
338 var e = new Error(str);
339 e.__proto__ = abort.prototype;
342 abort.prototype.__proto__ = Error.prototype;
345 function get_temporary_file (name) {
348 var file = file_locator_service.get("TmpD", Ci.nsIFile);
350 // Create the file now to ensure that no exploits are possible
351 file.createUnique(Ci.nsIFile.NORMAL_FILE_TYPE, 0600);
356 /* FIXME: This should be moved somewhere else, perhaps. */
357 function create_info_panel (window, panel_class, row_arr) {
358 /* Show information panel above minibuffer */
360 var g = new dom_generator(window.document, XUL_NS);
362 var p = g.element("vbox", "class", "panel " + panel_class, "flex", "0");
363 var grid = g.element("grid", p);
364 var cols = g.element("columns", grid);
365 g.element("column", cols, "flex", "0");
366 g.element("column", cols, "flex", "1");
368 var rows = g.element("rows", grid);
371 for each (let [row_class, row_label, row_value] in row_arr) {
372 row = g.element("row", rows, "class", row_class);
373 g.element("label", row,
375 "class", "panel-row-label");
376 g.element("label", row,
378 "class", "panel-row-value",
381 window.minibuffer.insert_before(p);
383 p.destroy = function () {
384 this.parentNode.removeChild(this);
392 * Paste from the X primary selection, unless the system doesn't support a
393 * primary selection, in which case fall back to the clipboard.
395 function read_from_x_primary_selection () {
397 let clipboard = Components.classes["@mozilla.org/widget/clipboard;1"]
398 .getService(Components.interfaces.nsIClipboard);
400 // Fall back to global clipboard if the system doesn't support a selection
401 let which_clipboard = clipboard.supportsSelectionClipboard() ?
402 clipboard.kSelectionClipboard : clipboard.kGlobalClipboard;
404 let flavors = ["text/unicode"];
406 // Don't barf if there's nothing on the clipboard
407 if (!clipboard.hasDataMatchingFlavors(flavors, flavors.length, which_clipboard))
410 // Create transferable that will transfer the text.
411 let trans = Components.classes["@mozilla.org/widget/transferable;1"]
412 .createInstance(Components.interfaces.nsITransferable);
414 for each (let flavor in flavors) {
415 trans.addDataFlavor(flavor);
417 clipboard.getData(trans, which_clipboard);
419 var data_flavor = {};
422 trans.getAnyTransferData(data_flavor, data, dataLen);
425 data = data.value.QueryInterface(Components.interfaces.nsISupportsString);
426 let data_length = dataLen.value;
427 if (data_flavor.value == "text/unicode")
428 data_length = dataLen.value / 2;
429 return data.data.substring(0, data_length);
436 function predicate_alist_match (alist, key) {
437 for each (let i in alist) {
445 function get_meta_title (doc) {
446 var title = doc.evaluate("//meta[@name='title']/@content", doc, xpath_lookup_namespace,
447 Ci.nsIDOMXPathResult.STRING_TYPE , null);
448 if (title && title.stringValue)
449 return title.stringValue;
461 return this.input.length + this.output.length;
464 this.input[this.input.length] = x;
467 let l = this.output.length;
469 l = this.input.length;
472 this.output = this.input.reverse();
474 let x = this.output[l];
475 this.output.length--;
481 function frame_iterator (root_frame, start_with) {
482 var q = new queue, x;
487 for (let i = 0, nframes = x.frames.length; i < nframes; ++i)
489 } while ((x = q.pop()));
496 for (let i = 0, nframes = x.frames.length; i < nframes; ++i)
498 } while ((x = q.pop()));
501 function xml_http_request () {
502 return Cc["@mozilla.org/xmlextras/xmlhttprequest;1"]
503 .createInstance(Ci.nsIXMLHttpRequest)
504 .QueryInterface(Ci.nsIJSXMLHttpRequest)
505 .QueryInterface(Ci.nsIDOMEventTarget);
508 var xml_http_request_load_listener = {
509 // nsIBadCertListener2
510 notifyCertProblem: function SSLL_certProblem (socketInfo, status, targetSite) {
514 // nsISSLErrorListener
515 notifySSLError: function SSLL_SSLError (socketInfo, error, targetSite) {
519 // nsIInterfaceRequestor
520 getInterface: function SSLL_getInterface (iid) {
521 return this.QueryInterface(iid);
526 // FIXME: array comprehension used here to hack around the lack of
527 // Ci.nsISSLErrorListener in 2007 versions of xulrunner 1.9pre.
528 // make it a simple generateQI when xulrunner is more stable.
529 QueryInterface: XPCOMUtils.generateQI(
530 [i for each (i in [Ci.nsIBadCertListener2,
531 Ci.nsISSLErrorListener,
532 Ci.nsIInterfaceRequestor])
538 * Coroutine interface for sending an HTTP request and waiting for the
539 * response. (This includes so-called "AJAX" requests.)
541 * @param lspec (required) a load_spec object or URI string (see load-spec.js)
543 * The request URI is obtained from this argument. In addition, if the
544 * load spec specifies post data, a POST request is made instead of a
545 * GET request, and the post data included in the load spec is
546 * sent. Specifically, the request_mime_type and raw_post_data
547 * properties of the load spec are used.
549 * @param $user (optional) HTTP user name to include in the request headers
550 * @param $password (optional) HTTP password to include in the request headers
552 * @param $override_mime_type (optional) Force the response to be interpreted
553 * as having the specified MIME type. This is only
554 * really useful for forcing the MIME type to be
555 * text/xml or something similar, such that it is
556 * automatically parsed into a DOM document.
557 * @param $headers (optional) an array of [name,value] pairs (each specified as
558 * a two-element array) specifying additional headers to add to
561 * @returns After the request completes (either successfully or with an error),
562 * the nsIXMLHttpRequest object is returned. Its responseText (for any
563 * arbitrary document) or responseXML (if the response type is an XML
564 * content type) properties can be accessed to examine the response
567 * If an exception is thrown to the continutation (which can be obtained by the
568 * caller by calling yield CONTINUATION prior to calling this function) while the
569 * request is in progress (i.e. before this coroutine returns), the request will
570 * be aborted, and the exception will be propagated to the caller.
573 define_keywords("$user", "$password", "$override_mime_type", "$headers");
574 function send_http_request (lspec) {
575 // why do we get warnings in jsconsole unless we initialize the
576 // following keywords?
577 keywords(arguments, $user = undefined, $password = undefined,
578 $override_mime_type = undefined, $headers = undefined);
579 if (! (lspec instanceof load_spec))
580 lspec = load_spec(lspec);
581 var req = xml_http_request();
582 var cc = yield CONTINUATION;
583 var aborting = false;
584 req.onreadystatechange = function send_http_request__onreadystatechange () {
585 if (req.readyState != 4)
592 if (arguments.$override_mime_type)
593 req.overrideMimeType(arguments.$override_mime_type);
595 var post_data = load_spec_raw_post_data(lspec);
597 var method = post_data ? "POST" : "GET";
599 req.open(method, load_spec_uri_string(lspec), true, arguments.$user, arguments.$password);
600 req.channel.notificationCallbacks = xml_http_request_load_listener;
602 for each (let [name,value] in arguments.$headers) {
603 req.setRequestHeader(name, value);
607 req.setRequestHeader("Content-Type", load_spec_request_mime_type(lspec));
620 // Let the caller access the status and reponse data
621 yield co_return(req);
626 * scroll_selection_into_view takes an editable element, and scrolls it so
627 * that the selection (or insertion point) are visible.
629 function scroll_selection_into_view (field) {
630 if (field.namespaceURI == XUL_NS)
631 field = field.inputField;
633 field.QueryInterface(Ci.nsIDOMNSEditableElement)
636 .scrollSelectionIntoView(
637 Ci.nsISelectionController.SELECTION_NORMAL,
638 Ci.nsISelectionController.SELECTION_FOCUS_REGION,
641 // we'll get here for richedit fields
647 * build_url_regex builds a regular expression to match URLs for a given
650 * Both the $domain and $path arguments can be either regexes, in
651 * which case they will be matched as is, or strings, in which case
652 * they will be matched literally.
654 * $tlds specifies a list of valid top-level-domains to match, and
655 * defaults to .com. Useful for when e.g. foo.org and foo.com are the
658 * If $allow_www is true, www.domain.tld will also be allowed.
660 define_keywords("$domain", "$path", "$tlds", "$allow_www");
661 function build_url_regex () {
662 function regex_to_string (obj) {
663 if (typeof obj == "object" && "source" in obj)
665 return quotemeta(obj);
668 keywords(arguments, $path = "", $tlds = ["com"], $allow_www = false);
669 var domain = regex_to_string(arguments.$domain);
670 if(arguments.$allow_www) {
671 domain = "(?:www\.)?" + domain;
673 var path = regex_to_string(arguments.$path);
674 var tlds = arguments.$tlds;
675 var regex = "^https?://" + domain + "\\." + choice_regex(tlds) + "/" + path;
676 return new RegExp(regex);
680 function compute_url_up_path (url) {
681 var new_url = Cc["@mozilla.org/network/standard-url;1"]
682 .createInstance (Ci.nsIURL);
685 if (new_url.param != "" || new_url.query != "")
686 up = new_url.filePath;
687 else if (new_url.fileName != "")
695 function url_path_trim (url) {
696 var uri = make_uri(url);
702 /* possibly_valid_url returns true if the string might be a valid
703 * thing to pass to nsIWebNavigation.loadURI. Currently just checks
704 * that there's no whitespace in the middle and that it's not entirely
707 function possibly_valid_url (url) {
708 return !(/\S\s+\S/.test(url)) && !(/^\s*$/.test(url));
713 * Convenience function for making simple XPath lookups in a document.
715 * @param doc The document to look in.
716 * @param exp The XPath expression to search for.
717 * @return The XPathResult object representing the set of found nodes.
719 function xpath_lookup (doc, exp) {
720 return doc.evaluate(exp, doc, null, Ci.nsIDOMXPathResult.ANY_TYPE, null);
724 /* get_contents_synchronously returns the contents of the given
725 * url (string or nsIURI) as a string on success, or null on failure.
727 function get_contents_synchronously (url) {
728 var ioService=Cc["@mozilla.org/network/io-service;1"]
729 .getService(Ci.nsIIOService);
730 var scriptableStream=Cc["@mozilla.org/scriptableinputstream;1"]
731 .getService(Ci.nsIScriptableInputStream);
735 if (url instanceof Ci.nsIURI)
736 channel = ioService.newChannelFromURI(url);
738 channel = ioService.newChannel(url, null, null);
739 input=channel.open();
743 scriptableStream.init(input);
744 var str=scriptableStream.read(input.available());
745 scriptableStream.close();
752 * dom_add_class adds a css class to the given dom node.
754 function dom_add_class (node, cssclass) {
755 if (node.className) {
756 var cs = node.className.split(" ");
757 if (cs.indexOf(cssclass) != -1)
760 node.className = cs.join(" ");
762 node.className = cssclass;
766 * dom_remove_class removes the given css class from the given dom node.
768 function dom_remove_class (node, cssclass) {
769 if (! node.className)
771 var classes = node.className.split(" ");
772 classes = classes.filter(function (x) { return x != cssclass; });
773 node.className = classes.join(" ");
778 * dom_node_flash adds the given cssclass to the node for a brief interval.
779 * this class can be styled, to create a flashing effect.
781 function dom_node_flash (node, cssclass) {
782 dom_add_class(node, cssclass);
785 dom_remove_class(node, cssclass);
792 * data is an an alist (array of 2 element arrays) where each pair is a key
795 * The return type is a mime input stream that can be passed as postData to
796 * nsIWebNavigation.loadURI. In terms of Conkeror's API, the return value
797 * of this function is of the correct type for the `post_data' field of a
800 function make_post_data (data) {
801 data = [(encodeURIComponent(pair[0])+'='+encodeURIComponent(pair[1]))
802 for each (pair in data)].join('&');
803 data = string_input_stream(data);
804 return mime_input_stream(
805 data, [["Content-Type", "application/x-www-form-urlencoded"]]);
810 * Centers the viewport around a given element.
812 * @param win The window to scroll.
813 * @param elem The element arund which we put the viewport.
815 function center_in_viewport (win, elem) {
816 let point = abs_point(elem);
818 point.x -= win.innerWidth / 2;
819 point.y -= win.innerHeight / 2;
821 win.scrollTo(point.x, point.y);
826 * Simple predicate returns true if elem is an nsIDOMNode or
829 function element_dom_node_or_window_p (elem) {
830 if (elem instanceof Ci.nsIDOMNode)
832 if (elem instanceof Ci.nsIDOMWindow)
838 * Given a hook name, a buffer and a function, waits until the buffer document
839 * has fully loaded, then calls the function with the buffer as its only
842 * @param {String} The hook name.
843 * @param {buffer} The buffer.
844 * @param {function} The function to call with the buffer as its argument once
845 * the buffer has loaded.
847 function do_when (hook, buffer, fun) {
848 if (buffer.browser.webProgress.isLoadingDocument)
849 add_hook.call(buffer, hook, fun);
856 * evaluate string s as javascript in the 'this' scope in which evaluate
859 function evaluate (s) {
861 var temp = get_temporary_file("conkeror-evaluate.tmp.js");
862 write_text_file(temp, s);
863 var url = make_uri(temp).spec;
864 return load_url(url, this);
866 if (temp && temp.exists())