add program name and version to user-agent string
[conkeror.git] / modules / utils.js
blobb84c732bf8a5028b9a2a255f74e7eea2d2c35072
1 /**
2  * (C) Copyright 2004-2007 Shawn Betts
3  * (C) Copyright 2007-2009 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 in_module(null);
12 function string_hashset () {}
14 string_hashset.prototype = {
15     constructor : string_hashset,
17     add : function (s) {
18         this["-" + s] = true;
19     },
21     contains : function (s) {
22         return (("-" + s) in this);
23     },
25     remove : function (s) {
26         delete this["-" + s];
27     },
29     for_each : function (f) {
30         for (var i in this) {
31             if (i[0] == "-")
32                 f(i.slice(1));
33         }
34     },
36     iterator : function () {
37         for (let k in this) {
38             if (i[0] == "-")
39                 yield i.slice(1);
40         }
41     }
44 function string_hashmap () {}
46 string_hashmap.prototype = {
47     constructor : string_hashmap,
49     put : function (s,value) {
50         this["-" + s] = value;
51     },
53     contains : function (s) {
54         return (("-" + s) in this);
55     },
57     get : function (s, default_value) {
58         if (this.contains(s))
59             return this["-" + s];
60         return default_value;
61     },
63     get_put_default : function (s, default_value) {
64         if (this.contains(s))
65             return this["-" + s];
66         return (this["-" + s] = default_value);
67     },
69     remove : function (s) {
70         delete this["-" + s];
71     },
73     for_each : function (f) {
74         for (var i in this) {
75             if (i[0] == "-")
76                 f(i.slice(1), this[i]);
77         }
78     },
80     for_each_value : function (f) {
81         for (var i in this) {
82             if (i[0] == "-")
83                 f(this[i]);
84         }
85     },
87     iterator: function (only_keys) {
88         if (only_keys) {
89             for (let k in Iterator(this, true)) {
90                 if (k[0] == "-")
91                     yield k.slice(1);
92             }
93         } else {
94             for (let [k,v] in Iterator(this, false)) {
95                 if (k[0] == "-")
96                     yield [k.slice(1),v];
97             }
98         }
99     }
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) {
112     // Construct nsIURL.
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)
122         return path;
123     var f = Cc["@mozilla.org/file/local;1"]
124         .createInstance(Ci.nsILocalFile);
125     f.initWithPath(path);
126     return f;
130 function make_file_from_chrome (url) {
131     var crs = Cc['@mozilla.org/chrome/chrome-registry;1']
132         .getService(Ci.nsIChromeRegistry);
133     var file = crs.convertChromeURL(make_uri(url));
134     return make_file(file.path);
137 function get_document_content_disposition (document_o) {
138     var content_disposition = null;
139     try {
140         content_disposition = document_o.defaultView
141             .QueryInterface(Components.interfaces.nsIInterfaceRequestor)
142             .getInterface(Components.interfaces.nsIDOMWindowUtils)
143             .getDocumentMetadata("content-disposition");
144     } catch (e) { }
145     return content_disposition;
149 function set_focus_no_scroll (window, element) {
150     window.document.commandDispatcher.suppressFocusScroll = true;
151     element.focus();
152     window.document.commandDispatcher.suppressFocusScroll = false;
155 function do_repeatedly_positive (func, n) {
156     var args = Array.prototype.slice.call(arguments, 2);
157     while (n-- > 0)
158         func.apply(null, args);
161 function do_repeatedly (func, n, positive_args, negative_args) {
162     if (n < 0)
163         do func.apply(null, negative_args); while (++n < 0);
164     else
165         while (n-- > 0) func.apply(null, positive_args);
170  * Given a node, returns its position relative to the document.
172  * @param node The node to get the position of.
173  * @return An object with properties "x" and "y" representing its offset from
174  *         the left and top of the document, respectively.
175  */
176 function abs_point (node) {
177     var orig = node;
178     var pt = {};
179     try {
180         pt.x = node.offsetLeft;
181         pt.y = node.offsetTop;
182         // find imagemap's coordinates
183         if (node.tagName == "AREA") {
184             var coords = node.getAttribute("coords").split(",");
185             pt.x += Number(coords[0]);
186             pt.y += Number(coords[1]);
187         }
189         node = node.offsetParent;
190         // Sometimes this fails, so just return what we got.
192         while (node.tagName != "BODY") {
193             pt.x += node.offsetLeft;
194             pt.y += node.offsetTop;
195             node = node.offsetParent;
196         }
197     } catch(e) {
198 //      node = orig;
199 //      while (node.tagName != "BODY") {
200 //          alert("okay: " + node + " " + node.tagName + " " + pt.x + " " + pt.y);
201 //          node = node.offsetParent;
202 //      }
203     }
204     return pt;
208 const XHTML_NS = "http://www.w3.org/1999/xhtml";
209 const XUL_NS = "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul";
210 const MATHML_NS = "http://www.w3.org/1998/Math/MathML";
211 const XLINK_NS = "http://www.w3.org/1999/xlink";
213 function create_XUL (window, tag_name) {
214     return window.document.createElementNS(XUL_NS, tag_name);
218 /* Used in calls to XPath evaluate */
219 function xpath_lookup_namespace (prefix) {
220     return {
221         xhtml: XHTML_NS,
222         m: MATHML_NS,
223         xul: XUL_NS
224     }[prefix] || null;
227 function method_caller (obj, func) {
228     return function () {
229         func.apply(obj, arguments);
230     };
234 function get_window_from_frame (frame) {
235     try {
236         var window = frame.QueryInterface(Ci.nsIInterfaceRequestor)
237             .getInterface(Ci.nsIWebNavigation)
238             .QueryInterface(Ci.nsIDocShellTreeItem)
239             .rootTreeItem
240             .QueryInterface(Ci.nsIInterfaceRequestor)
241             .getInterface(Ci.nsIDOMWindow).wrappedJSObject;
242         /* window is now an XPCSafeJSObjectWrapper */
243         window.escape_wrapper(function (w) { window = w; });
244         /* window is now completely unwrapped */
245         return window;
246     } catch (e) {
247         return null;
248     }
251 function get_buffer_from_frame (window, frame) {
252     var count = window.buffers.count;
253     for (var i = 0; i < count; ++i) {
254         var b = window.buffers.get_buffer(i);
255         if (b.top_frame == frame.top)
256             return b;
257     }
258     return null;
262 function dom_generator (document, ns) {
263     this.document = document;
264     this.ns = ns;
266 dom_generator.prototype = {
267     element : function (tag, parent) {
268         var node = this.document.createElementNS(this.ns, tag);
269         var i = 1;
270         if (parent != null && (parent instanceof Ci.nsIDOMNode)) {
271             parent.appendChild(node);
272             i = 2;
273         }
274         for (var nargs = arguments.length; i < nargs; i += 2)
275             node.setAttribute(arguments[i], arguments[i+1]);
276         return node;
277     },
279     text : function (str, parent) {
280         var node = this.document.createTextNode(str);
281         if (parent)
282             parent.appendChild(node);
283         return node;
284     },
287     stylesheet_link : function (href, parent) {
288         var node = this.element("link");
289         node.setAttribute("rel", "stylesheet");
290         node.setAttribute("type", "text/css");
291         node.setAttribute("href", href);
292         if (parent)
293             parent.appendChild(node);
294         return node;
295     },
298     add_stylesheet : function (url) {
299         var head = this.document.documentElement.firstChild;
300         this.stylesheet_link(url, head);
301     }
305  * Generates a QueryInterface function suitable for an implemenation
306  * of an XPCOM interface.  Unlike XPCOMUtils, this uses the Function
307  * constructor to generate a slightly more efficient version.  The
308  * arguments can be either Strings or elements of
309  * Components.interfaces.
310  */
311 function generate_QI () {
312     var args = Array.prototype.slice.call(arguments).map(String).concat(["nsISupports"]);
313     var fstr = "if(" +
314         Array.prototype.map.call(args, function (x) {
315             return "iid.equals(Components.interfaces." + x + ")";
316         })
317         .join("||") +
318         ") return this; throw Components.results.NS_ERROR_NO_INTERFACE;";
319     return new Function("iid", fstr);
323 function abort (str) {
324     var e = new Error(str);
325     e.__proto__ = abort.prototype;
326     return e;
328 abort.prototype.__proto__ = Error.prototype;
331 function get_temporary_file (name) {
332     if (name == null)
333         name = "temp.txt";
334     var file = file_locator_service.get("TmpD", Ci.nsIFile);
335     file.append(name);
336     // Create the file now to ensure that no exploits are possible
337     file.createUnique(Ci.nsIFile.NORMAL_FILE_TYPE, 0600);
338     return file;
342 /* FIXME: This should be moved somewhere else, perhaps. */
343 function create_info_panel (window, panel_class, row_arr) {
344     /* Show information panel above minibuffer */
346     var g = new dom_generator(window.document, XUL_NS);
348     var p = g.element("vbox", "class", "panel " + panel_class, "flex", "0");
349     var grid = g.element("grid", p);
350     var cols = g.element("columns", grid);
351     g.element("column", cols, "flex", "0");
352     g.element("column", cols, "flex", "1");
354     var rows = g.element("rows", grid);
355     var row;
357     for each (let [row_class, row_label, row_value] in row_arr) {
358         row = g.element("row", rows, "class", row_class);
359         g.element("label", row,
360                   "value", row_label,
361                   "class", "panel-row-label");
362         g.element("label", row,
363                   "value", row_value,
364                   "class", "panel-row-value",
365                   "crop", "end");
366     }
367     window.minibuffer.insert_before(p);
369     p.destroy = function () {
370         this.parentNode.removeChild(this);
371     };
373     return p;
378  * Paste from the X primary selection, unless the system doesn't support a
379  * primary selection, in which case fall back to the clipboard.
380  */
381 function read_from_x_primary_selection () {
382     // Get clipboard.
383     let clipboard = Components.classes["@mozilla.org/widget/clipboard;1"]
384         .getService(Components.interfaces.nsIClipboard);
386     // Fall back to global clipboard if the system doesn't support a selection
387     let which_clipboard = clipboard.supportsSelectionClipboard() ?
388         clipboard.kSelectionClipboard : clipboard.kGlobalClipboard;
390     let flavors = ["text/unicode"];
392     // Don't barf if there's nothing on the clipboard
393     if (!clipboard.hasDataMatchingFlavors(flavors, flavors.length, which_clipboard))
394         return "";
396     // Create transferable that will transfer the text.
397     let trans = Components.classes["@mozilla.org/widget/transferable;1"]
398         .createInstance(Components.interfaces.nsITransferable);
400     for each (let flavor in flavors) {
401         trans.addDataFlavor(flavor);
402     }
403     clipboard.getData(trans, which_clipboard);
405     var data_flavor = {};
406     var data = {};
407     var dataLen = {};
408     trans.getAnyTransferData(data_flavor, data, dataLen);
410     if (data) {
411         data = data.value.QueryInterface(Components.interfaces.nsISupportsString);
412         let data_length = dataLen.value;
413         if (data_flavor.value == "text/unicode")
414             data_length = dataLen.value / 2;
415         return data.data.substring(0, data_length);
416     } else {
417         return "";
418     }
422 function predicate_alist_match (alist, key) {
423     for each (let i in alist) {
424         if (i[0](key))
425             return i[1];
426     }
427     return undefined;
431 function get_meta_title (doc) {
432     var title = doc.evaluate("//meta[@name='title']/@content", doc, xpath_lookup_namespace,
433                              Ci.nsIDOMXPathResult.STRING_TYPE , null);
434     if (title && title.stringValue)
435         return title.stringValue;
436     return null;
440 function queue () {
441     this.input = [];
442     this.output = [];
444 queue.prototype = {
445     get length () {
446         return this.input.length + this.output.length;
447     },
448     push: function (x) {
449         this.input[this.input.length] = x;
450     },
451     pop: function (x) {
452         let l = this.output.length;
453         if (!l) {
454             l = this.input.length;
455             if (!l)
456                 return undefined;
457             this.output = this.input.reverse();
458             this.input = [];
459             let x = this.output[l];
460             this.output.length--;
461             return x;
462         }
463     }
466 function frame_iterator (root_frame, start_with) {
467     var q = new queue, x;
468     if (start_with) {
469         x = start_with;
470         do {
471             yield x;
472             for (let i = 0, nframes = x.frames.length; i < nframes; ++i)
473                 q.push(x.frames[i]);
474         } while ((x = q.pop()));
475     }
476     x = root_frame;
477     do {
478         if (x == start_with)
479             continue;
480         yield x;
481         for (let i = 0, nframes = x.frames.length; i < nframes; ++i)
482             q.push(x.frames[i]);
483     } while ((x = q.pop()));
486 function xml_http_request () {
487     return Cc["@mozilla.org/xmlextras/xmlhttprequest;1"]
488         .createInstance(Ci.nsIXMLHttpRequest)
489         .QueryInterface(Ci.nsIJSXMLHttpRequest)
490         .QueryInterface(Ci.nsIDOMEventTarget);
493 var xml_http_request_load_listener = {
494   // nsIBadCertListener2
495   notifyCertProblem: function SSLL_certProblem (socketInfo, status, targetSite) {
496     return true;
497   },
499   // nsISSLErrorListener
500   notifySSLError: function SSLL_SSLError (socketInfo, error, targetSite) {
501     return true;
502   },
504   // nsIInterfaceRequestor
505   getInterface: function SSLL_getInterface (iid) {
506     return this.QueryInterface(iid);
507   },
509   // nsISupports
510   //
511   // FIXME: array comprehension used here to hack around the lack of
512   // Ci.nsISSLErrorListener in 2007 versions of xulrunner 1.9pre.
513   // make it a simple generateQI when xulrunner is more stable.
514   QueryInterface: XPCOMUtils.generateQI(
515       [i for each (i in [Ci.nsIBadCertListener2,
516                          Ci.nsISSLErrorListener,
517                          Ci.nsIInterfaceRequestor])
518        if (i)])
523  * Coroutine interface for sending an HTTP request and waiting for the
524  * response. (This includes so-called "AJAX" requests.)
526  * @param lspec (required) a load_spec object or URI string (see load-spec.js)
528  * The request URI is obtained from this argument. In addition, if the
529  * load spec specifies post data, a POST request is made instead of a
530  * GET request, and the post data included in the load spec is
531  * sent. Specifically, the request_mime_type and raw_post_data
532  * properties of the load spec are used.
534  * @param $user (optional) HTTP user name to include in the request headers
535  * @param $password (optional) HTTP password to include in the request headers
537  * @param $override_mime_type (optional) Force the response to be interpreted
538  *                            as having the specified MIME type.  This is only
539  *                            really useful for forcing the MIME type to be
540  *                            text/xml or something similar, such that it is
541  *                            automatically parsed into a DOM document.
542  * @param $headers (optional) an array of [name,value] pairs (each specified as
543  *                 a two-element array) specifying additional headers to add to
544  *                 the request.
546  * @returns After the request completes (either successfully or with an error),
547  *          the nsIXMLHttpRequest object is returned.  Its responseText (for any
548  *          arbitrary document) or responseXML (if the response type is an XML
549  *          content type) properties can be accessed to examine the response
550  *          document.
552  * If an exception is thrown to the continutation (which can be obtained by the
553  * caller by calling yield CONTINUATION prior to calling this function) while the
554  * request is in progress (i.e. before this coroutine returns), the request will
555  * be aborted, and the exception will be propagated to the caller.
557  **/
558 define_keywords("$user", "$password", "$override_mime_type", "$headers");
559 function send_http_request (lspec) {
560     // why do we get warnings in jsconsole unless we initialize the
561     // following keywords?
562     keywords(arguments, $user = undefined, $password = undefined,
563              $override_mime_type = undefined, $headers = undefined);
564     if (! (lspec instanceof load_spec))
565         lspec = load_spec(lspec);
566     var req = xml_http_request();
567     var cc = yield CONTINUATION;
568     var aborting = false;
569     req.onreadystatechange = function send_http_request__onreadysatechange () {
570         if (req.readyState != 4)
571             return;
572         if (aborting)
573             return;
574         cc();
575     };
577     if (arguments.$override_mime_type)
578         req.overrideMimeType(arguments.$override_mime_type);
580     var post_data = load_spec_raw_post_data(lspec);
582     var method = post_data ? "POST" : "GET";
584     req.open(method, load_spec_uri_string(lspec), true, arguments.$user, arguments.$password);
585     req.channel.notificationCallbacks = xml_http_request_load_listener;
587     for each (let [name,value] in arguments.$headers) {
588         req.setRequestHeader(name, value);
589     }
591     if (post_data) {
592         req.setRequestHeader("Content-Type", load_spec_request_mime_type(lspec));
593         req.send(post_data);
594     } else
595         req.send(null);
597     try {
598         yield SUSPEND;
599     } catch (e) {
600         aborting = true;
601         req.abort();
602         throw e;
603     }
605     // Let the caller access the status and reponse data
606     yield co_return(req);
611  * scroll_selection_into_view takes an editable element, and scrolls it so
612  * that the selection (or insertion point) are visible.
613  */
614 function scroll_selection_into_view (field) {
615     if (field.namespaceURI == XUL_NS)
616         field = field.inputField;
617     try {
618         field.QueryInterface(Ci.nsIDOMNSEditableElement)
619             .editor
620             .selectionController
621             .scrollSelectionIntoView(
622                 Ci.nsISelectionController.SELECTION_NORMAL,
623                 Ci.nsISelectionController.SELECTION_FOCUS_REGION,
624                 true);
625     } catch (e) {
626         // we'll get here for richedit fields
627     }
632  * build_url_regex builds a regular expression to match URLs for a given
633  * web site.
635  * Both the $domain and $path arguments can be either regexes, in
636  * which case they will be matched as is, or strings, in which case
637  * they will be matched literally.
639  * $tlds specifies a list of valid top-level-domains to match, and
640  * defaults to .com. Useful for when e.g. foo.org and foo.com are the
641  * same.
643  * If $allow_www is true, www.domain.tld will also be allowed.
644  */
645 define_keywords("$domain", "$path", "$tlds", "$allow_www");
646 function build_url_regex () {
647     function regex_to_string (obj) {
648         if (obj instanceof RegExp)
649             return obj.source;
650         return quotemeta(obj);
651     }
653     keywords(arguments, $path = "", $tlds = ["com"], $allow_www = false);
654     var domain = regex_to_string(arguments.$domain);
655     if(arguments.$allow_www) {
656         domain = "(?:www\.)?" + domain;
657     }
658     var path   = regex_to_string(arguments.$path);
659     var tlds   = arguments.$tlds;
660     var regex = "^https?://" + domain + "\\." + choice_regex(tlds) + "/" + path;
661     return new RegExp(regex);
665 function compute_url_up_path (url) {
666     var new_url = Cc["@mozilla.org/network/standard-url;1"]
667         .createInstance (Ci.nsIURL);
668     new_url.spec = url;
669     var up;
670     if (new_url.param != "" || new_url.query != "")
671         up = new_url.filePath;
672     else if (new_url.fileName != "")
673         up = ".";
674     else
675         up = "..";
676     return up;
680 function url_path_trim (url) {
681     var uri = make_uri(url);
682     uri.spec = url;
683     uri.path = "";
684     return uri.spec;
687 /* possibly_valid_url returns true if the string might be a valid
688  * thing to pass to nsIWebNavigation.loadURI.  Currently just checks
689  * that there's no whitespace in the middle and that it's not entirely
690  * whitespace.
691  */
692 function possibly_valid_url (url) {
693     return !(/\S\s+\S/.test(url)) && !(/^\s*$/.test(url));
698  * Convenience function for making simple XPath lookups in a document.
700  * @param doc The document to look in.
701  * @param exp The XPath expression to search for.
702  * @return The XPathResult object representing the set of found nodes.
703  */
704 function xpath_lookup (doc, exp) {
705     return doc.evaluate(exp, doc, null, Ci.nsIDOMXPathResult.ANY_TYPE, null);
709 /* get_contents_synchronously returns the contents of the given
710  * url (string or nsIURI) as a string on success, or null on failure.
711  */
712 function get_contents_synchronously (url) {
713     var ioService=Cc["@mozilla.org/network/io-service;1"]
714         .getService(Ci.nsIIOService);
715     var scriptableStream=Cc["@mozilla.org/scriptableinputstream;1"]
716         .getService(Ci.nsIScriptableInputStream);
717     var channel;
718     var input;
719     try {
720         if (url instanceof Ci.nsIURI)
721             channel = ioService.newChannelFromURI(url);
722         else
723             channel = ioService.newChannel(url, null, null);
724         input=channel.open();
725     } catch (e) {
726         return null;
727     }
728     scriptableStream.init(input);
729     var str=scriptableStream.read(input.available());
730     scriptableStream.close();
731     input.close();
732     return str;
737  * dom_add_class adds a css class to the given dom node.
738  */
739 function dom_add_class (node, cssclass) {
740     if (node.className)
741         node.className += " "+cssclass;
742     else
743         node.className = cssclass;
747  * dom_remove_class removes the given css class from the given dom node.
748  */
749 function dom_remove_class (node, cssclass) {
750     if (! node.className)
751         return;
752     var classes = node.className.split(" ");
753     classes = classes.filter(function (x) { return x != cssclass; });
754     node.className = classes.join(" ");
759  * dom_node_flash adds the given cssclass to the node for a brief interval.
760  * this class can be styled, to create a flashing effect.
761  */
762 function dom_node_flash (node, cssclass) {
763     dom_add_class(node, cssclass);
764     call_after_timeout(
765         function () {
766             dom_remove_class(node, cssclass);
767         },
768         400);
773  * data is an an alist (array of 2 element arrays) where each pair is a key
774  * and a value.
776  * The return type is a mime input stream that can be passed as postData to
777  * nsIWebNavigation.loadURI.  In terms of Conkeror's API, the return value
778  * of this function is of the correct type for the `post_data' field of a
779  * load_spec.
780  */
781 function make_post_data (data) {
782     data = [(encodeURIComponent(pair[0])+'='+encodeURIComponent(pair[1]))
783             for each (pair in data)].join('&');
784     data = string_input_stream(data);
785     return mime_input_stream(
786         data, [["Content-Type", "application/x-www-form-urlencoded"]]);
791  * Centers the viewport around a given element.
793  * @param win  The window to scroll.
794  * @param elem The element arund which we put the viewport.
795  */
796 function center_in_viewport (win, elem) {
797     let point = abs_point(elem);
799     point.x -= win.innerWidth / 2;
800     point.y -= win.innerHeight / 2;
802     win.scrollTo(point.x, point.y);
807  * Takes an interactive context and a function to call with the word
808  * at point as its sole argument, and which returns a modified word.
809  */
810 //XXX: this should be implemented in terms of modify_region,
811 //     in order to work in richedit fields.
812 function modify_word_at_point (I, func) {
813     var focused = I.buffer.focused_element;
815     // Skip any whitespaces at point and move point to the right place.
816     var point = focused.selectionStart;
817     var rest = focused.value.substring(point);
819     // Skip any whitespaces.
820     for (var i = 0, rlen = rest.length; i < rlen; i++) {
821         if (" \n".indexOf(rest.charAt(i)) == -1) {
822             point += i;
823             break;
824         }
825     }
827     // Find the next whitespace, as it is the end of the word.  If no next
828     // whitespace is found, we're at the end of input.  TODO: Add "\n" support.
829     goal = focused.value.indexOf(" ", point);
830     if (goal == -1)
831         goal = focused.value.length;
833     // Change the value of the text field.
834     var input = focused.value;
835     focused.value =
836         input.substring(0, point) +
837         func(input.substring(point, goal)) +
838         input.substring(goal);
840     // Move point.
841     focused.selectionStart = goal;
842     focused.selectionEnd = goal;
847  * Simple predicate returns true if elem is an nsIDOMNode or
848  * nsIDOMWindow.
849  */
850 function element_dom_node_or_window_p (elem) {
851     if (elem instanceof Ci.nsIDOMNode)
852         return true;
853     if (elem instanceof Ci.nsIDOMWindow)
854         return true;
855     return false;
859  * Given a hook name, a buffer and a function, waits until the buffer document
860  * has fully loaded, then calls the function with the buffer as its only
861  * argument.
863  * @param {String} The hook name.
864  * @param {buffer} The buffer.
865  * @param {function} The function to call with the buffer as its argument once
866  *                   the buffer has loaded.
867  */
868 function do_when (hook, buffer, fun) {
869     if (buffer.browser.webProgress.isLoadingDocument)
870         add_hook.call(buffer, hook, fun);
871     else
872         fun(buffer);
875 provide("utils");