copy command: universal-argument (C-u) means append text to clipboard
[conkeror.git] / modules / utils.js
blob2210fada7125a8d3375fe352875862d2070365af
1 /**
2  * (C) Copyright 2004-2007 Shawn Betts
3  * (C) Copyright 2007-2011 John J. Foerch
4  * (C) Copyright 2007-2008 Jeremy Maitin-Shepard
5  *
6  * Use, modification, and distribution are subject to the terms specified in the
7  * COPYING file.
8 **/
10 require("io");
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) {
21     // Construct nsIURL.
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)
31         return path;
32     if (path == "~")
33         return get_home_directory();
34     if (WINDOWS)
35         path = path.replace("/", "\\", "g");
36     if ((POSIX && path.substring(0,2) == "~/") ||
37         (WINDOWS && path.substring(0,2) == "~\\"))
38     {
39         var f = get_home_directory();
40         f.appendRelativePath(path.substring(2));
41     } else {
42         f = Cc["@mozilla.org/file/local;1"]
43             .createInstance(Ci.nsILocalFile);
44         f.initWithPath(path);
45     }
46     return f;
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;
59     try {
60         content_disposition = document_o.defaultView
61             .QueryInterface(Components.interfaces.nsIInterfaceRequestor)
62             .getInterface(Components.interfaces.nsIDOMWindowUtils)
63             .getDocumentMetadata("content-disposition");
64     } catch (e) { }
65     return content_disposition;
69 function set_focus_no_scroll (window, element) {
70     window.document.commandDispatcher.suppressFocusScroll = true;
71     element.focus();
72     window.document.commandDispatcher.suppressFocusScroll = false;
75 function do_repeatedly_positive (func, n) {
76     var args = Array.prototype.slice.call(arguments, 2);
77     while (n-- > 0)
78         func.apply(null, args);
81 function do_repeatedly (func, n, positive_args, negative_args) {
82     if (n < 0)
83         do func.apply(null, negative_args); while (++n < 0);
84     else
85         while (n-- > 0) func.apply(null, positive_args);
89 /**
90  * Given a node, returns its position relative to the document.
91  *
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.
95  */
96 function abs_point (node) {
97     var orig = node;
98     var pt = {};
99     try {
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]);
107         }
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;
116         }
117     } catch(e) {
118 //      node = orig;
119 //      while (node.tagName != "BODY") {
120 //          alert("okay: " + node + " " + node.tagName + " " + pt.x + " " + pt.y);
121 //          node = node.offsetParent;
122 //      }
123     }
124     return pt;
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) {
141     return {
142         xhtml: XHTML_NS,
143         m: MATHML_NS,
144         xul: XUL_NS,
145         svg: SVG_NS
146     }[prefix] || null;
149 function method_caller (obj, func) {
150     return function () {
151         func.apply(obj, arguments);
152     };
156 function get_window_from_frame (frame) {
157     try {
158         var window = frame.QueryInterface(Ci.nsIInterfaceRequestor)
159             .getInterface(Ci.nsIWebNavigation)
160             .QueryInterface(Ci.nsIDocShellTreeItem)
161             .rootTreeItem
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 */
167         return window;
168     } catch (e) {
169         return null;
170     }
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)
178             return b;
179     }
180     return null;
184 function dom_generator (document, ns) {
185     this.document = document;
186     this.ns = ns;
188 dom_generator.prototype = {
189     constructor: dom_generator,
190     element: function (tag, parent) {
191         var node = this.document.createElementNS(this.ns, tag);
192         var i = 1;
193         if (parent != null && (parent instanceof Ci.nsIDOMNode)) {
194             parent.appendChild(node);
195             i = 2;
196         }
197         for (var nargs = arguments.length; i < nargs; i += 2)
198             node.setAttribute(arguments[i], arguments[i+1]);
199         return node;
200     },
202     text: function (str, parent) {
203         var node = this.document.createTextNode(str);
204         if (parent)
205             parent.appendChild(node);
206         return node;
207     },
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);
215         if (parent)
216             parent.appendChild(node);
217         return node;
218     },
221     add_stylesheet: function (url) {
222         var head = this.document.documentElement.firstChild;
223         this.stylesheet_link(url, head);
224     }
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.
233  */
234 function generate_QI () {
235     var args = Array.prototype.slice.call(arguments).map(String).concat(["nsISupports"]);
236     var fstr = "if(" +
237         Array.prototype.map.call(args, function (x) {
238             return "iid.equals(Components.interfaces." + x + ")";
239         })
240         .join("||") +
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;
249     return e;
251 abort.prototype.__proto__ = Error.prototype;
254 function get_temporary_file (name) {
255     if (name == null)
256         name = "temp.txt";
257     var file = file_locator_service.get("TmpD", Ci.nsIFile);
258     file.append(name);
259     // Create the file now to ensure that no exploits are possible
260     file.createUnique(Ci.nsIFile.NORMAL_FILE_TYPE, 0600);
261     return file;
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);
278     var row;
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,
283                   "value", row_label,
284                   "class", "panel-row-label");
285         g.element("label", row,
286                   "value", row_value,
287                   "class", "panel-row-value",
288                   "crop", "end");
289     }
290     window.minibuffer.insert_before(p);
292     p.destroy = function () {
293         this.parentNode.removeChild(this);
294     };
296     return p;
301  * Return clipboard contents as string.  When which_clipboard is given, it
302  * may be an nsIClipboard constant specifying which clipboard to use.
303  */
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))
314         return "";
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);
322     }
323     clipboard.getData(trans, which_clipboard);
325     var data_flavor = {};
326     var data = {};
327     var dataLen = {};
328     trans.getAnyTransferData(data_flavor, data, dataLen);
330     if (data) {
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);
336     } else
337         return "";
342  * Return selection clipboard contents as a string, or regular clipboard
343  * contents if the system does not support a selection clipboard.
344  */
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) {
359             if (i[0].exec(key))
360                 return i[1];
361         } else if (i[0](key))
362             return i[1];
363     }
364     return undefined;
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;
373     return null;
377 function queue () {
378     this.input = [];
379     this.output = [];
381 queue.prototype = {
382     constructor: queue,
383     get length () {
384         return this.input.length + this.output.length;
385     },
386     push: function (x) {
387         this.input[this.input.length] = x;
388     },
389     pop: function (x) {
390         let l = this.output.length;
391         if (!l) {
392             l = this.input.length;
393             if (!l)
394                 return undefined;
395             this.output = this.input.reverse();
396             this.input = [];
397             let x = this.output[l];
398             this.output.length--;
399             return x;
400         }
401     }
404 function frame_iterator (root_frame, start_with) {
405     var q = new queue, x;
406     if (start_with) {
407         x = start_with;
408         do {
409             yield x;
410             for (let i = 0, nframes = x.frames.length; i < nframes; ++i)
411                 q.push(x.frames[i]);
412         } while ((x = q.pop()));
413     }
414     x = root_frame;
415     do {
416         if (x == start_with)
417             continue;
418         yield x;
419         for (let i = 0, nframes = x.frames.length; i < nframes; ++i)
420             q.push(x.frames[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) {
434     return true;
435   },
437   // nsISSLErrorListener
438   notifySSLError: function SSLL_SSLError (socketInfo, error, targetSite) {
439     return true;
440   },
442   // nsIInterfaceRequestor
443   getInterface: function SSLL_getInterface (iid) {
444     return this.QueryInterface(iid);
445   },
447   // nsISupports
448   //
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])
456        if (i)])
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
482  *                 the request.
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
488  *          document.
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.
495  **/
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)
509             return;
510         if (aborting)
511             return;
512         cc();
513     };
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);
527     }
529     if (post_data) {
530         req.setRequestHeader("Content-Type", load_spec_request_mime_type(lspec));
531         req.send(post_data);
532     } else
533         req.send(null);
535     try {
536         yield SUSPEND;
537     } catch (e) {
538         aborting = true;
539         req.abort();
540         throw e;
541     }
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.
551  */
552 function scroll_selection_into_view (field) {
553     if (field.namespaceURI == XUL_NS)
554         field = field.inputField;
555     try {
556         field.QueryInterface(Ci.nsIDOMNSEditableElement)
557             .editor
558             .selectionController
559             .scrollSelectionIntoView(
560                 Ci.nsISelectionController.SELECTION_NORMAL,
561                 Ci.nsISelectionController.SELECTION_FOCUS_REGION,
562                 true);
563     } catch (e) {
564         // we'll get here for richedit fields
565     }
570  * build_url_regexp builds a regular expression to match URLs for a given
571  * web site.
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
579  * same.
581  * If $allow_www is true, www.domain.tld will also be allowed.
582  */
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)
587             return obj.source;
588         return quotemeta(obj);
589     }
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;
595     }
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"])) {
606         if (uri[p] != "") {
607             uri[p] = "";
608             return uri.spec;
609         }
610     }
611     return uri.resolve("..");
615 function url_path_trim (url) {
616     var uri = make_uri(url);
617     uri.spec = url;
618     uri.path = "";
619     return uri.spec;
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
625  * whitespace.
626  */
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.
638  */
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.
646  */
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);
652     var channel;
653     var input;
654     try {
655         if (url instanceof Ci.nsIURI)
656             channel = ioService.newChannelFromURI(url);
657         else
658             channel = ioService.newChannel(url, null, null);
659         input=channel.open();
660     } catch (e) {
661         return null;
662     }
663     scriptableStream.init(input);
664     var str=scriptableStream.read(input.available());
665     scriptableStream.close();
666     input.close();
667     return str;
672  * dom_add_class adds a css class to the given dom node.
673  */
674 function dom_add_class (node, cssclass) {
675     if (node.className) {
676         var cs = node.className.split(" ");
677         if (cs.indexOf(cssclass) != -1)
678             return;
679         cs.push(cssclass);
680         node.className = cs.join(" ");
681     } else
682         node.className = cssclass;
686  * dom_remove_class removes the given css class from the given dom node.
687  */
688 function dom_remove_class (node, cssclass) {
689     if (! node.className)
690         return;
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.
700  */
701 function dom_node_flash (node, cssclass) {
702     dom_add_class(node, cssclass);
703     call_after_timeout(
704         function () {
705             dom_remove_class(node, cssclass);
706         },
707         400);
712  * data is an an alist (array of 2 element arrays) where each pair is a key
713  * and a value.
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
718  * load_spec.
719  */
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.
734  */
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
747  * nsIDOMWindow.
748  */
749 function dom_node_or_window_p (elem) {
750     if (elem instanceof Ci.nsIDOMNode)
751         return true;
752     if (elem instanceof Ci.nsIDOMWindow)
753         return true;
754     return false;
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
760  * argument.
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.
766  */
767 function do_when (hook, buffer, fun) {
768     if (buffer.browser.webProgress.isLoadingDocument)
769         add_hook.call(buffer, hook, fun);
770     else
771         fun(buffer);
776  * evaluate string s as javascript in the 'this' scope in which evaluate
777  * is called.
778  */
779 function evaluate (s) {
780     try {
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);
788     } finally {
789         if (temp && temp.exists())
790             temp.remove(false);
791     }
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
803  * url-encoded url.
804  */
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) {
811         // internal handling
812         clear_default_pref(expose_pref);
813     } else if (handler) {
814         // external handling
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);
823             h.name = uri.host;
824             h.uriTemplate = handler;
825         }
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);
832     } else {
833         // prompt
834         info.alwaysAskBeforeHandling = true;
835         info.preferredAction = Ci.nsIHandlerInfo.alwaysAsk;
836         session_pref(expose_pref, false);
837     }
838     var hs = Cc["@mozilla.org/uriloader/handler-service;1"]
839         .getService(Ci.nsIHandlerService);
840     hs.store(info);
843 provide("utils");