read_browser_object: throw error when there is no object to read
[conkeror.git] / modules / element.js
blobb0891aa209368cc06cdeda110e550c676151044f
1 /**
2  * (C) Copyright 2007-2009 John J. Foerch
3  * (C) Copyright 2007-2008 Jeremy Maitin-Shepard
4  *
5  * Portions of this file are derived from Vimperator,
6  * (C) Copyright 2006-2007 Martin Stubenschrott.
7  *
8  * Use, modification, and distribution are subject to the terms specified in the
9  * COPYING file.
10 **/
12 in_module(null);
14 require("hints.js");
15 require("save.js");
16 require("mime-type-override.js");
17 require("minibuffer-read-mime-type.js");
19 var browser_object_classes = {};
21 /**
22  * browser_object_class
23  *
24  *   In normal cases, make a new browser_object_class with the function,
25  * `define_browser_object_class'.
26  *
27  * name: See note on `define_browser_object_class'.
28  *
29  * doc: a docstring
30  *
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.
34  *
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.
38  */
39 define_keywords("$hint");
40 function browser_object_class (name, doc, handler) {
41     keywords(arguments);
42     this.name = name;
43     this.handler = handler;
44     this.doc = doc;
45     this.hint = arguments.$hint;
48 /**
49  * define_browser_object_class
50  *
51  *   In normal cases, make a new browser_object_class with the function,
52  * `define_browser_object_class'.
53  *
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.
57  *
58  *   Other arguments are as for `browser_object_class'.
59  */
60 // keywords: $hint
61 function define_browser_object_class (name, doc, handler) {
62     keywords(arguments);
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; },
71         $prefix = true);
72     return ob;
75 /**
76  * xpath_browser_object_handler
77  *
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
81  * `xpath_expression'.
82  */
83 function xpath_browser_object_handler (xpath_expression) {
84     return function (I, prompt) {
85         var result = yield I.buffer.window.minibuffer.read_hinted_element(
86             $buffer = I.buffer,
87             $prompt = prompt,
88             $hint_xpath_expression = xpath_expression);
89         yield co_return(result);
90     };
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)
105             skip_hints = false;
106         else {
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")
112                     continue;
113                 skip_hints = false;
114                 break;
115             }
116         }
117         if (skip_hints) {
118             // only one frame (the top-level one), no need to use the hints system
119             yield co_return(I.buffer.top_frame);
120         }
121         var result = yield I.buffer.window.minibuffer.read_hinted_element(
122             $buffer = I.buffer,
123             $prompt = prompt,
124             $hint_xpath_expression = "//iframe | //frame | //xhtml:iframe | //xhtml:frame");
125         yield co_return(result);
126     },
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 @oncommand or @role='link' or @role='button' or @role='menuitem'] | " +
134         "//input[not(@type='hidden')] | //a | //area | //iframe | //textarea | //button | //select | " +
135         "//*[@contenteditable = 'true'] |" +
136         "//xhtml:*[@onclick or @onmouseover or @onmousedown or @onmouseup or @oncommand or @role='link' or @role='button' or @role='menuitem'] | " +
137         "//xhtml:input[not(@type='hidden')] | //xhtml:a | //xhtml:area | //xhtml:iframe | //xhtml:textarea | //xhtml:button | //xhtml:select | " +
138         "//xhtml:*[@contenteditable = 'true'] | "+
139         "//svg:a"),
140     $hint = "select link");
142 define_browser_object_class("mathml",
143     "Browser object class for selecting a MathML node via hinting.",
144     xpath_browser_object_handler("//m:math"),
145     $hint = "select MathML element");
147 define_browser_object_class("top",
148     "Browser object class which returns the top frame of the document.",
149     function (I, prompt) { return I.buffer.top_frame; });
151 define_browser_object_class("url",
152     "Browser object class which prompts the user for an url or webjump.",
153     function (I, prompt) {
154         var result = yield I.buffer.window.minibuffer.read_url($prompt = prompt);
155         yield co_return(result);
156     },
157     $hint = "enter URL/webjump");
159 define_browser_object_class("paste-url",
160     "Browser object which reads an url from the X Primary Selection, "+
161     "falling back on the clipboard for operating systems which lack one.",
162     function (I, prompt) {
163                 var url = read_from_x_primary_selection();
164                 // trim spaces
165                 url = url.replace(/^\s*|\s*$/,"");
166                 // add http:// if needed
167                 if (url.match(/^[^:]+\./)) {
168                         url = "http://" + url;
169                 }
170         try {
171             return make_uri(url).spec;
172         } catch (e) {
173             throw new interactive_error("error: malformed url: "+url);
174         }
175     });
177 define_browser_object_class("file",
178     "Browser object which prompts for a file name.",
179     function (I, prompt) {
180         var result = yield I.buffer.window.minibuffer.read_file(
181             $prompt = prompt,
182             $history = I.command.name+"/file",
183             $initial_value = I.local.cwd.path);
184         yield co_return(result);
185     },
186     $hint = "enter file name");
188 define_browser_object_class("alt",
189     "Browser object class which returns the alt text of an html:img, "+
190     "selected via hinting",
191     function (I, prompt) {
192         var result = yield I.buffer.window.minibuffer.read_hinted_element(
193             $buffer = I.buffer,
194             $prompt = prompt,
195             $hint_xpath_expression = "//img[@alt] | //xhtml:img[@alt]");
196         yield co_return(result.alt);
197     },
198     $hint = "select image for alt-text");
200 define_browser_object_class("title",
201     "Browser object class which returns the title attribute of an element, "+
202     "selected via hinting",
203     function (I, prompt) {
204         var result = yield I.buffer.window.minibuffer.read_hinted_element(
205             $buffer = I.buffer,
206             $prompt = prompt,
207             $hint_xpath_expression = "//*[@title] | //xhtml:*[@title]");
208         yield co_return(result.title);
209     },
210     $hint = "select element for title attribute");
212 define_browser_object_class("title-or-alt",
213     "Browser object which is the union of browser-object-alt and "+
214     "browser-object-title, with title having higher precedence in "+
215     "the case of an element that has both.",
216     function (I, prompt) {
217         var result = yield I.buffer.window.minibuffer.read_hinted_element(
218             $buffer = I.buffer,
219             $prompt = prompt,
220             $hint_xpath_expression = "//img[@alt] | //*[@title] | //xhtml:img[@alt] | //xhtml:*[@title]");
221         yield co_return(result.title ? result.title : result.alt);
222     },
223     $hint = "select element for title or alt-text");
225 define_browser_object_class("scrape-url",
226     "Browser object which lets the user choose an url from a list of "+
227     "urls scraped from the source code of the document.",
228     function (I, prompt) {
229         var completions = I.buffer.document.documentElement.innerHTML
230             .match(/http:[^\s>"]*/g)
231             .filter(remove_duplicates_filter());
232         var completer = prefix_completer($completions = completions);
233         var result = yield I.buffer.window.minibuffer.read(
234             $prompt = prompt,
235             $completer = completer,
236             $initial_value = null,
237             $auto_complete = "url",
238             $select,
239             $match_required = false);
240         yield co_return(result);
241     },
242     $hint = "choose scraped URL");
244 define_browser_object_class("up-url",
245     "Browser object which returns the url one level above the current one.",
246     function (I, prompt) {
247         var up = compute_url_up_path(I.buffer.current_uri.spec);
248         return I.buffer.current_uri.resolve(up);
249     });
251 define_browser_object_class("focused-element",
252     "Browser object which returns the focused element.",
253     function (I, prompt) { return I.buffer.focused_element; });
255 define_browser_object_class("dom-node", null,
256     xpath_browser_object_handler("//* | //xhtml:*"),
257     $hint = "select DOM node");
259 define_browser_object_class("fragment-link",
260     "Browser object class which returns a link to the specified fragment of a page",
261     function (I, prompt) {
262         var elem = yield I.buffer.window.minibuffer.read_hinted_element(
263             $buffer = I.buffer,
264             $prompt = prompt,
265             $hint_xpath_expression = "//*[@id] | //a[@name] | //xhtml:*[@id] | //xhtml:a[@name]");
266         yield co_return(page_fragment_load_spec(elem));
267     },
268     $hint = "select element to link to");
270 interactive("browser-object-text",
271     "Composable browser object which returns the text of another object.",
272     function (I) {
273         // our job here is to modify the interactive context.
274         // set I.browser_object to a browser_object which calls the
275         // original one, then returns its text.
276         var b = I.browser_object;
277         I.browser_object = function (I) {
278             I.browser_object = b;
279             var e = yield read_browser_object(I);
280             if (e instanceof Ci.nsIDOMHTMLImageElement)
281                 yield co_return(e.getAttribute("alt"));
282             yield co_return(e.textContent);
283         }
284     },
285     $prefix);
287 function read_browser_object (I) {
288     var browser_object = I.browser_object;
289     if (browser_object === undefined)
290         throw interactive_error("No browser object");
292     var result;
293     // literals cannot be overridden
294     if (browser_object instanceof Function) {
295         result = yield browser_object(I);
296         yield co_return(result);
297     }
298     if (! (browser_object instanceof browser_object_class))
299         yield co_return(browser_object);
301     var prompt = I.command.prompt;
302     if (! prompt) {
303         prompt = I.command.name.split(/-|_/).join(" ");
304         prompt = prompt[0].toUpperCase() + prompt.substring(1);
305     }
306     if (I.target != null)
307         prompt += TARGET_PROMPTS[I.target];
308     if (browser_object.hint)
309         prompt += " (" + browser_object.hint + ")";
310     prompt += ":";
312     result = yield browser_object.handler.call(null, I, prompt);
313     yield co_return(result);
318  * This is a simple wrapper function that sets focus to elem, and
319  * bypasses the automatic focus prevention system, which might
320  * otherwise prevent this from happening.
321  */
322 function browser_set_element_focus (buffer, elem, prevent_scroll) {
323     if (!element_dom_node_or_window_p(elem))
324         return;
325     if (! elem.focus)
326         return;
327     if (prevent_scroll)
328         set_focus_no_scroll(buffer.window, elem);
329     else
330         elem.focus();
333 function browser_element_focus (buffer, elem) {
334     if (!element_dom_node_or_window_p(elem))
335         return;
337     if (elem instanceof Ci.nsIDOMXULTextBoxElement)
338         elem = elem.wrappedJSObject.inputField; // focus the input field
340     browser_set_element_focus(buffer, elem);
341     if (elem instanceof Ci.nsIDOMWindow)
342         return;
344     // If it is not a window, it must be an HTML element
345     var x = 0;
346     var y = 0;
347     if (elem instanceof Ci.nsIDOMHTMLFrameElement ||
348         elem instanceof Ci.nsIDOMHTMLIFrameElement)
349     {
350         elem.contentWindow.focus();
351         return;
352     }
353     if (elem instanceof Ci.nsIDOMHTMLAreaElement) {
354         var coords = elem.getAttribute("coords").split(",");
355         x = Number(coords[0]);
356         y = Number(coords[1]);
357     }
359     var doc = elem.ownerDocument;
360     var evt = doc.createEvent("MouseEvents");
362     evt.initMouseEvent("mouseover", true, true, doc.defaultView, 1, x, y, 0, 0, 0, 0, 0, 0, 0, null);
363     elem.dispatchEvent(evt);
366 function browser_object_follow (buffer, target, elem) {
367     // XXX: would be better to let nsILocalFile objects be load_specs
368     if (elem instanceof Ci.nsILocalFile)
369         elem = elem.path;
371     var e;
372     if (elem instanceof load_spec)
373         e = load_spec_element(elem);
374     if (! e)
375         e = elem;
377     browser_set_element_focus(buffer, e, true /* no scroll */);
379     var no_click = (((elem instanceof load_spec) &&
380                      load_spec_forced_charset(elem)) ||
381                     (e instanceof load_spec) ||
382                     (e instanceof Ci.nsIDOMWindow) ||
383                     (e instanceof Ci.nsIDOMHTMLFrameElement) ||
384                     (e instanceof Ci.nsIDOMHTMLIFrameElement) ||
385                     (e instanceof Ci.nsIDOMHTMLLinkElement) ||
386                     (e instanceof Ci.nsIDOMHTMLImageElement &&
387                      !e.hasAttribute("onmousedown") && !e.hasAttribute("onclick")));
389     if (target == FOLLOW_DEFAULT && !no_click) {
390         var x = 1, y = 1;
391         if (e instanceof Ci.nsIDOMHTMLAreaElement) {
392             var coords = e.getAttribute("coords").split(",");
393             if (coords.length >= 2) {
394                 x = Number(coords[0]) + 1;
395                 y = Number(coords[1]) + 1;
396             }
397         }
398         dom_node_click(e, x, y);
399         return;
400     }
402     var spec = load_spec(elem);
404     if (load_spec_uri_string(spec).match(/^\s*javascript:/)) {
405         // it is nonsensical to follow a javascript url in a different
406         // buffer or window
407         target = FOLLOW_DEFAULT;
408     } else if (!(buffer instanceof content_buffer) &&
409         (target == FOLLOW_CURRENT_FRAME ||
410          target == FOLLOW_DEFAULT ||
411          target == OPEN_CURRENT_BUFFER))
412     {
413         target = OPEN_NEW_BUFFER;
414     }
416     switch (target) {
417     case FOLLOW_CURRENT_FRAME:
418         var current_frame = load_spec_source_frame(spec);
419         if (current_frame && current_frame != buffer.top_frame) {
420             var target_obj = get_web_navigation_for_frame(current_frame);
421             apply_load_spec(target_obj, spec);
422             break;
423         }
424     case FOLLOW_DEFAULT:
425     case OPEN_CURRENT_BUFFER:
426         buffer.load(spec);
427         break;
428     case OPEN_NEW_WINDOW:
429     case OPEN_NEW_BUFFER:
430     case OPEN_NEW_BUFFER_BACKGROUND:
431         create_buffer(buffer.window,
432                       buffer_creator(content_buffer,
433                                      $opener = buffer,
434                                      $load = spec),
435                       target);
436     }
440  * Follow a link-like element by generating fake mouse events.
441  */
442 function dom_node_click (elem, x, y) {
443     var doc = elem.ownerDocument;
444     var view = doc.defaultView;
446     var evt = doc.createEvent("MouseEvents");
447     evt.initMouseEvent("mousedown", true, true, view, 1, x, y, 0, 0, /*ctrl*/ 0, /*event.altKey*/0,
448                        /*event.shiftKey*/ 0, /*event.metaKey*/ 0, 0, null);
449     elem.dispatchEvent(evt);
451     evt = doc.createEvent("MouseEvents");
452     evt.initMouseEvent("click", true, true, view, 1, x, y, 0, 0, /*ctrl*/ 0, /*event.altKey*/0,
453                        /*event.shiftKey*/ 0, /*event.metaKey*/ 0, 0, null);
454     elem.dispatchEvent(evt);
456     evt = doc.createEvent("MouseEvents");
457     evt.initMouseEvent("mouseup", true, true, view, 1, x, y, 0, 0, /*ctrl*/ 0, /*event.altKey*/0,
458                        /*event.shiftKey*/ 0, /*event.metaKey*/ 0, 0, null);
459     elem.dispatchEvent(evt);
463 function follow (I, target) {
464     if (target == null)
465         target = FOLLOW_DEFAULT;
466     I.target = target;
467     if (target == OPEN_CURRENT_BUFFER)
468         check_buffer(I.buffer, content_buffer);
469     var element = yield read_browser_object(I);
470     try {
471         element = load_spec(element);
472         if (I.forced_charset)
473             element.forced_charset = I.forced_charset;
474     } catch (e) {}
475     browser_object_follow(I.buffer, target, element);
478 function follow_new_buffer (I) {
479     yield follow(I, OPEN_NEW_BUFFER);
482 function follow_new_buffer_background (I) {
483     yield follow(I, OPEN_NEW_BUFFER_BACKGROUND);
486 function follow_new_window (I) {
487     yield follow(I, OPEN_NEW_WINDOW);
490 function follow_current_frame (I) {
491     yield follow(I, FOLLOW_CURRENT_FRAME);
494 function follow_current_buffer (I) {
495     yield follow(I, OPEN_CURRENT_BUFFER);
499 function element_get_load_target_label (element) {
500     if (element instanceof Ci.nsIDOMWindow)
501         return "page";
502     if (element instanceof Ci.nsIDOMHTMLFrameElement)
503         return "frame";
504     if (element instanceof Ci.nsIDOMHTMLIFrameElement)
505         return "iframe";
506     return null;
509 function element_get_operation_label (element, op_name, suffix) {
510     var target_label = element_get_load_target_label(element);
511     if (target_label != null)
512         target_label = " " + target_label;
513     else
514         target_label = "";
516     if (suffix != null)
517         suffix = " " + suffix;
518     else
519         suffix = "";
521     return op_name + target_label + suffix + ":";
525 function browser_element_copy (buffer, elem) {
526     var spec;
527     try {
528        spec = load_spec(elem);
529     } catch (e) {}
530     var text = null;
531     if (typeof elem == "string" || elem instanceof String)
532         text = elem;
533     else if (spec)
534         text = load_spec_uri_string(spec);
535     else  {
536         if (!(elem instanceof Ci.nsIDOMNode))
537             throw interactive_error("Element has no associated text to copy.");
538         switch (elem.localName) {
539         case "INPUT":
540         case "TEXTAREA":
541             text = elem.value;
542             break;
543         case "SELECT":
544             if (elem.selectedIndex >= 0)
545                 text = elem.item(elem.selectedIndex).text;
546             break;
547         default:
548             text = elem.textContent;
549             break;
550         }
551     }
552     browser_set_element_focus(buffer, elem);
553     writeToClipboard(text);
554     buffer.window.minibuffer.message("Copied: " + text);
558 define_variable("view_source_use_external_editor", false,
559     "When true, the `view-source' command will send its document to "+
560     "your external editor.");
562 define_variable("view_source_function", null,
563     "May be set to a user-defined function for viewing source code. "+
564     "The function should accept an nsILocalFile of the filename as "+
565     "its one positional argument, and it will also be called with "+
566     "the keyword `$temporary', whose value will be true if the file "+
567     "is considered temporary, and therefore the function must take "+
568     "responsibility for deleting it.");
570 function browser_object_view_source (buffer, target, elem) {
571     if (view_source_use_external_editor || view_source_function) {
572         var spec = load_spec(elem);
574         let [file, temp] = yield download_as_temporary(spec,
575                                                        $buffer = buffer,
576                                                        $action = "View source");
577         if (view_source_use_external_editor)
578             yield open_file_with_external_editor(file, $temporary = temp);
579         else
580             yield view_source_function(file, $temporary = temp);
581         return;
582     }
584     var win = null;
585     var window = buffer.window;
586     if (elem.localName) {
587         switch (elem.localName.toLowerCase()) {
588         case "frame": case "iframe":
589             win = elem.contentWindow;
590             break;
591         case "math":
592             view_mathml_source(window, charset, elem);
593             return;
594         default:
595             throw new Error("Invalid browser element");
596         }
597     } else
598         win = elem;
599     win.focus();
601     var url_s = win.location.href;
602     if (url_s.substring (0,12) != "view-source:") {
603         try {
604             browser_object_follow(buffer, target, "view-source:" + url_s);
605         } catch(e) { dump_error(e); }
606     } else {
607         try {
608             browser_object_follow(buffer, target, url_s.replace(/^view-source\:/, ''));
609         } catch(e) { dump_error(e); }
610     }
613 function view_source (I, target) {
614     I.target = target;
615     if (target == null)
616         target = OPEN_CURRENT_BUFFER;
617     var element = yield read_browser_object(I);
618     yield browser_object_view_source(I.buffer, target, element);
621 function view_source_new_buffer (I) {
622     yield view_source(I, OPEN_NEW_BUFFER);
625 function view_source_new_window (I) {
626     yield view_source(I, OPEN_NEW_WINDOW);
630 function browser_element_shell_command (buffer, elem, command, cwd) {
631     var spec = load_spec(elem);
632     yield download_as_temporary(spec,
633                                 $buffer = buffer,
634                                 $shell_command = command,
635                                 $shell_command_cwd = cwd);
638 provide("element");