whitespace
[conkeror.git] / modules / element.js
blob4c8042b1cdf6f6408035a6a07ac4a374fc541408
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 "+
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'] | "+
143         "//svg:a"),
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);
160     },
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();
168                 // trim spaces
169                 url = url.replace(/^\s*|\s*$/,"");
170                 // add http:// if needed
171                 if (url.match(/^[^:]+\./)) {
172                         url = "http://" + url;
173                 }
174         try {
175             return make_uri(url).spec;
176         } catch (e) {
177             throw new interactive_error("error: malformed url: "+url);
178         }
179     });
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(
185             $prompt = prompt,
186             $history = I.command.name+"/file",
187             $initial_value = I.local.cwd.path);
188         yield co_return(result);
189     },
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(
197             $buffer = I.buffer,
198             $prompt = prompt,
199             $hint_xpath_expression = "//img[@alt] | //xhtml:img[@alt]");
200         yield co_return(result.alt);
201     },
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(
209             $buffer = I.buffer,
210             $prompt = prompt,
211             $hint_xpath_expression = "//*[@title] | //xhtml:*[@title]");
212         yield co_return(result.title);
213     },
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(
222             $buffer = I.buffer,
223             $prompt = prompt,
224             $hint_xpath_expression = "//img[@alt] | //*[@title] | //xhtml:img[@alt] | //xhtml:*[@title]");
225         yield co_return(result.title ? result.title : result.alt);
226     },
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(/http:[^\s>"]*/g)
235             .filter(remove_duplicates_filter());
236         var completer = prefix_completer($completions = completions);
237         var result = yield I.buffer.window.minibuffer.read(
238             $prompt = prompt,
239             $completer = completer,
240             $initial_value = null,
241             $auto_complete = "url",
242             $select,
243             $match_required = false);
244         yield co_return(result);
245     },
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         var up = compute_url_up_path(I.buffer.current_uri.spec);
252         return I.buffer.current_uri.resolve(up);
253     });
255 define_browser_object_class("focused-element",
256     "Browser object which returns the focused element.",
257     function (I, prompt) { return I.buffer.focused_element; });
259 define_browser_object_class("dom-node", null,
260     xpath_browser_object_handler("//* | //xhtml:*"),
261     $hint = "select DOM node");
263 define_browser_object_class("fragment-link",
264     "Browser object class which returns a link to the specified fragment of a page",
265     function (I, prompt) {
266         var elem = yield I.buffer.window.minibuffer.read_hinted_element(
267             $buffer = I.buffer,
268             $prompt = prompt,
269             $hint_xpath_expression = "//*[@id] | //a[@name] | //xhtml:*[@id] | //xhtml:a[@name]");
270         yield co_return(page_fragment_load_spec(elem));
271     },
272     $hint = "select element to link to");
274 interactive("browser-object-text",
275     "Composable browser object which returns the text of another object.",
276     function (I) {
277         // our job here is to modify the interactive context.
278         // set I.browser_object to a browser_object which calls the
279         // original one, then returns its text.
280         var b = I.browser_object;
281         I.browser_object = function (I) {
282             I.browser_object = b;
283             var e = yield read_browser_object(I);
284             if (e instanceof Ci.nsIDOMHTMLImageElement)
285                 yield co_return(e.getAttribute("alt"));
286             yield co_return(e.textContent);
287         }
288     },
289     $prefix);
291 function read_browser_object (I) {
292     var browser_object = I.browser_object;
293     if (browser_object === undefined)
294         throw interactive_error("No browser object");
296     var result;
297     // literals cannot be overridden
298     if (browser_object instanceof Function) {
299         result = yield browser_object(I);
300         yield co_return(result);
301     }
302     if (! (browser_object instanceof browser_object_class))
303         yield co_return(browser_object);
305     var prompt = I.command.prompt;
306     if (! prompt) {
307         prompt = I.command.name.split(/-|_/).join(" ");
308         prompt = prompt[0].toUpperCase() + prompt.substring(1);
309     }
310     if (I.target != null)
311         prompt += TARGET_PROMPTS[I.target];
312     if (browser_object.hint)
313         prompt += " (" + browser_object.hint + ")";
314     prompt += ":";
316     result = yield browser_object.handler.call(null, I, prompt);
317     yield co_return(result);
322  * This is a simple wrapper function that sets focus to elem, and
323  * bypasses the automatic focus prevention system, which might
324  * otherwise prevent this from happening.
325  */
326 function browser_set_element_focus (buffer, elem, prevent_scroll) {
327     if (!element_dom_node_or_window_p(elem))
328         return;
329     if (! elem.focus)
330         return;
331     if (prevent_scroll)
332         set_focus_no_scroll(buffer.window, elem);
333     else
334         elem.focus();
337 function browser_element_focus (buffer, elem) {
338     if (!element_dom_node_or_window_p(elem))
339         return;
341     if (elem instanceof Ci.nsIDOMXULTextBoxElement)
342         elem = elem.wrappedJSObject.inputField; // focus the input field
344     browser_set_element_focus(buffer, elem);
345     if (elem instanceof Ci.nsIDOMWindow)
346         return;
348     // If it is not a window, it must be an HTML element
349     var x = 0;
350     var y = 0;
351     if (elem instanceof Ci.nsIDOMHTMLFrameElement ||
352         elem instanceof Ci.nsIDOMHTMLIFrameElement)
353     {
354         elem.contentWindow.focus();
355         return;
356     }
357     if (elem instanceof Ci.nsIDOMHTMLAreaElement) {
358         var coords = elem.getAttribute("coords").split(",");
359         x = Number(coords[0]);
360         y = Number(coords[1]);
361     }
363     var doc = elem.ownerDocument;
364     var evt = doc.createEvent("MouseEvents");
366     evt.initMouseEvent("mouseover", true, true, doc.defaultView, 1, x, y, 0, 0, 0, 0, 0, 0, 0, null);
367     elem.dispatchEvent(evt);
370 function browser_object_follow (buffer, target, elem) {
371     // XXX: would be better to let nsILocalFile objects be load_specs
372     if (elem instanceof Ci.nsILocalFile)
373         elem = elem.path;
375     var e;
376     if (elem instanceof load_spec)
377         e = load_spec_element(elem);
378     if (! e)
379         e = elem;
381     browser_set_element_focus(buffer, e, true /* no scroll */);
383     var no_click = (((elem instanceof load_spec) &&
384                      load_spec_forced_charset(elem)) ||
385                     (e instanceof load_spec) ||
386                     (e instanceof Ci.nsIDOMWindow) ||
387                     (e instanceof Ci.nsIDOMHTMLFrameElement) ||
388                     (e instanceof Ci.nsIDOMHTMLIFrameElement) ||
389                     (e instanceof Ci.nsIDOMHTMLLinkElement) ||
390                     (e instanceof Ci.nsIDOMHTMLImageElement &&
391                      !e.hasAttribute("onmousedown") && !e.hasAttribute("onclick")));
393     if (target == FOLLOW_DEFAULT && !no_click) {
394         var x = 1, y = 1;
395         if (e instanceof Ci.nsIDOMHTMLAreaElement) {
396             var coords = e.getAttribute("coords").split(",");
397             if (coords.length >= 2) {
398                 x = Number(coords[0]) + 1;
399                 y = Number(coords[1]) + 1;
400             }
401         }
402         dom_node_click(e, x, y);
403         return;
404     }
406     var spec = load_spec(elem);
408     if (load_spec_uri_string(spec).match(/^\s*javascript:/)) {
409         // it is nonsensical to follow a javascript url in a different
410         // buffer or window
411         target = FOLLOW_DEFAULT;
412     } else if (!(buffer instanceof content_buffer) &&
413         (target == FOLLOW_CURRENT_FRAME ||
414          target == FOLLOW_DEFAULT ||
415          target == OPEN_CURRENT_BUFFER))
416     {
417         target = OPEN_NEW_BUFFER;
418     }
420     switch (target) {
421     case FOLLOW_CURRENT_FRAME:
422         var current_frame = load_spec_source_frame(spec);
423         if (current_frame && current_frame != buffer.top_frame) {
424             var target_obj = get_web_navigation_for_frame(current_frame);
425             apply_load_spec(target_obj, spec);
426             break;
427         }
428     case FOLLOW_DEFAULT:
429     case OPEN_CURRENT_BUFFER:
430         buffer.load(spec);
431         break;
432     case OPEN_NEW_WINDOW:
433     case OPEN_NEW_BUFFER:
434     case OPEN_NEW_BUFFER_BACKGROUND:
435         create_buffer(buffer.window,
436                       buffer_creator(content_buffer,
437                                      $opener = buffer,
438                                      $load = spec),
439                       target);
440     }
444  * Follow a link-like element by generating fake mouse events.
445  */
446 function dom_node_click (elem, x, y) {
447     var doc = elem.ownerDocument;
448     var view = doc.defaultView;
450     var evt = doc.createEvent("MouseEvents");
451     evt.initMouseEvent("mousedown", true, true, view, 1, x, y, 0, 0, /*ctrl*/ 0, /*event.altKey*/0,
452                        /*event.shiftKey*/ 0, /*event.metaKey*/ 0, 0, null);
453     elem.dispatchEvent(evt);
455     evt = doc.createEvent("MouseEvents");
456     evt.initMouseEvent("click", true, true, view, 1, x, y, 0, 0, /*ctrl*/ 0, /*event.altKey*/0,
457                        /*event.shiftKey*/ 0, /*event.metaKey*/ 0, 0, null);
458     elem.dispatchEvent(evt);
460     evt = doc.createEvent("MouseEvents");
461     evt.initMouseEvent("mouseup", true, true, view, 1, x, y, 0, 0, /*ctrl*/ 0, /*event.altKey*/0,
462                        /*event.shiftKey*/ 0, /*event.metaKey*/ 0, 0, null);
463     elem.dispatchEvent(evt);
467 function follow (I, target) {
468     if (target == null)
469         target = FOLLOW_DEFAULT;
470     I.target = target;
471     if (target == OPEN_CURRENT_BUFFER)
472         check_buffer(I.buffer, content_buffer);
473     var element = yield read_browser_object(I);
474     try {
475         element = load_spec(element);
476         if (I.forced_charset)
477             element.forced_charset = I.forced_charset;
478     } catch (e) {}
479     browser_object_follow(I.buffer, target, element);
482 function follow_new_buffer (I) {
483     yield follow(I, OPEN_NEW_BUFFER);
486 function follow_new_buffer_background (I) {
487     yield follow(I, OPEN_NEW_BUFFER_BACKGROUND);
490 function follow_new_window (I) {
491     yield follow(I, OPEN_NEW_WINDOW);
494 function follow_current_frame (I) {
495     yield follow(I, FOLLOW_CURRENT_FRAME);
498 function follow_current_buffer (I) {
499     yield follow(I, OPEN_CURRENT_BUFFER);
503 function element_get_load_target_label (element) {
504     if (element instanceof Ci.nsIDOMWindow)
505         return "page";
506     if (element instanceof Ci.nsIDOMHTMLFrameElement)
507         return "frame";
508     if (element instanceof Ci.nsIDOMHTMLIFrameElement)
509         return "iframe";
510     return null;
513 function element_get_operation_label (element, op_name, suffix) {
514     var target_label = element_get_load_target_label(element);
515     if (target_label != null)
516         target_label = " " + target_label;
517     else
518         target_label = "";
520     if (suffix != null)
521         suffix = " " + suffix;
522     else
523         suffix = "";
525     return op_name + target_label + suffix + ":";
529 function browser_element_copy (buffer, elem) {
530     var spec;
531     try {
532        spec = load_spec(elem);
533     } catch (e) {}
534     var text = null;
535     if (typeof elem == "string" || elem instanceof String)
536         text = elem;
537     else if (spec)
538         text = load_spec_uri_string(spec);
539     else  {
540         if (!(elem instanceof Ci.nsIDOMNode))
541             throw interactive_error("Element has no associated text to copy.");
542         switch (elem.localName) {
543         case "INPUT":
544         case "TEXTAREA":
545             text = elem.value;
546             break;
547         case "SELECT":
548             if (elem.selectedIndex >= 0)
549                 text = elem.item(elem.selectedIndex).text;
550             break;
551         default:
552             text = elem.textContent;
553             break;
554         }
555     }
556     browser_set_element_focus(buffer, elem);
557     writeToClipboard(text);
558     buffer.window.minibuffer.message("Copied: " + text);
562 define_variable("view_source_use_external_editor", false,
563     "When true, the `view-source' command will send its document to "+
564     "your external editor.");
566 define_variable("view_source_function", null,
567     "May be set to a user-defined function for viewing source code. "+
568     "The function should accept an nsILocalFile of the filename as "+
569     "its one positional argument, and it will also be called with "+
570     "the keyword `$temporary', whose value will be true if the file "+
571     "is considered temporary, and therefore the function must take "+
572     "responsibility for deleting it.");
574 function browser_object_view_source (buffer, target, elem) {
575     if (view_source_use_external_editor || view_source_function) {
576         var spec = load_spec(elem);
578         let [file, temp] = yield download_as_temporary(spec,
579                                                        $buffer = buffer,
580                                                        $action = "View source");
581         if (view_source_use_external_editor)
582             yield open_file_with_external_editor(file, $temporary = temp);
583         else
584             yield view_source_function(file, $temporary = temp);
585         return;
586     }
588     var win = null;
589     var window = buffer.window;
590     if (elem.localName) {
591         switch (elem.localName.toLowerCase()) {
592         case "frame": case "iframe":
593             win = elem.contentWindow;
594             break;
595         case "math":
596             view_mathml_source(window, charset, elem);
597             return;
598         default:
599             throw new Error("Invalid browser element");
600         }
601     } else
602         win = elem;
603     win.focus();
605     var url_s = win.location.href;
606     if (url_s.substring (0,12) != "view-source:") {
607         try {
608             browser_object_follow(buffer, target, "view-source:" + url_s);
609         } catch(e) { dump_error(e); }
610     } else {
611         try {
612             browser_object_follow(buffer, target, url_s.replace(/^view-source\:/, ''));
613         } catch(e) { dump_error(e); }
614     }
617 function view_source (I, target) {
618     I.target = target;
619     if (target == null)
620         target = OPEN_CURRENT_BUFFER;
621     var element = yield read_browser_object(I);
622     yield browser_object_view_source(I.buffer, target, element);
625 function view_source_new_buffer (I) {
626     yield view_source(I, OPEN_NEW_BUFFER);
629 function view_source_new_window (I) {
630     yield view_source(I, OPEN_NEW_WINDOW);
634 function browser_element_shell_command (buffer, elem, command, cwd) {
635     var spec = load_spec(elem);
636     yield download_as_temporary(spec,
637                                 $buffer = buffer,
638                                 $shell_command = command,
639                                 $shell_command_cwd = cwd);
642 provide("element");