2 * (C) Copyright 2007-2009 John J. Foerch
3 * (C) Copyright 2007-2008 Jeremy Maitin-Shepard
5 * Portions of this file are derived from Vimperator,
6 * (C) Copyright 2006-2007 Martin Stubenschrott.
8 * Use, modification, and distribution are subject to the terms specified in the
16 require("mime-type-override.js");
17 require("minibuffer-read-mime-type.js");
19 var browser_object_classes = {};
22 * browser_object_class
24 * In normal cases, make a new browser_object_class with the function,
25 * `define_browser_object_class'.
27 * name: See note on `define_browser_object_class'.
31 * handler: a coroutine called as: handler(I, prompt). `I' is a normal
32 * interactive context. `prompt' is there to pass along as the
33 * $prompt of various minibuffer read procedures, if needed.
35 * $hint: short string (usually verb and noun) to describe the UI
36 * of the browser object class to the user. Only used by
37 * browser object classes which make use of the minibuffer.
39 define_keywords("$hint");
40 function browser_object_class (name, doc, handler) {
43 this.handler = handler;
45 this.hint = arguments.$hint;
49 * define_browser_object_class
51 * In normal cases, make a new browser_object_class with the function,
52 * `define_browser_object_class'.
54 * name: the name of the browser object class. multiword names should be
55 * hyphenated. From this name, a variable browser_object_NAME and
56 * an interactive command browser-object-NAME will be generated.
58 * Other arguments are as for `browser_object_class'.
61 function define_browser_object_class (name, doc, handler) {
63 var varname = 'browser_object_'+name.replace('-','_','g');
64 var ob = conkeror[varname] =
65 new browser_object_class(name, doc, handler,
66 forward_keywords(arguments));
67 interactive("browser-object-"+name,
68 "A prefix command to specify that the following command operate "+
69 "on objects of type: "+name+".",
70 function (I) { I.browser_object = ob; },
76 * xpath_browser_object_handler
78 * This generates a function of the type needed for a handler of a
79 * browser object class. The handler uses `read_hinted_element' of
80 * hints.js to let the user pick a DOM node from those matched by
83 function xpath_browser_object_handler (xpath_expression) {
84 return function (I, prompt) {
85 var result = yield I.buffer.window.minibuffer.read_hinted_element(
88 $hint_xpath_expression = xpath_expression);
89 yield co_return(result);
93 define_browser_object_class("images",
94 "Browser object class for selecting an html:img via hinting.",
95 xpath_browser_object_handler("//img | //xhtml:img"),
96 $hint = "select image");
98 define_browser_object_class("frames",
99 "Browser object class for selecting a frame or iframe via hinting.",
100 function (I, prompt) {
101 var doc = I.buffer.document;
102 // Check for any frames or visible iframes
103 var skip_hints = true;
104 if (doc.getElementsByTagName("frame").length > 0)
107 let topwin = I.buffer.top_frame;
108 let iframes = doc.getElementsByTagName("iframe");
109 for (var i = 0, nframes = iframes.length; i < nframes; i++) {
110 let style = topwin.getComputedStyle(iframes[i], "");
111 if (style.display == "none" || style.visibility == "hidden")
118 // only one frame (the top-level one), no need to use the hints system
119 yield co_return(I.buffer.top_frame);
121 var result = yield I.buffer.window.minibuffer.read_hinted_element(
124 $hint_xpath_expression = "//iframe | //frame | //xhtml:iframe | //xhtml:frame");
125 yield co_return(result);
127 $hint = "select frame");
129 define_browser_object_class("links",
130 "Browser object class for selecting a hyperlink, form field, "+
131 "or link-like element, via hinting.",
132 xpath_browser_object_handler(
133 "//*[@onclick or @onmouseover or @onmousedown or @onmouseup or "+
134 "@oncommand or @role='link' or @role='button' or @role='menuitem'] | "+
135 "//input[not(@type='hidden')] | //a[@href] | //area | "+
136 "//iframe | //textarea | //button | //select | "+
137 "//*[@contenteditable = 'true'] | "+
138 "//xhtml:*[@onclick or @onmouseover or @onmousedown or @onmouseup or "+
139 "@oncommand or @role='link' or @role='button' or @role='menuitem'] | "+
140 "//xhtml:input[not(@type='hidden')] | //xhtml:a[@href] | //xhtml:area | "+
141 "//xhtml:iframe | //xhtml:textarea | //xhtml:button | //xhtml:select | " +
142 "//xhtml:*[@contenteditable = 'true'] | "+
144 $hint = "select link");
146 define_browser_object_class("mathml",
147 "Browser object class for selecting a MathML node via hinting.",
148 xpath_browser_object_handler("//m:math"),
149 $hint = "select MathML element");
151 define_browser_object_class("top",
152 "Browser object class which returns the top frame of the document.",
153 function (I, prompt) { return I.buffer.top_frame; });
155 define_browser_object_class("url",
156 "Browser object class which prompts the user for an url or webjump.",
157 function (I, prompt) {
158 var result = yield I.buffer.window.minibuffer.read_url($prompt = prompt);
159 yield co_return(result);
161 $hint = "enter URL/webjump");
163 define_browser_object_class("paste-url",
164 "Browser object which reads an url from the X Primary Selection, "+
165 "falling back on the clipboard for operating systems which lack one.",
166 function (I, prompt) {
167 var url = read_from_x_primary_selection();
169 url = url.replace(/^\s*|\s*$/,"");
170 // add http:// if needed
171 if (url.match(/^[^:]+\./)) {
172 url = "http://" + url;
175 return make_uri(url).spec;
177 throw new interactive_error("error: malformed url: "+url);
181 define_browser_object_class("file",
182 "Browser object which prompts for a file name.",
183 function (I, prompt) {
184 var result = yield I.buffer.window.minibuffer.read_file(
186 $history = I.command.name+"/file",
187 $initial_value = I.local.cwd.path);
188 yield co_return(result);
190 $hint = "enter file name");
192 define_browser_object_class("alt",
193 "Browser object class which returns the alt text of an html:img, "+
194 "selected via hinting",
195 function (I, prompt) {
196 var result = yield I.buffer.window.minibuffer.read_hinted_element(
199 $hint_xpath_expression = "//img[@alt] | //xhtml:img[@alt]");
200 yield co_return(result.alt);
202 $hint = "select image for alt-text");
204 define_browser_object_class("title",
205 "Browser object class which returns the title attribute of an element, "+
206 "selected via hinting",
207 function (I, prompt) {
208 var result = yield I.buffer.window.minibuffer.read_hinted_element(
211 $hint_xpath_expression = "//*[@title] | //xhtml:*[@title]");
212 yield co_return(result.title);
214 $hint = "select element for title attribute");
216 define_browser_object_class("title-or-alt",
217 "Browser object which is the union of browser-object-alt and "+
218 "browser-object-title, with title having higher precedence in "+
219 "the case of an element that has both.",
220 function (I, prompt) {
221 var result = yield I.buffer.window.minibuffer.read_hinted_element(
224 $hint_xpath_expression = "//img[@alt] | //*[@title] | //xhtml:img[@alt] | //xhtml:*[@title]");
225 yield co_return(result.title ? result.title : result.alt);
227 $hint = "select element for title or alt-text");
229 define_browser_object_class("scrape-url",
230 "Browser object which lets the user choose an url from a list of "+
231 "urls scraped from the source code of the document.",
232 function (I, prompt) {
233 var completions = I.buffer.document.documentElement.innerHTML
234 .match(/https?:[^\s<>)"]*/g)
235 .filter(remove_duplicates_filter());
236 var completer = all_word_completer($completions = completions);
237 var result = yield I.buffer.window.minibuffer.read(
239 $completer = completer,
240 $initial_value = null,
241 $auto_complete = "url",
243 $match_required = false);
244 yield co_return(result);
246 $hint = "choose scraped URL");
248 define_browser_object_class("up-url",
249 "Browser object which returns the url one level above the current one.",
250 function (I, prompt) {
251 return compute_up_url(I.buffer.current_uri);
254 define_browser_object_class("focused-element",
255 "Browser object which returns the focused element.",
256 function (I, prompt) { return I.buffer.focused_element; });
258 define_browser_object_class("dom-node", null,
259 xpath_browser_object_handler("//* | //xhtml:*"),
260 $hint = "select DOM node");
262 define_browser_object_class("fragment-link",
263 "Browser object class which returns a link to the specified fragment of a page",
264 function (I, prompt) {
265 var elem = yield I.buffer.window.minibuffer.read_hinted_element(
268 $hint_xpath_expression = "//*[@id] | //a[@name] | //xhtml:*[@id] | //xhtml:a[@name]");
269 yield co_return(page_fragment_load_spec(elem));
271 $hint = "select element to link to");
273 interactive("browser-object-text",
274 "Composable browser object which returns the text of another object.",
276 // our job here is to modify the interactive context.
277 // set I.browser_object to a browser_object which calls the
278 // original one, then returns its text.
279 var b = I.browser_object;
280 I.browser_object = function (I) {
281 I.browser_object = b;
282 var e = yield read_browser_object(I);
283 if (e instanceof Ci.nsIDOMHTMLImageElement)
284 yield co_return(e.getAttribute("alt"));
285 yield co_return(e.textContent);
290 function get_browser_object (I) {
291 var obj = I.browser_object;
294 // if there was no interactive browser-object,
295 // binding_browser_object becomes the default.
296 if (obj === undefined) {
297 obj = I.binding_browser_object;
299 // if the command's default browser object is a non-null literal,
300 // it overrides an interactive browser-object, but not a binding
302 if (cmd.browser_object != null &&
303 (! (cmd.browser_object instanceof browser_object_class)) &&
304 (I.binding_browser_object === undefined))
306 obj = cmd.browser_object;
308 // if we still have no browser-object, look for a page-mode
309 // default, or finally the command default.
310 if (obj === undefined) {
312 I.buffer.default_browser_object_classes[cmd.name]) ||
319 function read_browser_object (I) {
320 var browser_object = get_browser_object(I);
321 if (browser_object === undefined)
322 throw interactive_error("No browser object");
325 // literals cannot be overridden
326 if (browser_object instanceof Function) {
327 result = yield browser_object(I);
328 yield co_return(result);
330 if (! (browser_object instanceof browser_object_class))
331 yield co_return(browser_object);
333 var prompt = I.command.prompt;
335 prompt = I.command.name.split(/-|_/).join(" ");
336 prompt = prompt[0].toUpperCase() + prompt.substring(1);
338 if (I.target != null)
339 prompt += TARGET_PROMPTS[I.target];
340 if (browser_object.hint)
341 prompt += " (" + browser_object.hint + ")";
344 result = yield browser_object.handler.call(null, I, prompt);
345 yield co_return(result);
350 * This is a simple wrapper function that sets focus to elem, and
351 * bypasses the automatic focus prevention system, which might
352 * otherwise prevent this from happening.
354 function browser_set_element_focus (buffer, elem, prevent_scroll) {
355 if (! dom_node_or_window_p(elem))
360 set_focus_no_scroll(buffer.window, elem);
365 function browser_element_focus (buffer, elem) {
366 if (! dom_node_or_window_p(elem))
369 if (elem instanceof Ci.nsIDOMXULTextBoxElement)
370 elem = elem.wrappedJSObject.inputField; // focus the input field
372 browser_set_element_focus(buffer, elem);
373 if (elem instanceof Ci.nsIDOMWindow)
376 // If it is not a window, it must be an HTML element
379 if (elem instanceof Ci.nsIDOMHTMLFrameElement ||
380 elem instanceof Ci.nsIDOMHTMLIFrameElement)
382 elem.contentWindow.focus();
385 if (elem instanceof Ci.nsIDOMHTMLAreaElement) {
386 var coords = elem.getAttribute("coords").split(",");
387 x = Number(coords[0]);
388 y = Number(coords[1]);
391 var doc = elem.ownerDocument;
392 var evt = doc.createEvent("MouseEvents");
394 evt.initMouseEvent("mouseover", true, true, doc.defaultView, 1, x, y, 0, 0, 0, 0, 0, 0, 0, null);
395 elem.dispatchEvent(evt);
398 function browser_object_follow (buffer, target, elem) {
399 // XXX: would be better to let nsILocalFile objects be load_specs
400 if (elem instanceof Ci.nsILocalFile)
404 if (elem instanceof load_spec)
405 e = load_spec_element(elem);
409 browser_set_element_focus(buffer, e, true /* no scroll */);
411 var no_click = (((elem instanceof load_spec) &&
412 load_spec_forced_charset(elem)) ||
413 (e instanceof load_spec) ||
414 (e instanceof Ci.nsIDOMWindow) ||
415 (e instanceof Ci.nsIDOMHTMLFrameElement) ||
416 (e instanceof Ci.nsIDOMHTMLIFrameElement) ||
417 (e instanceof Ci.nsIDOMHTMLLinkElement) ||
418 (e instanceof Ci.nsIDOMHTMLImageElement &&
419 !e.hasAttribute("onmousedown") && !e.hasAttribute("onclick")));
421 if (target == FOLLOW_DEFAULT && !no_click) {
423 if (e instanceof Ci.nsIDOMHTMLAreaElement) {
424 var coords = e.getAttribute("coords").split(",");
425 if (coords.length >= 2) {
426 x = Number(coords[0]) + 1;
427 y = Number(coords[1]) + 1;
430 dom_node_click(e, x, y);
434 var spec = load_spec(elem);
436 if (load_spec_uri_string(spec).match(/^\s*javascript:/)) {
437 // it is nonsensical to follow a javascript url in a different
439 target = FOLLOW_DEFAULT;
440 } else if (!(buffer instanceof content_buffer) &&
441 (target == FOLLOW_CURRENT_FRAME ||
442 target == FOLLOW_DEFAULT ||
443 target == OPEN_CURRENT_BUFFER))
445 target = OPEN_NEW_BUFFER;
449 case FOLLOW_CURRENT_FRAME:
450 var current_frame = load_spec_source_frame(spec);
451 if (current_frame && current_frame != buffer.top_frame) {
452 var target_obj = get_web_navigation_for_frame(current_frame);
453 apply_load_spec(target_obj, spec);
457 case OPEN_CURRENT_BUFFER:
460 case OPEN_NEW_WINDOW:
461 case OPEN_NEW_BUFFER:
462 case OPEN_NEW_BUFFER_BACKGROUND:
463 if (dom_node_or_window_p(e))
467 create_buffer(buffer.window,
468 buffer_creator(content_buffer,
476 * Follow a link-like element by generating fake mouse events.
478 function dom_node_click (elem, x, y) {
479 var doc = elem.ownerDocument;
480 var view = doc.defaultView;
482 var evt = doc.createEvent("MouseEvents");
483 evt.initMouseEvent("mousedown", true, true, view, 1, x, y, 0, 0, /*ctrl*/ 0, /*event.altKey*/0,
484 /*event.shiftKey*/ 0, /*event.metaKey*/ 0, 0, null);
485 elem.dispatchEvent(evt);
487 evt = doc.createEvent("MouseEvents");
488 evt.initMouseEvent("click", true, true, view, 1, x, y, 0, 0, /*ctrl*/ 0, /*event.altKey*/0,
489 /*event.shiftKey*/ 0, /*event.metaKey*/ 0, 0, null);
490 elem.dispatchEvent(evt);
492 evt = doc.createEvent("MouseEvents");
493 evt.initMouseEvent("mouseup", true, true, view, 1, x, y, 0, 0, /*ctrl*/ 0, /*event.altKey*/0,
494 /*event.shiftKey*/ 0, /*event.metaKey*/ 0, 0, null);
495 elem.dispatchEvent(evt);
499 function follow (I, target) {
501 target = FOLLOW_DEFAULT;
503 if (target == OPEN_CURRENT_BUFFER)
504 check_buffer(I.buffer, content_buffer);
505 var element = yield read_browser_object(I);
507 element = load_spec(element);
508 if (I.forced_charset)
509 element.forced_charset = I.forced_charset;
511 browser_object_follow(I.buffer, target, element);
514 function follow_new_buffer (I) {
515 yield follow(I, OPEN_NEW_BUFFER);
518 function follow_new_buffer_background (I) {
519 yield follow(I, OPEN_NEW_BUFFER_BACKGROUND);
522 function follow_new_window (I) {
523 yield follow(I, OPEN_NEW_WINDOW);
526 function follow_current_frame (I) {
527 yield follow(I, FOLLOW_CURRENT_FRAME);
530 function follow_current_buffer (I) {
531 yield follow(I, OPEN_CURRENT_BUFFER);
535 function element_get_load_target_label (element) {
536 if (element instanceof Ci.nsIDOMWindow)
538 if (element instanceof Ci.nsIDOMHTMLFrameElement)
540 if (element instanceof Ci.nsIDOMHTMLIFrameElement)
545 function element_get_operation_label (element, op_name, suffix) {
546 var target_label = element_get_load_target_label(element);
547 if (target_label != null)
548 target_label = " " + target_label;
553 suffix = " " + suffix;
557 return op_name + target_label + suffix + ":";
561 function browser_element_copy (buffer, elem) {
563 var spec = load_spec(elem);
566 if (typeof elem == "string" || elem instanceof String)
569 text = load_spec_uri_string(spec);
571 if (!(elem instanceof Ci.nsIDOMNode))
572 throw interactive_error("Element has no associated text to copy.");
573 var tag = elem.localName.toLowerCase();
574 if ((tag == "input" || tag == "button") &&
575 elem.type == "submit" && elem.form && elem.form.action)
577 text = elem.form.action;
578 } else if (tag == "input" || tag == "textarea") {
580 } else if (tag == "select") {
581 if (elem.selectedIndex >= 0)
582 text = elem.item(elem.selectedIndex).text;
584 text = elem.textContent;
587 browser_set_element_focus(buffer, elem);
588 writeToClipboard(text);
589 buffer.window.minibuffer.message("Copied: " + text);
593 define_variable("view_source_use_external_editor", false,
594 "When true, the `view-source' command will send its document to "+
595 "your external editor.");
597 define_variable("view_source_function", null,
598 "May be set to a user-defined function for viewing source code. "+
599 "The function should accept an nsILocalFile of the filename as "+
600 "its one positional argument, and it will also be called with "+
601 "the keyword `$temporary', whose value will be true if the file "+
602 "is considered temporary, and therefore the function must take "+
603 "responsibility for deleting it.");
605 function browser_object_view_source (buffer, target, elem) {
606 if (view_source_use_external_editor || view_source_function) {
607 var spec = load_spec(elem);
609 let [file, temp] = yield download_as_temporary(spec,
611 $action = "View source");
612 if (view_source_use_external_editor)
613 yield open_file_with_external_editor(file, $temporary = temp);
615 yield view_source_function(file, $temporary = temp);
620 var window = buffer.window;
621 if (elem.localName) {
622 switch (elem.localName.toLowerCase()) {
623 case "frame": case "iframe":
624 win = elem.contentWindow;
627 view_mathml_source(window, charset, elem);
630 throw new Error("Invalid browser element");
636 var url_s = win.location.href;
637 if (url_s.substring (0,12) != "view-source:") {
639 browser_object_follow(buffer, target, "view-source:" + url_s);
640 } catch(e) { dump_error(e); }
643 browser_object_follow(buffer, target, url_s.replace(/^view-source\:/, ''));
644 } catch(e) { dump_error(e); }
648 function view_source (I, target) {
651 target = OPEN_CURRENT_BUFFER;
652 var element = yield read_browser_object(I);
653 yield browser_object_view_source(I.buffer, target, element);
656 function view_source_new_buffer (I) {
657 yield view_source(I, OPEN_NEW_BUFFER);
660 function view_source_new_window (I) {
661 yield view_source(I, OPEN_NEW_WINDOW);
665 function browser_element_shell_command (buffer, elem, command, cwd) {
666 var spec = load_spec(elem);
667 yield download_as_temporary(spec,
669 $shell_command = command,
670 $shell_command_cwd = cwd);