2 * (C) Copyright 2004-2007 Shawn Betts
3 * (C) Copyright 2007-2011 John J. Foerch
4 * (C) Copyright 2007-2008 Jeremy Maitin-Shepard
6 * Use, modification, and distribution are subject to the terms specified in the
12 // Put the string on the clipboard
13 function writeToClipboard (str) {
14 var gClipboardHelper = Cc["@mozilla.org/widget/clipboardhelper;1"]
15 .getService(Ci.nsIClipboardHelper);
16 gClipboardHelper.copyString(str);
20 function makeURLAbsolute (base, url) {
22 var ioService = Cc["@mozilla.org/network/io-service;1"]
23 .getService(Ci.nsIIOService);
24 var baseURI = ioService.newURI(base, null, null);
25 return ioService.newURI(baseURI.resolve(url), null, null).spec;
29 function make_file (path) {
30 if (path instanceof Ci.nsILocalFile)
33 return get_home_directory();
35 path = path.replace("/", "\\", "g");
36 if ((POSIX && path.substring(0,2) == "~/") ||
37 (WINDOWS && path.substring(0,2) == "~\\"))
39 var f = get_home_directory();
40 f.appendRelativePath(path.substring(2));
42 f = Cc["@mozilla.org/file/local;1"]
43 .createInstance(Ci.nsILocalFile);
50 function make_file_from_chrome (url) {
51 var crs = Cc['@mozilla.org/chrome/chrome-registry;1']
52 .getService(Ci.nsIChromeRegistry);
53 var file = crs.convertChromeURL(make_uri(url));
54 return make_file(file.path);
57 function get_document_content_disposition (document_o) {
58 var content_disposition = null;
60 content_disposition = document_o.defaultView
61 .QueryInterface(Components.interfaces.nsIInterfaceRequestor)
62 .getInterface(Components.interfaces.nsIDOMWindowUtils)
63 .getDocumentMetadata("content-disposition");
65 return content_disposition;
69 function set_focus_no_scroll (window, element) {
70 window.document.commandDispatcher.suppressFocusScroll = true;
72 window.document.commandDispatcher.suppressFocusScroll = false;
75 function do_repeatedly_positive (func, n) {
76 var args = Array.prototype.slice.call(arguments, 2);
78 func.apply(null, args);
81 function do_repeatedly (func, n, positive_args, negative_args) {
83 do func.apply(null, negative_args); while (++n < 0);
85 while (n-- > 0) func.apply(null, positive_args);
90 * Given a node, returns its position relative to the document.
92 * @param node The node to get the position of.
93 * @return An object with properties "x" and "y" representing its offset from
94 * the left and top of the document, respectively.
96 function abs_point (node) {
100 pt.x = node.offsetLeft;
101 pt.y = node.offsetTop;
102 // find imagemap's coordinates
103 if (node.tagName == "AREA") {
104 var coords = node.getAttribute("coords").split(",");
105 pt.x += Number(coords[0]);
106 pt.y += Number(coords[1]);
109 node = node.offsetParent;
110 // Sometimes this fails, so just return what we got.
112 while (node.tagName != "BODY") {
113 pt.x += node.offsetLeft;
114 pt.y += node.offsetTop;
115 node = node.offsetParent;
119 // while (node.tagName != "BODY") {
120 // alert("okay: " + node + " " + node.tagName + " " + pt.x + " " + pt.y);
121 // node = node.offsetParent;
128 const XHTML_NS = "http://www.w3.org/1999/xhtml";
129 const XUL_NS = "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul";
130 const MATHML_NS = "http://www.w3.org/1998/Math/MathML";
131 const XLINK_NS = "http://www.w3.org/1999/xlink";
132 const SVG_NS = "http://www.w3.org/2000/svg";
134 function create_XUL (window, tag_name) {
135 return window.document.createElementNS(XUL_NS, tag_name);
139 /* Used in calls to XPath evaluate */
140 function xpath_lookup_namespace (prefix) {
149 function method_caller (obj, func) {
151 func.apply(obj, arguments);
156 function get_window_from_frame (frame) {
158 var window = frame.QueryInterface(Ci.nsIInterfaceRequestor)
159 .getInterface(Ci.nsIWebNavigation)
160 .QueryInterface(Ci.nsIDocShellTreeItem)
162 .QueryInterface(Ci.nsIInterfaceRequestor)
163 .getInterface(Ci.nsIDOMWindow).wrappedJSObject;
164 /* window is now an XPCSafeJSObjectWrapper */
165 window.escape_wrapper(function (w) { window = w; });
166 /* window is now completely unwrapped */
173 function get_buffer_from_frame (window, frame) {
174 var count = window.buffers.count;
175 for (var i = 0; i < count; ++i) {
176 var b = window.buffers.get_buffer(i);
177 if (b.top_frame == frame.top)
184 function dom_generator (document, ns) {
185 this.document = document;
188 dom_generator.prototype = {
189 constructor: dom_generator,
190 element: function (tag, parent) {
191 var node = this.document.createElementNS(this.ns, tag);
193 if (parent != null && (parent instanceof Ci.nsIDOMNode)) {
194 parent.appendChild(node);
197 for (var nargs = arguments.length; i < nargs; i += 2)
198 node.setAttribute(arguments[i], arguments[i+1]);
202 text: function (str, parent) {
203 var node = this.document.createTextNode(str);
205 parent.appendChild(node);
210 stylesheet_link: function (href, parent) {
211 var node = this.element("link");
212 node.setAttribute("rel", "stylesheet");
213 node.setAttribute("type", "text/css");
214 node.setAttribute("href", href);
216 parent.appendChild(node);
221 add_stylesheet: function (url) {
222 var head = this.document.documentElement.firstChild;
223 this.stylesheet_link(url, head);
228 * Generates a QueryInterface function suitable for an implemenation
229 * of an XPCOM interface. Unlike XPCOMUtils, this uses the Function
230 * constructor to generate a slightly more efficient version. The
231 * arguments can be either Strings or elements of
232 * Components.interfaces.
234 function generate_QI () {
235 var args = Array.prototype.slice.call(arguments).map(String).concat(["nsISupports"]);
237 Array.prototype.map.call(args, function (x) {
238 return "iid.equals(Components.interfaces." + x + ")";
241 ") return this; throw Components.results.NS_ERROR_NO_INTERFACE;";
242 return new Function("iid", fstr);
246 function abort (str) {
247 var e = new Error(str);
248 e.__proto__ = abort.prototype;
251 abort.prototype.__proto__ = Error.prototype;
254 function get_temporary_file (name) {
257 var file = file_locator_service.get("TmpD", Ci.nsIFile);
259 // Create the file now to ensure that no exploits are possible
260 file.createUnique(Ci.nsIFile.NORMAL_FILE_TYPE, 0600);
265 /* FIXME: This should be moved somewhere else, perhaps. */
266 function create_info_panel (window, panel_class, row_arr) {
267 /* Show information panel above minibuffer */
269 var g = new dom_generator(window.document, XUL_NS);
271 var p = g.element("vbox", "class", "panel " + panel_class, "flex", "0");
272 var grid = g.element("grid", p);
273 var cols = g.element("columns", grid);
274 g.element("column", cols, "flex", "0");
275 g.element("column", cols, "flex", "1");
277 var rows = g.element("rows", grid);
280 for each (let [row_class, row_label, row_value] in row_arr) {
281 row = g.element("row", rows, "class", row_class);
282 g.element("label", row,
284 "class", "panel-row-label");
285 g.element("label", row,
287 "class", "panel-row-value",
290 window.minibuffer.insert_before(p);
292 p.destroy = function () {
293 this.parentNode.removeChild(this);
301 * Return clipboard contents as string. When which_clipboard is given, it
302 * may be an nsIClipboard constant specifying which clipboard to use.
304 function read_from_clipboard (which_clipboard) {
305 var clipboard = Cc["@mozilla.org/widget/clipboard;1"]
306 .getService(Ci.nsIClipboard);
307 if (which_clipboard == null)
308 which_clipboard = clipboard.kGlobalClipboard;
310 var flavors = ["text/unicode"];
312 // Don't barf if there's nothing on the clipboard
313 if (!clipboard.hasDataMatchingFlavors(flavors, flavors.length, which_clipboard))
316 // Create transferable that will transfer the text.
317 var trans = Cc["@mozilla.org/widget/transferable;1"]
318 .createInstance(Ci.nsITransferable);
320 for each (let flavor in flavors) {
321 trans.addDataFlavor(flavor);
323 clipboard.getData(trans, which_clipboard);
325 var data_flavor = {};
328 trans.getAnyTransferData(data_flavor, data, dataLen);
331 data = data.value.QueryInterface(Ci.nsISupportsString);
332 var data_length = dataLen.value;
333 if (data_flavor.value == "text/unicode")
334 data_length = dataLen.value / 2;
335 return data.data.substring(0, data_length);
342 * Return selection clipboard contents as a string, or regular clipboard
343 * contents if the system does not support a selection clipboard.
345 function read_from_x_primary_selection () {
346 var clipboard = Cc["@mozilla.org/widget/clipboard;1"]
347 .getService(Ci.nsIClipboard);
348 // fall back to global clipboard if the
349 // system doesn't support a selection
350 var which_clipboard = clipboard.supportsSelectionClipboard() ?
351 clipboard.kSelectionClipboard : clipboard.kGlobalClipboard;
352 return read_from_clipboard(which_clipboard);
356 function predicate_alist_match (alist, key) {
357 for each (let i in alist) {
358 if (i[0] instanceof RegExp) {
361 } else if (i[0](key))
368 function get_meta_title (doc) {
369 var title = doc.evaluate("//meta[@name='title']/@content", doc, xpath_lookup_namespace,
370 Ci.nsIDOMXPathResult.STRING_TYPE , null);
371 if (title && title.stringValue)
372 return title.stringValue;
384 return this.input.length + this.output.length;
387 this.input[this.input.length] = x;
390 let l = this.output.length;
392 l = this.input.length;
395 this.output = this.input.reverse();
397 let x = this.output[l];
398 this.output.length--;
404 function frame_iterator (root_frame, start_with) {
405 var q = new queue, x;
410 for (let i = 0, nframes = x.frames.length; i < nframes; ++i)
412 } while ((x = q.pop()));
419 for (let i = 0, nframes = x.frames.length; i < nframes; ++i)
421 } while ((x = q.pop()));
424 function xml_http_request () {
425 return Cc["@mozilla.org/xmlextras/xmlhttprequest;1"]
426 .createInstance(Ci.nsIXMLHttpRequest)
427 .QueryInterface(Ci.nsIJSXMLHttpRequest)
428 .QueryInterface(Ci.nsIDOMEventTarget);
431 var xml_http_request_load_listener = {
432 // nsIBadCertListener2
433 notifyCertProblem: function SSLL_certProblem (socketInfo, status, targetSite) {
437 // nsISSLErrorListener
438 notifySSLError: function SSLL_SSLError (socketInfo, error, targetSite) {
442 // nsIInterfaceRequestor
443 getInterface: function SSLL_getInterface (iid) {
444 return this.QueryInterface(iid);
449 // FIXME: array comprehension used here to hack around the lack of
450 // Ci.nsISSLErrorListener in 2007 versions of xulrunner 1.9pre.
451 // make it a simple generateQI when xulrunner is more stable.
452 QueryInterface: XPCOMUtils.generateQI(
453 [i for each (i in [Ci.nsIBadCertListener2,
454 Ci.nsISSLErrorListener,
455 Ci.nsIInterfaceRequestor])
461 * Coroutine interface for sending an HTTP request and waiting for the
462 * response. (This includes so-called "AJAX" requests.)
464 * @param lspec (required) a load_spec object or URI string (see load-spec.js)
466 * The request URI is obtained from this argument. In addition, if the
467 * load spec specifies post data, a POST request is made instead of a
468 * GET request, and the post data included in the load spec is
469 * sent. Specifically, the request_mime_type and raw_post_data
470 * properties of the load spec are used.
472 * @param $user (optional) HTTP user name to include in the request headers
473 * @param $password (optional) HTTP password to include in the request headers
475 * @param $override_mime_type (optional) Force the response to be interpreted
476 * as having the specified MIME type. This is only
477 * really useful for forcing the MIME type to be
478 * text/xml or something similar, such that it is
479 * automatically parsed into a DOM document.
480 * @param $headers (optional) an array of [name,value] pairs (each specified as
481 * a two-element array) specifying additional headers to add to
484 * @returns After the request completes (either successfully or with an error),
485 * the nsIXMLHttpRequest object is returned. Its responseText (for any
486 * arbitrary document) or responseXML (if the response type is an XML
487 * content type) properties can be accessed to examine the response
490 * If an exception is thrown to the continutation (which can be obtained by the
491 * caller by calling yield CONTINUATION prior to calling this function) while the
492 * request is in progress (i.e. before this coroutine returns), the request will
493 * be aborted, and the exception will be propagated to the caller.
496 define_keywords("$user", "$password", "$override_mime_type", "$headers");
497 function send_http_request (lspec) {
498 // why do we get warnings in jsconsole unless we initialize the
499 // following keywords?
500 keywords(arguments, $user = undefined, $password = undefined,
501 $override_mime_type = undefined, $headers = undefined);
502 if (! (lspec instanceof load_spec))
503 lspec = load_spec(lspec);
504 var req = xml_http_request();
505 var cc = yield CONTINUATION;
506 var aborting = false;
507 req.onreadystatechange = function send_http_request__onreadystatechange () {
508 if (req.readyState != 4)
515 if (arguments.$override_mime_type)
516 req.overrideMimeType(arguments.$override_mime_type);
518 var post_data = load_spec_raw_post_data(lspec);
520 var method = post_data ? "POST" : "GET";
522 req.open(method, load_spec_uri_string(lspec), true, arguments.$user, arguments.$password);
523 req.channel.notificationCallbacks = xml_http_request_load_listener;
525 for each (let [name,value] in arguments.$headers) {
526 req.setRequestHeader(name, value);
530 req.setRequestHeader("Content-Type", load_spec_request_mime_type(lspec));
543 // Let the caller access the status and reponse data
544 yield co_return(req);
549 * scroll_selection_into_view takes an editable element, and scrolls it so
550 * that the selection (or insertion point) are visible.
552 function scroll_selection_into_view (field) {
553 if (field.namespaceURI == XUL_NS)
554 field = field.inputField;
556 field.QueryInterface(Ci.nsIDOMNSEditableElement)
559 .scrollSelectionIntoView(
560 Ci.nsISelectionController.SELECTION_NORMAL,
561 Ci.nsISelectionController.SELECTION_FOCUS_REGION,
564 // we'll get here for richedit fields
570 * build_url_regexp builds a regular expression to match URLs for a given
573 * Both the $domain and $path arguments can be either regexps, in
574 * which case they will be matched as is, or strings, in which case
575 * they will be matched literally.
577 * $tlds specifies a list of valid top-level-domains to match, and
578 * defaults to .com. Useful for when e.g. foo.org and foo.com are the
581 * If $allow_www is true, www.domain.tld will also be allowed.
583 define_keywords("$domain", "$path", "$tlds", "$allow_www");
584 function build_url_regexp () {
585 function regexp_to_string (obj) {
586 if (typeof obj == "object" && "source" in obj)
588 return quotemeta(obj);
591 keywords(arguments, $path = "", $tlds = ["com"], $allow_www = false);
592 var domain = regexp_to_string(arguments.$domain);
593 if (arguments.$allow_www) {
594 domain = "(?:www\.)?" + domain;
596 var path = regexp_to_string(arguments.$path);
597 var tlds = arguments.$tlds;
598 var regexp = "^https?://" + domain + "\\." + choice_regexp(tlds) + "/" + path;
599 return new RegExp(regexp);
603 function compute_up_url (uri) {
604 uri = uri.clone().QueryInterface(Ci.nsIURL);
605 for (let [k, p] in Iterator(["ref", "query", "param", "fileName"])) {
611 return uri.resolve("..");
615 function url_path_trim (url) {
616 var uri = make_uri(url);
622 /* possibly_valid_url returns true if the string might be a valid
623 * thing to pass to nsIWebNavigation.loadURI. Currently just checks
624 * that there's no whitespace in the middle and that it's not entirely
627 function possibly_valid_url (url) {
628 return !(/\S\s+\S/.test(url)) && !(/^\s*$/.test(url));
633 * Convenience function for making simple XPath lookups in a document.
635 * @param doc The document to look in.
636 * @param exp The XPath expression to search for.
637 * @return The XPathResult object representing the set of found nodes.
639 function xpath_lookup (doc, exp) {
640 return doc.evaluate(exp, doc, null, Ci.nsIDOMXPathResult.ANY_TYPE, null);
644 /* get_contents_synchronously returns the contents of the given
645 * url (string or nsIURI) as a string on success, or null on failure.
647 function get_contents_synchronously (url) {
648 var ioService=Cc["@mozilla.org/network/io-service;1"]
649 .getService(Ci.nsIIOService);
650 var scriptableStream=Cc["@mozilla.org/scriptableinputstream;1"]
651 .getService(Ci.nsIScriptableInputStream);
655 if (url instanceof Ci.nsIURI)
656 channel = ioService.newChannelFromURI(url);
658 channel = ioService.newChannel(url, null, null);
659 input=channel.open();
663 scriptableStream.init(input);
664 var str=scriptableStream.read(input.available());
665 scriptableStream.close();
672 * dom_add_class adds a css class to the given dom node.
674 function dom_add_class (node, cssclass) {
675 if (node.className) {
676 var cs = node.className.split(" ");
677 if (cs.indexOf(cssclass) != -1)
680 node.className = cs.join(" ");
682 node.className = cssclass;
686 * dom_remove_class removes the given css class from the given dom node.
688 function dom_remove_class (node, cssclass) {
689 if (! node.className)
691 var classes = node.className.split(" ");
692 classes = classes.filter(function (x) { return x != cssclass; });
693 node.className = classes.join(" ");
698 * dom_node_flash adds the given cssclass to the node for a brief interval.
699 * this class can be styled, to create a flashing effect.
701 function dom_node_flash (node, cssclass) {
702 dom_add_class(node, cssclass);
705 dom_remove_class(node, cssclass);
712 * data is an an alist (array of 2 element arrays) where each pair is a key
715 * The return type is a mime input stream that can be passed as postData to
716 * nsIWebNavigation.loadURI. In terms of Conkeror's API, the return value
717 * of this function is of the correct type for the `post_data' field of a
720 function make_post_data (data) {
721 data = [(encodeURIComponent(pair[0])+'='+encodeURIComponent(pair[1]))
722 for each (pair in data)].join('&');
723 data = string_input_stream(data);
724 return mime_input_stream(
725 data, [["Content-Type", "application/x-www-form-urlencoded"]]);
730 * Centers the viewport around a given element.
732 * @param win The window to scroll.
733 * @param elem The element arund which we put the viewport.
735 function center_in_viewport (win, elem) {
736 let point = abs_point(elem);
738 point.x -= win.innerWidth / 2;
739 point.y -= win.innerHeight / 2;
741 win.scrollTo(point.x, point.y);
746 * Simple predicate returns true if elem is an nsIDOMNode or
749 function dom_node_or_window_p (elem) {
750 if (elem instanceof Ci.nsIDOMNode)
752 if (elem instanceof Ci.nsIDOMWindow)
758 * Given a hook name, a buffer and a function, waits until the buffer document
759 * has fully loaded, then calls the function with the buffer as its only
762 * @param {String} The hook name.
763 * @param {buffer} The buffer.
764 * @param {function} The function to call with the buffer as its argument once
765 * the buffer has loaded.
767 function do_when (hook, buffer, fun) {
768 if (buffer.browser.webProgress.isLoadingDocument)
769 add_hook.call(buffer, hook, fun);
776 * evaluate string s as javascript in the 'this' scope in which evaluate
779 function evaluate (s) {
781 var obs = Cc["@mozilla.org/observer-service;1"]
782 .getService(Ci.nsIObserverService);
783 obs.notifyObservers(null, "startupcache-invalidate", null);
784 var temp = get_temporary_file("conkeror-evaluate.tmp.js");
785 write_text_file(temp, s);
786 var url = make_uri(temp).spec;
787 return load_url(url, this);
789 if (temp && temp.exists())
796 * set_protocol_handler takes a protocol and a handler spec. If the
797 * handler is true, Mozilla will (try to) handle this protocol internally.
798 * If the handler null, the user will be prompted for a handler when a
799 * resource of this protocol is requested. If the handler is an nsIFile,
800 * the program it gives will be launched with the url as an argument. If
801 * the handler is a string, it will be interpreted as an URL template for
802 * a web service and the sequence '%s' within it will be replaced by the
805 function set_protocol_handler (protocol, handler) {
806 var eps = Cc["@mozilla.org/uriloader/external-protocol-service;1"]
807 .getService(Ci.nsIExternalProtocolService);
808 var info = eps.getProtocolHandlerInfo(protocol);
809 var expose_pref = "network.protocol-handler.expose."+protocol;
810 if (handler == true) {
812 clear_default_pref(expose_pref);
813 } else if (handler) {
815 if (handler instanceof Ci.nsIFile) {
816 var h = Cc["@mozilla.org/uriloader/local-handler-app;1"]
817 .createInstance(Ci.nsILocalHandlerApp);
818 h.executable = handler;
819 } else if (typeof handler == "string") {
820 h = Cc["@mozilla.org/uriloader/web-handler-app;1"]
821 .createInstance(Ci.nsIWebHandlerApp);
822 var uri = make_uri(handler);
824 h.uriTemplate = handler;
826 info.alwaysAskBeforeHandling = false;
827 info.preferredAction = Ci.nsIHandlerInfo.useHelperApp;
828 info.possibleApplicationHandlers.clear();
829 info.possibleApplicationHandlers.appendElement(h, false);
830 info.preferredApplicationHandler = h;
831 session_pref(expose_pref, false);
834 info.alwaysAskBeforeHandling = true;
835 info.preferredAction = Ci.nsIHandlerInfo.alwaysAsk;
836 session_pref(expose_pref, false);
838 var hs = Cc["@mozilla.org/uriloader/handler-service;1"]
839 .getService(Ci.nsIHandlerService);