modify_region: more control for point placement
[conkeror.git] / modules / element.js
bloba3d8b3e9d190a82b22461e0eb08fbe2a327d2462
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     var result;
290     // literals cannot be overridden
291     if (browser_object instanceof Function) {
292         result = yield browser_object(I);
293         yield co_return(result);
294     }
295     if (! (browser_object instanceof browser_object_class))
296         yield co_return(browser_object);
298     var prompt = I.command.prompt;
299     if (! prompt) {
300         prompt = I.command.name.split(/-|_/).join(" ");
301         prompt = prompt[0].toUpperCase() + prompt.substring(1);
302     }
303     if (I.target != null)
304         prompt += TARGET_PROMPTS[I.target];
305     if (browser_object.hint)
306         prompt += " (" + browser_object.hint + ")";
307     prompt += ":";
309     result = yield browser_object.handler.call(null, I, prompt);
310     yield co_return(result);
315  * This is a simple wrapper function that sets focus to elem, and
316  * bypasses the automatic focus prevention system, which might
317  * otherwise prevent this from happening.
318  */
319 function browser_set_element_focus (buffer, elem, prevent_scroll) {
320     if (!element_dom_node_or_window_p(elem))
321         return;
322     if (! elem.focus)
323         return;
324     if (prevent_scroll)
325         set_focus_no_scroll(buffer.window, elem);
326     else
327         elem.focus();
330 function browser_element_focus (buffer, elem) {
331     if (!element_dom_node_or_window_p(elem))
332         return;
334     if (elem instanceof Ci.nsIDOMXULTextBoxElement)
335         elem = elem.wrappedJSObject.inputField; // focus the input field
337     browser_set_element_focus(buffer, elem);
338     if (elem instanceof Ci.nsIDOMWindow)
339         return;
341     // If it is not a window, it must be an HTML element
342     var x = 0;
343     var y = 0;
344     if (elem instanceof Ci.nsIDOMHTMLFrameElement ||
345         elem instanceof Ci.nsIDOMHTMLIFrameElement)
346     {
347         elem.contentWindow.focus();
348         return;
349     }
350     if (elem instanceof Ci.nsIDOMHTMLAreaElement) {
351         var coords = elem.getAttribute("coords").split(",");
352         x = Number(coords[0]);
353         y = Number(coords[1]);
354     }
356     var doc = elem.ownerDocument;
357     var evt = doc.createEvent("MouseEvents");
359     evt.initMouseEvent("mouseover", true, true, doc.defaultView, 1, x, y, 0, 0, 0, 0, 0, 0, 0, null);
360     elem.dispatchEvent(evt);
363 function browser_object_follow (buffer, target, elem) {
364     // XXX: would be better to let nsILocalFile objects be load_specs
365     if (elem instanceof Ci.nsILocalFile)
366         elem = elem.path;
368     var e;
369     if (elem instanceof load_spec)
370         e = load_spec_element(elem);
371     if (! e)
372         e = elem;
374     browser_set_element_focus(buffer, e, true /* no scroll */);
376     var no_click = (((elem instanceof load_spec) &&
377                      load_spec_forced_charset(elem)) ||
378                     (e instanceof load_spec) ||
379                     (e instanceof Ci.nsIDOMWindow) ||
380                     (e instanceof Ci.nsIDOMHTMLFrameElement) ||
381                     (e instanceof Ci.nsIDOMHTMLIFrameElement) ||
382                     (e instanceof Ci.nsIDOMHTMLLinkElement) ||
383                     (e instanceof Ci.nsIDOMHTMLImageElement &&
384                      !e.hasAttribute("onmousedown") && !e.hasAttribute("onclick")));
386     if (target == FOLLOW_DEFAULT && !no_click) {
387         var x = 1, y = 1;
388         if (e instanceof Ci.nsIDOMHTMLAreaElement) {
389             var coords = e.getAttribute("coords").split(",");
390             if (coords.length >= 2) {
391                 x = Number(coords[0]) + 1;
392                 y = Number(coords[1]) + 1;
393             }
394         }
395         dom_node_click(e, x, y);
396         return;
397     }
399     var spec = load_spec(elem);
401     if (load_spec_uri_string(spec).match(/^\s*javascript:/)) {
402         // it is nonsensical to follow a javascript url in a different
403         // buffer or window
404         target = FOLLOW_DEFAULT;
405     } else if (!(buffer instanceof content_buffer) &&
406         (target == FOLLOW_CURRENT_FRAME ||
407          target == FOLLOW_DEFAULT ||
408          target == OPEN_CURRENT_BUFFER))
409     {
410         target = OPEN_NEW_BUFFER;
411     }
413     switch (target) {
414     case FOLLOW_CURRENT_FRAME:
415         var current_frame = load_spec_source_frame(spec);
416         if (current_frame && current_frame != buffer.top_frame) {
417             var target_obj = get_web_navigation_for_frame(current_frame);
418             apply_load_spec(target_obj, spec);
419             break;
420         }
421     case FOLLOW_DEFAULT:
422     case OPEN_CURRENT_BUFFER:
423         buffer.load(spec);
424         break;
425     case OPEN_NEW_WINDOW:
426     case OPEN_NEW_BUFFER:
427     case OPEN_NEW_BUFFER_BACKGROUND:
428         create_buffer(buffer.window,
429                       buffer_creator(content_buffer,
430                                      $opener = buffer,
431                                      $load = spec),
432                       target);
433     }
437  * Follow a link-like element by generating fake mouse events.
438  */
439 function dom_node_click (elem, x, y) {
440     var doc = elem.ownerDocument;
441     var view = doc.defaultView;
443     var evt = doc.createEvent("MouseEvents");
444     evt.initMouseEvent("mousedown", true, true, view, 1, x, y, 0, 0, /*ctrl*/ 0, /*event.altKey*/0,
445                        /*event.shiftKey*/ 0, /*event.metaKey*/ 0, 0, null);
446     elem.dispatchEvent(evt);
448     evt = doc.createEvent("MouseEvents");
449     evt.initMouseEvent("click", true, true, view, 1, x, y, 0, 0, /*ctrl*/ 0, /*event.altKey*/0,
450                        /*event.shiftKey*/ 0, /*event.metaKey*/ 0, 0, null);
451     elem.dispatchEvent(evt);
453     evt = doc.createEvent("MouseEvents");
454     evt.initMouseEvent("mouseup", true, true, view, 1, x, y, 0, 0, /*ctrl*/ 0, /*event.altKey*/0,
455                        /*event.shiftKey*/ 0, /*event.metaKey*/ 0, 0, null);
456     elem.dispatchEvent(evt);
460 function follow (I, target) {
461     if (target == null)
462         target = FOLLOW_DEFAULT;
463     I.target = target;
464     if (target == OPEN_CURRENT_BUFFER)
465         check_buffer(I.buffer, content_buffer);
466     var element = yield read_browser_object(I);
467     try {
468         element = load_spec(element);
469         if (I.forced_charset)
470             element.forced_charset = I.forced_charset;
471     } catch (e) {}
472     browser_object_follow(I.buffer, target, element);
475 function follow_new_buffer (I) {
476     yield follow(I, OPEN_NEW_BUFFER);
479 function follow_new_buffer_background (I) {
480     yield follow(I, OPEN_NEW_BUFFER_BACKGROUND);
483 function follow_new_window (I) {
484     yield follow(I, OPEN_NEW_WINDOW);
487 function follow_current_frame (I) {
488     yield follow(I, FOLLOW_CURRENT_FRAME);
491 function follow_current_buffer (I) {
492     yield follow(I, OPEN_CURRENT_BUFFER);
496 function element_get_load_target_label (element) {
497     if (element instanceof Ci.nsIDOMWindow)
498         return "page";
499     if (element instanceof Ci.nsIDOMHTMLFrameElement)
500         return "frame";
501     if (element instanceof Ci.nsIDOMHTMLIFrameElement)
502         return "iframe";
503     return null;
506 function element_get_operation_label (element, op_name, suffix) {
507     var target_label = element_get_load_target_label(element);
508     if (target_label != null)
509         target_label = " " + target_label;
510     else
511         target_label = "";
513     if (suffix != null)
514         suffix = " " + suffix;
515     else
516         suffix = "";
518     return op_name + target_label + suffix + ":";
522 function browser_element_copy (buffer, elem) {
523     var spec;
524     try {
525        spec = load_spec(elem);
526     } catch (e) {}
527     var text = null;
528     if (typeof elem == "string" || elem instanceof String)
529         text = elem;
530     else if (spec)
531         text = load_spec_uri_string(spec);
532     else  {
533         if (!(elem instanceof Ci.nsIDOMNode))
534             throw interactive_error("Element has no associated text to copy.");
535         switch (elem.localName) {
536         case "INPUT":
537         case "TEXTAREA":
538             text = elem.value;
539             break;
540         case "SELECT":
541             if (elem.selectedIndex >= 0)
542                 text = elem.item(elem.selectedIndex).text;
543             break;
544         default:
545             text = elem.textContent;
546             break;
547         }
548     }
549     browser_set_element_focus(buffer, elem);
550     writeToClipboard(text);
551     buffer.window.minibuffer.message("Copied: " + text);
555 define_variable("view_source_use_external_editor", false,
556     "When true, the `view-source' command will send its document to "+
557     "your external editor.");
559 define_variable("view_source_function", null,
560     "May be set to a user-defined function for viewing source code. "+
561     "The function should accept an nsILocalFile of the filename as "+
562     "its one positional argument, and it will also be called with "+
563     "the keyword `$temporary', whose value will be true if the file "+
564     "is considered temporary, and therefore the function must take "+
565     "responsibility for deleting it.");
567 function browser_object_view_source (buffer, target, elem) {
568     if (view_source_use_external_editor || view_source_function) {
569         var spec = load_spec(elem);
571         let [file, temp] = yield download_as_temporary(spec,
572                                                        $buffer = buffer,
573                                                        $action = "View source");
574         if (view_source_use_external_editor)
575             yield open_file_with_external_editor(file, $temporary = temp);
576         else
577             yield view_source_function(file, $temporary = temp);
578         return;
579     }
581     var win = null;
582     var window = buffer.window;
583     if (elem.localName) {
584         switch (elem.localName.toLowerCase()) {
585         case "frame": case "iframe":
586             win = elem.contentWindow;
587             break;
588         case "math":
589             view_mathml_source(window, charset, elem);
590             return;
591         default:
592             throw new Error("Invalid browser element");
593         }
594     } else
595         win = elem;
596     win.focus();
598     var url_s = win.location.href;
599     if (url_s.substring (0,12) != "view-source:") {
600         try {
601             browser_object_follow(buffer, target, "view-source:" + url_s);
602         } catch(e) { dump_error(e); }
603     } else {
604         try {
605             browser_object_follow(buffer, target, url_s.replace(/^view-source\:/, ''));
606         } catch(e) { dump_error(e); }
607     }
610 function view_source (I, target) {
611     I.target = target;
612     if (target == null)
613         target = OPEN_CURRENT_BUFFER;
614     var element = yield read_browser_object(I);
615     yield browser_object_view_source(I.buffer, target, element);
618 function view_source_new_buffer (I) {
619     yield view_source(I, OPEN_NEW_BUFFER);
622 function view_source_new_window (I) {
623     yield view_source(I, OPEN_NEW_WINDOW);
627 function browser_element_shell_command (buffer, elem, command, cwd) {
628     var spec = load_spec(elem);
629     yield download_as_temporary(spec,
630                                 $buffer = buffer,
631                                 $shell_command = command,
632                                 $shell_command_cwd = cwd);
635 provide("element");