fix focus problem http://bugs.conkeror.org/issue263
[conkeror.git] / modules / element.js
blob7cc6d923e13947b5d2aa1df8fe876b1dca10f939
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'] | " +
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'] | " +
137         "//xhtml:input[not(@type='hidden')] | //xhtml:a | //xhtml:area | //xhtml:iframe | //xhtml:textarea | //xhtml:button | //xhtml:select | " +
138         "//xhtml:*[@contenteditable = 'true']"),
139     $hint = "select link");
141 define_browser_object_class("mathml",
142     "Browser object class for selecting a MathML node via hinting.",
143     xpath_browser_object_handler("//m:math"),
144     $hint = "select MathML element");
146 define_browser_object_class("top",
147     "Browser object class which returns the top frame of the document.",
148     function (I, prompt) { return I.buffer.top_frame; });
150 define_browser_object_class("url",
151     "Browser object class which prompts the user for an url or webjump.",
152     function (I, prompt) {
153         var result = yield I.buffer.window.minibuffer.read_url($prompt = prompt);
154         yield co_return(result);
155     },
156     $hint = "enter URL/webjump");
158 define_browser_object_class("paste-url",
159     "Browser object which reads an url from the X Primary Selection, "+
160     "falling back on the clipboard for operating systems which lack one.",
161     function (I, prompt) {
162                 var url = read_from_x_primary_selection();
163                 // trim spaces
164                 url = url.replace(/^\s*|\s*$/,"");
165                 // add http:// if needed
166                 if (url.match(/^[^:]+\./)) {
167                         url = "http://" + url;
168                 }
169         try {
170             return make_uri(url).spec;
171         } catch (e) {
172             throw new interactive_error("error: malformed url: "+url);
173         }
174     });
176 define_browser_object_class("file",
177     "Browser object which prompts for a file name.",
178     function (I, prompt) {
179         var result = yield I.buffer.window.minibuffer.read_file(
180             $prompt = prompt,
181             $history = I.command.name+"/file",
182             $initial_value = I.local.cwd.path);
183         yield co_return(result);
184     },
185     $hint = "enter file name");
187 define_browser_object_class("alt",
188     "Browser object class which returns the alt text of an html:img, "+
189     "selected via hinting",
190     function (I, prompt) {
191         var result = yield I.buffer.window.minibuffer.read_hinted_element(
192             $buffer = I.buffer,
193             $prompt = prompt,
194             $hint_xpath_expression = "//img[@alt] | //xhtml:img[@alt]");
195         yield co_return(result.alt);
196     },
197     $hint = "select image for alt-text");
199 define_browser_object_class("title",
200     "Browser object class which returns the title attribute of an element, "+
201     "selected via hinting",
202     function (I, prompt) {
203         var result = yield I.buffer.window.minibuffer.read_hinted_element(
204             $buffer = I.buffer,
205             $prompt = prompt,
206             $hint_xpath_expression = "//*[@title] | //xhtml:*[@title]");
207         yield co_return(result.title);
208     },
209     $hint = "select element for title attribute");
211 define_browser_object_class("title-or-alt",
212     "Browser object which is the union of browser-object-alt and "+
213     "browser-object-title, with title having higher precedence in "+
214     "the case of an element that has both.",
215     function (I, prompt) {
216         var result = yield I.buffer.window.minibuffer.read_hinted_element(
217             $buffer = I.buffer,
218             $prompt = prompt,
219             $hint_xpath_expression = "//img[@alt] | //*[@title] | //xhtml:img[@alt] | //xhtml:*[@title]");
220         yield co_return(result.title ? result.title : result.alt);
221     },
222     $hint = "select element for title or alt-text");
224 define_browser_object_class("scrape-url",
225     "Browser object which lets the user choose an url from a list of "+
226     "urls scraped from the source code of the document.",
227     function (I, prompt) {
228         var completions = I.buffer.document.documentElement.innerHTML
229             .match(/http:[^\s>"]*/g)
230             .filter(remove_duplicates_filter());
231         var completer = prefix_completer($completions = completions);
232         var result = yield I.buffer.window.minibuffer.read(
233             $prompt = prompt,
234             $completer = completer,
235             $initial_value = null,
236             $auto_complete = "url",
237             $select,
238             $match_required = false);
239         yield co_return(result);
240     },
241     $hint = "choose scraped URL");
243 define_browser_object_class("up-url",
244     "Browser object which returns the url one level above the current one.",
245     function (I, prompt) {
246         var up = compute_url_up_path(I.buffer.current_uri.spec);
247         return I.buffer.current_uri.resolve(up);
248     });
250 define_browser_object_class("focused-element",
251     "Browser object which returns the focused element.",
252     function (I, prompt) { return I.buffer.focused_element; });
254 define_browser_object_class("dom-node", null,
255     xpath_browser_object_handler("//* | //xhtml:*"),
256     $hint = "select DOM node");
258 define_browser_object_class("fragment-link",
259     "Browser object class which returns a link to the specified fragment of a page",
260     function (I, prompt) {
261         var elem = yield I.buffer.window.minibuffer.read_hinted_element(
262             $buffer = I.buffer,
263             $prompt = prompt,
264             $hint_xpath_expression = "//*[@id] | //a[@name] | //xhtml:*[@id] | //xhtml:a[@name]");
265         yield co_return(page_fragment_load_spec(elem));
266     },
267     $hint = "select element to link to");
269 interactive("browser-object-text",
270     "Composable browser object which returns the text of another object.",
271     function (I) {
272         // our job here is to modify the interactive context.
273         // set I.browser_object to a browser_object which calls the
274         // original one, then returns its text.
275         var b = I.browser_object;
276         I.browser_object = function (I) {
277             I.browser_object = b;
278             var e = yield read_browser_object(I);
279             if (e instanceof Ci.nsIDOMHTMLImageElement)
280                 yield co_return(e.getAttribute("alt"));
281             yield co_return(e.textContent);
282         }
283     },
284     $prefix);
286 function read_browser_object (I) {
287     var browser_object = I.browser_object;
288     var result;
289     // literals cannot be overridden
290     if (browser_object instanceof Function) {
291         result = yield browser_object(I);
292         yield co_return(result);
293     }
294     if (! (browser_object instanceof browser_object_class))
295         yield co_return(browser_object);
297     var prompt = I.command.prompt;
298     if (! prompt) {
299         prompt = I.command.name.split(/-|_/).join(" ");
300         prompt = prompt[0].toUpperCase() + prompt.substring(1);
301     }
302     if (I.target != null)
303         prompt += TARGET_PROMPTS[I.target];
304     if (browser_object.hint)
305         prompt += " (" + browser_object.hint + ")";
306     prompt += ":";
308     result = yield browser_object.handler.call(null, I, prompt);
309     yield co_return(result);
314  * This is a simple wrapper function that sets focus to elem, and
315  * bypasses the automatic focus prevention system, which might
316  * otherwise prevent this from happening.
317  */
318 function browser_set_element_focus (buffer, elem, prevent_scroll) {
319     if (!element_dom_node_or_window_p(elem))
320         return;
321     if (prevent_scroll)
322         set_focus_no_scroll(buffer.window, elem);
323     else
324         elem.focus();
327 function browser_element_focus (buffer, elem) {
328     if (!element_dom_node_or_window_p(elem))
329         return;
331     if (elem instanceof Ci.nsIDOMXULTextBoxElement)
332         elem = elem.wrappedJSObject.inputField; // focus the input field
334     browser_set_element_focus(buffer, elem);
335     if (elem instanceof Ci.nsIDOMWindow)
336         return;
338     // If it is not a window, it must be an HTML element
339     var x = 0;
340     var y = 0;
341     if (elem instanceof Ci.nsIDOMHTMLFrameElement ||
342         elem instanceof Ci.nsIDOMHTMLIFrameElement)
343     {
344         elem.contentWindow.focus();
345         return;
346     }
347     if (elem instanceof Ci.nsIDOMHTMLAreaElement) {
348         var coords = elem.getAttribute("coords").split(",");
349         x = Number(coords[0]);
350         y = Number(coords[1]);
351     }
353     var doc = elem.ownerDocument;
354     var evt = doc.createEvent("MouseEvents");
356     evt.initMouseEvent("mouseover", true, true, doc.defaultView, 1, x, y, 0, 0, 0, 0, 0, 0, 0, null);
357     elem.dispatchEvent(evt);
360 function browser_object_follow (buffer, target, elem) {
361     // XXX: would be better to let nsILocalFile objects be load_specs
362     if (elem instanceof Ci.nsILocalFile)
363         elem = elem.path;
365     var e;
366     if (elem instanceof load_spec)
367         e = load_spec_element(elem);
368     if (! e)
369         e = elem;
371     browser_set_element_focus(buffer, e, true /* no scroll */);
373     var no_click = (((elem instanceof load_spec) &&
374                      load_spec_forced_charset(elem)) ||
375                     (e instanceof load_spec) ||
376                     (e instanceof Ci.nsIDOMWindow) ||
377                     (e instanceof Ci.nsIDOMHTMLFrameElement) ||
378                     (e instanceof Ci.nsIDOMHTMLIFrameElement) ||
379                     (e instanceof Ci.nsIDOMHTMLLinkElement) ||
380                     (e instanceof Ci.nsIDOMHTMLImageElement &&
381                      !e.hasAttribute("onmousedown") && !e.hasAttribute("onclick")));
383     if (target == FOLLOW_DEFAULT && !no_click) {
384         var x = 1, y = 1;
385         if (e instanceof Ci.nsIDOMHTMLAreaElement) {
386             var coords = e.getAttribute("coords").split(",");
387             if (coords.length >= 2) {
388                 x = Number(coords[0]) + 1;
389                 y = Number(coords[1]) + 1;
390             }
391         }
392         dom_node_click(e, x, y);
393         return;
394     }
396     var spec = load_spec(elem);
398     if (load_spec_uri_string(spec).match(/^\s*javascript:/)) {
399         // it is nonsensical to follow a javascript url in a different
400         // buffer or window
401         target = FOLLOW_DEFAULT;
402     } else if (!(buffer instanceof content_buffer) &&
403         (target == FOLLOW_CURRENT_FRAME ||
404          target == FOLLOW_DEFAULT ||
405          target == OPEN_CURRENT_BUFFER))
406     {
407         target = OPEN_NEW_BUFFER;
408     }
410     switch (target) {
411     case FOLLOW_CURRENT_FRAME:
412         var current_frame = load_spec_source_frame(spec);
413         if (current_frame && current_frame != buffer.top_frame) {
414             var target_obj = get_web_navigation_for_frame(current_frame);
415             apply_load_spec(target_obj, spec);
416             break;
417         }
418     case FOLLOW_DEFAULT:
419     case OPEN_CURRENT_BUFFER:
420         buffer.load(spec);
421         break;
422     case OPEN_NEW_WINDOW:
423     case OPEN_NEW_BUFFER:
424     case OPEN_NEW_BUFFER_BACKGROUND:
425         create_buffer(buffer.window,
426                       buffer_creator(content_buffer,
427                                      $opener = buffer,
428                                      $load = spec),
429                       target);
430     }
434  * Follow a link-like element by generating fake mouse events.
435  */
436 function dom_node_click (elem, x, y) {
437     var doc = elem.ownerDocument;
438     var view = doc.defaultView;
440     var evt = doc.createEvent("MouseEvents");
441     evt.initMouseEvent("mousedown", true, true, view, 1, x, y, 0, 0, /*ctrl*/ 0, /*event.altKey*/0,
442                        /*event.shiftKey*/ 0, /*event.metaKey*/ 0, 0, null);
443     elem.dispatchEvent(evt);
445     evt = doc.createEvent("MouseEvents");
446     evt.initMouseEvent("click", true, true, view, 1, x, y, 0, 0, /*ctrl*/ 0, /*event.altKey*/0,
447                        /*event.shiftKey*/ 0, /*event.metaKey*/ 0, 0, null);
448     elem.dispatchEvent(evt);
452 function follow (I, target) {
453     if (target == null)
454         target = FOLLOW_DEFAULT;
455     I.target = target;
456     if (target == OPEN_CURRENT_BUFFER)
457         check_buffer(I.buffer, content_buffer);
458     var element = yield read_browser_object(I);
459     try {
460         element = load_spec(element);
461         if (I.forced_charset)
462             element.forced_charset = I.forced_charset;
463     } catch (e) {}
464     browser_object_follow(I.buffer, target, element);
467 function follow_new_buffer (I) {
468     yield follow(I, OPEN_NEW_BUFFER);
471 function follow_new_buffer_background (I) {
472     yield follow(I, OPEN_NEW_BUFFER_BACKGROUND);
475 function follow_new_window (I) {
476     yield follow(I, OPEN_NEW_WINDOW);
479 function follow_current_frame (I) {
480     yield follow(I, FOLLOW_CURRENT_FRAME);
483 function follow_current_buffer (I) {
484     yield follow(I, OPEN_CURRENT_BUFFER);
488 function element_get_load_target_label (element) {
489     if (element instanceof Ci.nsIDOMWindow)
490         return "page";
491     if (element instanceof Ci.nsIDOMHTMLFrameElement)
492         return "frame";
493     if (element instanceof Ci.nsIDOMHTMLIFrameElement)
494         return "iframe";
495     return null;
498 function element_get_operation_label (element, op_name, suffix) {
499     var target_label = element_get_load_target_label(element);
500     if (target_label != null)
501         target_label = " " + target_label;
502     else
503         target_label = "";
505     if (suffix != null)
506         suffix = " " + suffix;
507     else
508         suffix = "";
510     return op_name + target_label + suffix + ":";
514 function browser_element_copy (buffer, elem) {
515     var spec;
516     try {
517        spec = load_spec(elem);
518     } catch (e) {}
519     var text = null;
520     if (typeof elem == "string" || elem instanceof String)
521         text = elem;
522     else if (spec)
523         text = load_spec_uri_string(spec);
524     else  {
525         if (!(elem instanceof Ci.nsIDOMNode))
526             throw interactive_error("Element has no associated text to copy.");
527         switch (elem.localName) {
528         case "INPUT":
529         case "TEXTAREA":
530             text = elem.value;
531             break;
532         case "SELECT":
533             if (elem.selectedIndex >= 0)
534                 text = elem.item(elem.selectedIndex).text;
535             break;
536         default:
537             text = elem.textContent;
538             break;
539         }
540     }
541     browser_set_element_focus(buffer, elem);
542     writeToClipboard(text);
543     buffer.window.minibuffer.message("Copied: " + text);
547 define_variable("view_source_use_external_editor", false,
548     "When true, the `view-source' command will send its document to "+
549     "your external editor.");
551 define_variable("view_source_function", null,
552     "May be set to a user-defined function for viewing source code. "+
553     "The function should accept an nsILocalFile of the filename as "+
554     "its one positional argument, and it will also be called with "+
555     "the keyword `$temporary', whose value will be true if the file "+
556     "is considered temporary, and therefore the function must take "+
557     "responsibility for deleting it.");
559 function browser_object_view_source (buffer, target, elem) {
560     if (view_source_use_external_editor || view_source_function) {
561         var spec = load_spec(elem);
563         let [file, temp] = yield download_as_temporary(spec,
564                                                        $buffer = buffer,
565                                                        $action = "View source");
566         if (view_source_use_external_editor)
567             yield open_file_with_external_editor(file, $temporary = temp);
568         else
569             yield view_source_function(file, $temporary = temp);
570         return;
571     }
573     var win = null;
574     var window = buffer.window;
575     if (elem.localName) {
576         switch (elem.localName.toLowerCase()) {
577         case "frame": case "iframe":
578             win = elem.contentWindow;
579             break;
580         case "math":
581             view_mathml_source(window, charset, elem);
582             return;
583         default:
584             throw new Error("Invalid browser element");
585         }
586     } else
587         win = elem;
588     win.focus();
590     var url_s = win.location.href;
591     if (url_s.substring (0,12) != "view-source:") {
592         try {
593             browser_object_follow(buffer, target, "view-source:" + url_s);
594         } catch(e) { dump_error(e); }
595     } else {
596         window.minibuffer.message ("Already viewing source");
597     }
600 function view_source (I, target) {
601     I.target = target;
602     if (target == null)
603         target = OPEN_CURRENT_BUFFER;
604     var element = yield read_browser_object(I);
605     yield browser_object_view_source(I.buffer, target, element);
608 function view_source_new_buffer (I) {
609     yield view_source(I, OPEN_NEW_BUFFER);
612 function view_source_new_window (I) {
613     yield view_source(I, OPEN_NEW_WINDOW);
617 function browser_element_shell_command (buffer, elem, command, cwd) {
618     var spec = load_spec(elem);
619     yield download_as_temporary(spec,
620                                 $buffer = buffer,
621                                 $shell_command = command,
622                                 $shell_command_cwd = cwd);
625 provide("element");