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);
59 * file_symlink_p takes an nsIFile and returns the value of
60 * file.isSymlink(), but also catches the error and returns false if the
61 * file does not exist. Note that this cannot be tested with
62 * file.exists(), because that method automatically resolves symlinks.
64 function file_symlink_p (file) {
66 return file.isSymlink();
67 } catch (e if (e instanceof Ci.nsIException) &&
68 e.result == Cr.NS_ERROR_FILE_TARGET_DOES_NOT_EXIST)
75 function get_document_content_disposition (document_o) {
76 var content_disposition = null;
78 content_disposition = document_o.defaultView
79 .QueryInterface(Components.interfaces.nsIInterfaceRequestor)
80 .getInterface(Components.interfaces.nsIDOMWindowUtils)
81 .getDocumentMetadata("content-disposition");
83 return content_disposition;
87 function set_focus_no_scroll (window, element) {
88 window.document.commandDispatcher.suppressFocusScroll = true;
90 window.document.commandDispatcher.suppressFocusScroll = false;
93 function do_repeatedly_positive (func, n) {
94 var args = Array.prototype.slice.call(arguments, 2);
96 func.apply(null, args);
99 function do_repeatedly (func, n, positive_args, negative_args) {
101 do func.apply(null, negative_args); while (++n < 0);
103 while (n-- > 0) func.apply(null, positive_args);
108 * Given a node, returns its position relative to the document.
110 * @param node The node to get the position of.
111 * @return An object with properties "x" and "y" representing its offset from
112 * the left and top of the document, respectively.
114 function abs_point (node) {
118 pt.x = node.offsetLeft;
119 pt.y = node.offsetTop;
120 // find imagemap's coordinates
121 if (node.tagName == "AREA") {
122 var coords = node.getAttribute("coords").split(",");
123 pt.x += Number(coords[0]);
124 pt.y += Number(coords[1]);
127 node = node.offsetParent;
128 // Sometimes this fails, so just return what we got.
130 while (node.tagName != "BODY") {
131 pt.x += node.offsetLeft;
132 pt.y += node.offsetTop;
133 node = node.offsetParent;
137 // while (node.tagName != "BODY") {
138 // alert("okay: " + node + " " + node.tagName + " " + pt.x + " " + pt.y);
139 // node = node.offsetParent;
146 function method_caller (obj, func) {
148 func.apply(obj, arguments);
153 function get_window_from_frame (frame) {
155 var window = frame.QueryInterface(Ci.nsIInterfaceRequestor)
156 .getInterface(Ci.nsIWebNavigation)
157 .QueryInterface(Ci.nsIDocShellTreeItem)
159 .QueryInterface(Ci.nsIInterfaceRequestor)
160 .getInterface(Ci.nsIDOMWindow).wrappedJSObject;
161 /* window is now an XPCSafeJSObjectWrapper */
162 window.escape_wrapper(function (w) { window = w; });
163 /* window is now completely unwrapped */
170 function get_buffer_from_frame (window, frame) {
171 var count = window.buffers.count;
172 for (var i = 0; i < count; ++i) {
173 var b = window.buffers.get_buffer(i);
174 if (b.top_frame == frame.top)
182 * Generates a QueryInterface function suitable for an implemenation
183 * of an XPCOM interface. Unlike XPCOMUtils, this uses the Function
184 * constructor to generate a slightly more efficient version. The
185 * arguments can be either Strings or elements of
186 * Components.interfaces.
188 function generate_QI () {
189 var args = Array.prototype.slice.call(arguments).map(String).concat(["nsISupports"]);
191 Array.prototype.map.call(args, function (x) {
192 return "iid.equals(Components.interfaces." + x + ")";
195 ") return this; throw Components.results.NS_ERROR_NO_INTERFACE;";
196 return new Function("iid", fstr);
200 function abort (str) {
201 var e = new Error(str);
202 e.__proto__ = abort.prototype;
205 abort.prototype.__proto__ = Error.prototype;
208 function get_temporary_file (name) {
211 var file = file_locator_service.get("TmpD", Ci.nsIFile);
213 // Create the file now to ensure that no exploits are possible
214 file.createUnique(Ci.nsIFile.NORMAL_FILE_TYPE, 0600);
219 /* FIXME: This should be moved somewhere else, perhaps. */
220 function create_info_panel (window, panel_class, row_arr) {
221 /* Show information panel above minibuffer */
223 var g = new dom_generator(window.document, XUL_NS);
225 var p = g.element("vbox", "class", "panel " + panel_class, "flex", "0");
226 var grid = g.element("grid", p);
227 var cols = g.element("columns", grid);
228 g.element("column", cols, "flex", "0");
229 g.element("column", cols, "flex", "1");
231 var rows = g.element("rows", grid);
234 for each (let [row_class, row_label, row_value] in row_arr) {
235 row = g.element("row", rows, "class", row_class);
236 g.element("label", row,
238 "class", "panel-row-label");
239 g.element("label", row,
241 "class", "panel-row-value",
244 window.minibuffer.insert_before(p);
246 p.destroy = function () {
247 this.parentNode.removeChild(this);
255 * Return clipboard contents as string. When which_clipboard is given, it
256 * may be an nsIClipboard constant specifying which clipboard to use.
258 function read_from_clipboard (which_clipboard) {
259 var clipboard = Cc["@mozilla.org/widget/clipboard;1"]
260 .getService(Ci.nsIClipboard);
261 if (which_clipboard == null)
262 which_clipboard = clipboard.kGlobalClipboard;
264 var flavors = ["text/unicode"];
266 // Don't barf if there's nothing on the clipboard
267 if (!clipboard.hasDataMatchingFlavors(flavors, flavors.length, which_clipboard))
270 // Create transferable that will transfer the text.
271 var trans = Cc["@mozilla.org/widget/transferable;1"]
272 .createInstance(Ci.nsITransferable);
274 for each (let flavor in flavors) {
275 trans.addDataFlavor(flavor);
277 clipboard.getData(trans, which_clipboard);
279 var data_flavor = {};
282 trans.getAnyTransferData(data_flavor, data, dataLen);
285 data = data.value.QueryInterface(Ci.nsISupportsString);
286 var data_length = dataLen.value;
287 if (data_flavor.value == "text/unicode")
288 data_length = dataLen.value / 2;
289 return data.data.substring(0, data_length);
291 return ""; //XXX: is this even reachable?
296 * Return selection clipboard contents as a string, or regular clipboard
297 * contents if the system does not support a selection clipboard.
299 function read_from_x_primary_selection () {
300 var clipboard = Cc["@mozilla.org/widget/clipboard;1"]
301 .getService(Ci.nsIClipboard);
302 // fall back to global clipboard if the
303 // system doesn't support a selection
304 var which_clipboard = clipboard.supportsSelectionClipboard() ?
305 clipboard.kSelectionClipboard : clipboard.kGlobalClipboard;
306 return read_from_clipboard(which_clipboard);
310 function predicate_alist_match (alist, key) {
311 for each (let i in alist) {
312 if (i[0] instanceof RegExp) {
315 } else if (i[0](key))
322 function get_meta_title (doc) {
323 var title = doc.evaluate("//meta[@name='title']/@content", doc, xpath_lookup_namespace,
324 Ci.nsIDOMXPathResult.STRING_TYPE , null);
325 if (title && title.stringValue)
326 return title.stringValue;
338 return this.input.length + this.output.length;
341 this.input[this.input.length] = x;
344 let l = this.output.length;
346 l = this.input.length;
349 this.output = this.input.reverse();
351 let x = this.output[l];
352 this.output.length--;
358 function frame_iterator (root_frame, start_with) {
359 var q = new queue, x;
364 for (let i = 0, nframes = x.frames.length; i < nframes; ++i)
366 } while ((x = q.pop()));
373 for (let i = 0, nframes = x.frames.length; i < nframes; ++i)
375 } while ((x = q.pop()));
378 function xml_http_request () {
379 return Cc["@mozilla.org/xmlextras/xmlhttprequest;1"]
380 .createInstance(Ci.nsIXMLHttpRequest)
381 .QueryInterface(Ci.nsIJSXMLHttpRequest)
382 .QueryInterface(Ci.nsIDOMEventTarget);
385 var xml_http_request_load_listener = {
386 // nsIBadCertListener2
387 notifyCertProblem: function SSLL_certProblem (socketInfo, status, targetSite) {
391 // nsISSLErrorListener
392 notifySSLError: function SSLL_SSLError (socketInfo, error, targetSite) {
396 // nsIInterfaceRequestor
397 getInterface: function SSLL_getInterface (iid) {
398 return this.QueryInterface(iid);
403 // FIXME: array comprehension used here to hack around the lack of
404 // Ci.nsISSLErrorListener in 2007 versions of xulrunner 1.9pre.
405 // make it a simple generateQI when xulrunner is more stable.
406 QueryInterface: XPCOMUtils.generateQI(
407 [i for each (i in [Ci.nsIBadCertListener2,
408 Ci.nsISSLErrorListener,
409 Ci.nsIInterfaceRequestor])
415 * Coroutine interface for sending an HTTP request and waiting for the
416 * response. (This includes so-called "AJAX" requests.)
418 * @param lspec (required) a load_spec object or URI string (see load-spec.js)
420 * The request URI is obtained from this argument. In addition, if the
421 * load spec specifies post data, a POST request is made instead of a
422 * GET request, and the post data included in the load spec is
423 * sent. Specifically, the request_mime_type and raw_post_data
424 * properties of the load spec are used.
426 * @param $user (optional) HTTP user name to include in the request headers
427 * @param $password (optional) HTTP password to include in the request headers
429 * @param $override_mime_type (optional) Force the response to be interpreted
430 * as having the specified MIME type. This is only
431 * really useful for forcing the MIME type to be
432 * text/xml or something similar, such that it is
433 * automatically parsed into a DOM document.
434 * @param $headers (optional) an array of [name,value] pairs (each specified as
435 * a two-element array) specifying additional headers to add to
438 * @returns After the request completes (either successfully or with an error),
439 * the nsIXMLHttpRequest object is returned. Its responseText (for any
440 * arbitrary document) or responseXML (if the response type is an XML
441 * content type) properties can be accessed to examine the response
444 * If an exception is thrown to the continutation (which can be obtained by the
445 * caller by calling yield CONTINUATION prior to calling this function) while the
446 * request is in progress (i.e. before this coroutine returns), the request will
447 * be aborted, and the exception will be propagated to the caller.
450 define_keywords("$user", "$password", "$override_mime_type", "$headers");
451 function send_http_request (lspec) {
452 // why do we get warnings in jsconsole unless we initialize the
453 // following keywords?
454 keywords(arguments, $user = undefined, $password = undefined,
455 $override_mime_type = undefined, $headers = undefined);
456 if (! (lspec instanceof load_spec))
457 lspec = load_spec(lspec);
458 var req = xml_http_request();
459 var cc = yield CONTINUATION;
460 var aborting = false;
461 req.onreadystatechange = function send_http_request__onreadystatechange () {
462 if (req.readyState != 4)
469 if (arguments.$override_mime_type)
470 req.overrideMimeType(arguments.$override_mime_type);
472 var post_data = load_spec_raw_post_data(lspec);
474 var method = post_data ? "POST" : "GET";
476 req.open(method, load_spec_uri_string(lspec), true, arguments.$user, arguments.$password);
477 req.channel.notificationCallbacks = xml_http_request_load_listener;
479 for each (let [name,value] in arguments.$headers) {
480 req.setRequestHeader(name, value);
484 req.setRequestHeader("Content-Type", load_spec_request_mime_type(lspec));
497 // Let the caller access the status and reponse data
498 yield co_return(req);
503 * scroll_selection_into_view takes an editable element, and scrolls it so
504 * that the selection (or insertion point) are visible.
506 function scroll_selection_into_view (field) {
507 if (field.namespaceURI == XUL_NS)
508 field = field.inputField;
510 field.QueryInterface(Ci.nsIDOMNSEditableElement)
513 .scrollSelectionIntoView(
514 Ci.nsISelectionController.SELECTION_NORMAL,
515 Ci.nsISelectionController.SELECTION_FOCUS_REGION,
518 // we'll get here for richedit fields
523 function compute_up_url (uri) {
525 uri = uri.clone().QueryInterface(Ci.nsIURL);
529 for (let [k, p] in Iterator(["ref", "query", "param", "fileName"])) {
530 if (p in uri && uri[p] != "") {
535 return uri.resolve("..");
539 function url_path_trim (url) {
540 var uri = make_uri(url);
547 * possibly_valid_url returns true if its argument is an url-like string,
548 * meaning likely a valid thing to pass to nsIWebNavigation.loadURI.
550 function possibly_valid_url (str) {
551 // no inner space before first /
552 return /^\s*[^\/\s]*(\/|\s*$)/.test(str)
553 && !(/^\s*$/.test(str));
557 /* get_contents_synchronously returns the contents of the given
558 * url (string or nsIURI) as a string on success, or null on failure.
560 function get_contents_synchronously (url) {
561 var ioService=Cc["@mozilla.org/network/io-service;1"]
562 .getService(Ci.nsIIOService);
563 var scriptableStream=Cc["@mozilla.org/scriptableinputstream;1"]
564 .getService(Ci.nsIScriptableInputStream);
568 if (url instanceof Ci.nsIURI)
569 channel = ioService.newChannelFromURI(url);
571 channel = ioService.newChannel(url, null, null);
572 input=channel.open();
576 scriptableStream.init(input);
577 var str=scriptableStream.read(input.available());
578 scriptableStream.close();
585 * data is an an alist (array of 2 element arrays) where each pair is a key
588 * The return type is a mime input stream that can be passed as postData to
589 * nsIWebNavigation.loadURI. In terms of Conkeror's API, the return value
590 * of this function is of the correct type for the `post_data' field of a
593 function make_post_data (data) {
594 data = [(encodeURIComponent(pair[0])+'='+encodeURIComponent(pair[1]))
595 for each (pair in data)].join('&');
596 data = string_input_stream(data);
597 return mime_input_stream(
598 data, [["Content-Type", "application/x-www-form-urlencoded"]]);
603 * Centers the viewport around a given element.
605 * @param win The window to scroll.
606 * @param elem The element arund which we put the viewport.
608 function center_in_viewport (win, elem) {
609 let point = abs_point(elem);
611 point.x -= win.innerWidth / 2;
612 point.y -= win.innerHeight / 2;
614 win.scrollTo(point.x, point.y);
619 * Simple predicate returns true if elem is an nsIDOMNode or
622 function dom_node_or_window_p (elem) {
623 if (elem instanceof Ci.nsIDOMNode)
625 if (elem instanceof Ci.nsIDOMWindow)
631 * Given a hook name, a buffer and a function, waits until the buffer document
632 * has fully loaded, then calls the function with the buffer as its only
635 * @param {String} The hook name.
636 * @param {buffer} The buffer.
637 * @param {function} The function to call with the buffer as its argument once
638 * the buffer has loaded.
640 function do_when (hook, buffer, fun) {
641 if (buffer.browser.webProgress.isLoadingDocument)
642 add_hook.call(buffer, hook, fun);
649 * evaluate string s as javascript in the 'this' scope in which evaluate
652 function evaluate (s) {
654 var obs = Cc["@mozilla.org/observer-service;1"]
655 .getService(Ci.nsIObserverService);
656 obs.notifyObservers(null, "startupcache-invalidate", null);
657 var temp = get_temporary_file("conkeror-evaluate.tmp.js");
658 write_text_file(temp, s);
659 var url = make_uri(temp).spec;
660 return load_url(url, this);
662 if (temp && temp.exists())
669 * set_protocol_handler takes a protocol and a handler spec. If the
670 * handler is true, Mozilla will (try to) handle this protocol internally.
671 * If the handler null, the user will be prompted for a handler when a
672 * resource of this protocol is requested. If the handler is an nsIFile,
673 * the program it gives will be launched with the url as an argument. If
674 * the handler is a string, it will be interpreted as an URL template for
675 * a web service and the sequence '%s' within it will be replaced by the
678 function set_protocol_handler (protocol, handler) {
679 var eps = Cc["@mozilla.org/uriloader/external-protocol-service;1"]
680 .getService(Ci.nsIExternalProtocolService);
681 var info = eps.getProtocolHandlerInfo(protocol);
682 var expose_pref = "network.protocol-handler.expose."+protocol;
683 if (handler == true) {
685 clear_default_pref(expose_pref);
686 } else if (handler) {
688 if (handler instanceof Ci.nsIFile) {
689 var h = Cc["@mozilla.org/uriloader/local-handler-app;1"]
690 .createInstance(Ci.nsILocalHandlerApp);
691 h.executable = handler;
692 } else if (typeof handler == "string") {
693 h = Cc["@mozilla.org/uriloader/web-handler-app;1"]
694 .createInstance(Ci.nsIWebHandlerApp);
695 var uri = make_uri(handler);
697 h.uriTemplate = handler;
699 info.alwaysAskBeforeHandling = false;
700 info.preferredAction = Ci.nsIHandlerInfo.useHelperApp;
701 info.possibleApplicationHandlers.clear();
702 info.possibleApplicationHandlers.appendElement(h, false);
703 info.preferredApplicationHandler = h;
704 session_pref(expose_pref, false);
707 info.alwaysAskBeforeHandling = true;
708 info.preferredAction = Ci.nsIHandlerInfo.alwaysAsk;
709 session_pref(expose_pref, false);
711 var hs = Cc["@mozilla.org/uriloader/handler-service;1"]
712 .getService(Ci.nsIHandlerService);